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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use tokio::sync::mpsc;

use crate::sources::parse_news_html;
use crate::state::{AppState, PackageItem};

use super::utils::{
    find_in_install, matches_any, refresh_install_details, refresh_remove_details,
    refresh_selected_details,
};

/// AUR vs official duplicate-results warning before privileged install.
mod aur_dup_warn;
/// Preflight modal opening functions for install operations.
mod preflight;

#[cfg(test)]
mod tests;

pub use aur_dup_warn::try_open_warn_aur_repo_duplicate_modal;

pub use preflight::{
    open_preflight_downgrade_modal, open_preflight_install_modal, open_preflight_remove_modal,
};

/// What: Handle `pane_next` navigation (cycles through panes).
fn handle_pane_next_navigation(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    // Desired cycle: Search -> Downgrade -> Remove -> Recent -> Search
    if app.installed_only_mode {
        match app.right_pane_focus {
            crate::state::RightPaneFocus::Downgrade => {
                // Downgrade -> Remove (stay in Install)
                app.right_pane_focus = crate::state::RightPaneFocus::Remove;
                if app.remove_state.selected().is_none() && !app.remove_list.is_empty() {
                    app.remove_state.select(Some(0));
                }
                refresh_remove_details(app, details_tx);
                return;
            }
            crate::state::RightPaneFocus::Remove => {
                // Remove -> Recent
                if app.history_state.selected().is_none() && !app.recent.is_empty() {
                    app.history_state.select(Some(0));
                }
                app.focus = crate::state::Focus::Recent;
                crate::ui::helpers::trigger_recent_preview(app, preview_tx);
                return;
            }
            crate::state::RightPaneFocus::Install => {}
        }
    }
    // Not in installed-only: Install -> Recent
    if app.history_state.selected().is_none() && !app.recent.is_empty() {
        app.history_state.select(Some(0));
    }
    app.focus = crate::state::Focus::Recent;
    crate::ui::helpers::trigger_recent_preview(app, preview_tx);
}

/// What: Handle Left arrow navigation (moves focus left).
fn handle_left_arrow_navigation(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    // In installed-only mode, follow reverse: Remove -> Downgrade -> Search
    if app.installed_only_mode {
        match app.right_pane_focus {
            crate::state::RightPaneFocus::Remove => {
                // Move to Downgrade subpane and keep Install focus
                app.right_pane_focus = crate::state::RightPaneFocus::Downgrade;
                if app.downgrade_state.selected().is_none() && !app.downgrade_list.is_empty() {
                    app.downgrade_state.select(Some(0));
                }
                super::utils::refresh_downgrade_details(app, details_tx);
            }
            crate::state::RightPaneFocus::Downgrade => {
                // Downgrade -> Search
                app.focus = crate::state::Focus::Search;
                refresh_selected_details(app, details_tx);
            }
            crate::state::RightPaneFocus::Install => {
                // Normal mode: Install -> Search
                app.focus = crate::state::Focus::Search;
                refresh_selected_details(app, details_tx);
            }
        }
    } else {
        // Normal mode: Install -> Search
        app.focus = crate::state::Focus::Search;
        refresh_selected_details(app, details_tx);
    }
}

/// What: Ensure bookmark selection is valid in news mode.
fn ensure_news_bookmark_selection(app: &mut AppState) {
    let len = app.news_bookmarks.len();
    if len == 0 {
        app.install_state.select(None);
        return;
    }
    let sel = app
        .install_state
        .selected()
        .filter(|i| *i < len)
        .unwrap_or(0);
    app.install_state.select(Some(sel));
}

/// What: Move bookmark selection up or down in news mode.
fn move_news_bookmark_selection(app: &mut AppState, down: bool) {
    ensure_news_bookmark_selection(app);
    let len = app.news_bookmarks.len();
    if len == 0 {
        return;
    }
    let current = app.install_state.selected().unwrap_or(0);
    let next = if down {
        std::cmp::min(current + 1, len.saturating_sub(1))
    } else {
        current.saturating_sub(1)
    };
    app.install_state.select(Some(next));
}

/// What: Delete the currently selected news bookmark and its cached file.
fn delete_news_bookmark_at_selection(app: &mut AppState) {
    ensure_news_bookmark_selection(app);
    let Some(sel) = app.install_state.selected() else {
        return;
    };
    if let Some(removed) = app.remove_news_bookmark_at(sel)
        && let Some(path) = removed.html_path
    {
        let _ = std::fs::remove_file(path);
    }
    // Adjust selection
    let len = app.news_bookmarks.len();
    if len == 0 {
        app.install_state.select(None);
    } else if sel >= len {
        app.install_state.select(Some(len.saturating_sub(1)));
    }
}

/// What: Load the selected news bookmark into the details pane from local cache.
fn load_news_bookmark(app: &mut AppState) {
    ensure_news_bookmark_selection(app);
    let Some(sel) = app.install_state.selected() else {
        return;
    };
    let Some(bookmark) = app.news_bookmarks.get(sel).cloned() else {
        return;
    };

    // Ensure the bookmarked item is present in results for metadata rendering
    let idx = if let Some(pos) = app
        .news_results
        .iter()
        .position(|it| it.id == bookmark.item.id)
    {
        pos
    } else {
        app.news_results.insert(0, bookmark.item.clone());
        0
    };
    app.news_selected = idx;
    app.news_list_state.select(Some(idx));

    // Load content from html if available, else fallback to cached content
    let mut content = bookmark.content.clone();
    if content.is_none()
        && let Some(path) = bookmark.html_path.as_ref()
        && let Ok(html) = std::fs::read_to_string(path)
    {
        content = Some(parse_news_html(&html));
    }
    if let Some(url) = bookmark.item.url.as_ref() {
        if let Some(ref c) = content {
            app.news_content_cache.insert(url.clone(), c.clone());
        }
        app.details.url.clone_from(url);
    } else {
        app.details.url.clear();
    }
    app.news_content = content;
    app.news_content_loading = false;
}

/// What: Handle key events inside the news bookmarks pane.
fn handle_news_bookmarks_key(ke: KeyEvent, app: &mut AppState) -> bool {
    match ke.code {
        KeyCode::Char('j') | KeyCode::Down => {
            move_news_bookmark_selection(app, true);
        }
        KeyCode::Char('k') | KeyCode::Up => {
            move_news_bookmark_selection(app, false);
        }
        code if matches_any(&ke, &app.keymap.pane_next) && code == ke.code => {
            if app.history_state.selected().is_none() && !app.news_recent_values().is_empty() {
                app.history_state.select(Some(0));
            }
            app.focus = crate::state::Focus::Recent;
        }
        KeyCode::Enter | KeyCode::Char('\n' | '\r') => {
            load_news_bookmark(app);
        }
        KeyCode::Delete => {
            delete_news_bookmark_at_selection(app);
        }
        KeyCode::Esc | KeyCode::Left => {
            app.focus = crate::state::Focus::Search;
            app.search_normal_mode = true;
        }
        KeyCode::Right => {
            app.focus = crate::state::Focus::Recent;
        }
        _ => {}
    }
    false
}

/// What: Handle Right arrow navigation (moves focus right).
fn handle_right_arrow_navigation(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    // In installed-only mode, follow: Downgrade -> Remove -> Recent; else wrap to Recent
    if app.installed_only_mode {
        match app.right_pane_focus {
            crate::state::RightPaneFocus::Downgrade => {
                app.right_pane_focus = crate::state::RightPaneFocus::Remove;
                if app.remove_state.selected().is_none() && !app.remove_list.is_empty() {
                    app.remove_state.select(Some(0));
                }
                refresh_remove_details(app, details_tx);
            }
            crate::state::RightPaneFocus::Remove => {
                // Wrap-around to Recent from rightmost subpane
                if app.history_state.selected().is_none() && !app.recent.is_empty() {
                    app.history_state.select(Some(0));
                }
                app.focus = crate::state::Focus::Recent;
                crate::ui::helpers::trigger_recent_preview(app, preview_tx);
            }
            crate::state::RightPaneFocus::Install => {
                // Normal Install subpane: wrap directly to Recent
                if app.history_state.selected().is_none() && !app.recent.is_empty() {
                    app.history_state.select(Some(0));
                }
                app.focus = crate::state::Focus::Recent;
                crate::ui::helpers::trigger_recent_preview(app, preview_tx);
            }
        }
    } else {
        // Normal mode: Install -> Recent (wrap)
        if app.history_state.selected().is_none() && !app.recent.is_empty() {
            app.history_state.select(Some(0));
        }
        app.focus = crate::state::Focus::Recent;
        crate::ui::helpers::trigger_recent_preview(app, preview_tx);
    }
}

/// What: Handle key events while the Install pane (right column) is focused.
///
/// Inputs:
/// - `ke`: Key event received from the terminal
/// - `app`: Mutable application state (selection, lists, pane focus)
/// - `details_tx`: Channel to request package details for the focused item
/// - `preview_tx`: Channel to request preview details (used for some focus changes)
/// - `_add_tx`: Channel for adding items (not used directly in Install handler)
///
/// Output:
/// - `true` to request application exit (e.g., Ctrl+C); `false` to continue.
///
/// Details:
/// - In-pane find: `/` enters find mode; typing edits the pattern; Enter jumps to next match;
///   Esc cancels. Find matches against name/description (Install) or name-only (Remove/Downgrade).
/// - Navigation: `j/k` and `Down/Up` move selection in the active subpane. Behavior adapts to
///   installed-only mode (`app.installed_only_mode`) and current `right_pane_focus`:
///   - Normal mode: selection moves in Install list only.
///   - Installed-only: selection moves in Downgrade/Remove/Install subpane depending on focus.
/// - Pane cycling: Configured `pane_next` chord cycles focus across panes. In installed-only mode
///   it cycles Search → Downgrade → Remove → Recent → Search; otherwise Search → Install → Recent.
/// - Arrow focus: Left/Right move focus between Search/Install/Recent (and subpanes when installed-only).
/// - Deletion: `Delete` (or configured `install_remove`) removes the selected entry from the active
///   list (Install/Remove/Downgrade) and updates selection and details.
/// - Clear list: Configured `install_clear` clears the respective list (or all in normal mode),
///   and resets selection.
/// - Enter:
///   - Normal mode with non-empty Install list: opens `Modal::ConfirmInstall` for batch install.
///   - Installed-only Remove focus with non-empty list: opens `Modal::ConfirmRemove`.
///   - Installed-only Downgrade focus with non-empty list: runs `downgrade` tool (or dry-run).
/// - Esc: Returns focus to Search and refreshes the selected result's details.
pub fn handle_install_key(
    ke: KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
    _add_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        return handle_news_bookmarks_key(ke, app);
    }
    if ke.code == KeyCode::Char('c') && ke.modifiers.contains(KeyModifiers::CONTROL) {
        return true;
    }

    // Pane-search mode first
    if app.pane_find.is_some() && handle_pane_find_mode(ke, app, details_tx) {
        return false;
    }

    // Handle Shift+char keybinds (menus, import, export, updates, status) that work in all modes
    if crate::events::search::handle_shift_keybinds(&ke, app) {
        return false;
    }

    let km = &app.keymap;
    // Match helper that treats Shift+<char> from config as equivalent to uppercase char without Shift from terminal
    let matches_any = |list: &Vec<crate::theme::KeyChord>| {
        list.iter().any(|c| {
            if (c.code, c.mods) == (ke.code, ke.modifiers) {
                return true;
            }
            match (c.code, ke.code) {
                (
                    crossterm::event::KeyCode::Char(cfg_ch),
                    crossterm::event::KeyCode::Char(ev_ch),
                ) => {
                    let cfg_has_shift = c.mods.contains(crossterm::event::KeyModifiers::SHIFT);
                    let ev_has_no_shift =
                        !ke.modifiers.contains(crossterm::event::KeyModifiers::SHIFT);
                    cfg_has_shift && ev_has_no_shift && ev_ch == cfg_ch.to_ascii_uppercase()
                }
                _ => false,
            }
        })
    };

    match ke.code {
        KeyCode::Char('j') => {
            handle_navigation_down(app, details_tx);
        }
        KeyCode::Char('k') => {
            handle_navigation_up(app, details_tx);
        }
        KeyCode::Char('/') => {
            app.pane_find = Some(String::new());
        }
        KeyCode::Enter | KeyCode::Char('\n' | '\r') => {
            handle_enter_key(app);
        }
        KeyCode::Esc => {
            app.focus = crate::state::Focus::Search;
            // Activate Search Normal mode when returning with Esc
            app.search_normal_mode = true;
            refresh_selected_details(app, details_tx);
        }
        code if matches_any(&km.pane_next) && code == ke.code => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                // Bookmarks -> History
                app.focus = crate::state::Focus::Recent;
            } else {
                handle_pane_next_navigation(app, details_tx, preview_tx);
            }
        }
        KeyCode::Left => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                app.focus = crate::state::Focus::Search;
            } else {
                handle_left_arrow_navigation(app, details_tx);
            }
        }
        KeyCode::Right => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                app.focus = crate::state::Focus::Recent;
            } else {
                handle_right_arrow_navigation(app, details_tx, preview_tx);
            }
        }
        KeyCode::Delete if !ke.modifiers.contains(KeyModifiers::SHIFT) => {
            handle_delete_item(app, details_tx);
        }
        code if matches_any(&km.install_clear) && code == ke.code => {
            handle_clear_list(app);
        }
        code if matches_any(&km.install_remove) && code == ke.code => {
            handle_delete_item(app, details_tx);
        }
        KeyCode::Up => {
            handle_navigation_up(app, details_tx);
        }
        KeyCode::Down => {
            handle_navigation_down(app, details_tx);
        }
        _ => {}
    }
    false
}

/// What: Handle key events while in pane-find mode.
///
/// Inputs:
/// - `ke`: Key event received from the terminal
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `true` if the event was handled and should return early; `false` otherwise
///
/// Details:
/// - Handles Enter (jump to next match), Esc (cancel), Backspace (delete char), and Char (append char).
fn handle_pane_find_mode(
    ke: KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    match ke.code {
        KeyCode::Enter | KeyCode::Char('\n' | '\r') => {
            find_in_install(app, true);
            refresh_install_details(app, details_tx);
        }
        KeyCode::Esc => {
            app.pane_find = None;
        }
        KeyCode::Backspace => {
            if let Some(buf) = &mut app.pane_find {
                buf.pop();
            }
        }
        KeyCode::Char(ch) => {
            if let Some(buf) = &mut app.pane_find {
                buf.push(ch);
            }
        }
        _ => {}
    }
    true
}

/// What: Handle Enter key to trigger install/remove/downgrade actions.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - No return value; modifies app state to open modals or trigger actions
///
/// Details:
/// - Normal mode with non-empty Install list: opens Preflight modal or skips to direct install
/// - Installed-only Remove focus: opens Preflight modal or skips to direct remove
/// - Installed-only Downgrade focus: runs downgrade tool
fn handle_enter_key(app: &mut AppState) {
    // Never trigger preflight when SystemUpdate or OptionalDeps modals are active
    // These modals use spawn_shell_commands_in_terminal which bypasses preflight
    let skip_preflight_for_modals = matches!(
        app.modal,
        crate::state::Modal::SystemUpdate { .. }
            | crate::state::Modal::OptionalDeps { .. }
            | crate::state::Modal::Repositories { .. }
    );
    let skip = crate::theme::settings().skip_preflight || skip_preflight_for_modals;
    if !app.installed_only_mode && !app.install_list.is_empty() {
        if skip {
            let install_snapshot = app.install_list.clone();
            if try_open_warn_aur_repo_duplicate_modal(
                app,
                &install_snapshot,
                crate::state::modal::PreflightHeaderChips::default(),
            ) {
                return;
            }
            // Direct install - check for reinstalls first, then batch updates
            // First, check if we're installing packages that are already installed (reinstall scenario)
            // BUT exclude packages that have updates available (those should go through normal update flow)
            let installed_set = crate::logic::deps::get_installed_packages();
            let provided_set = crate::logic::deps::get_provided_packages(&installed_set);
            let upgradable_set = crate::logic::deps::get_upgradable_packages();

            let installed_packages: Vec<crate::state::PackageItem> = app
                .install_list
                .iter()
                .filter(|item| {
                    // Check if package is installed or provided by an installed package
                    let is_installed = crate::logic::deps::is_package_installed_or_provided(
                        &item.name,
                        &installed_set,
                        &provided_set,
                    );

                    if !is_installed {
                        return false;
                    }

                    // Check if package has an update available
                    // For official packages: check if it's in upgradable_set OR version differs from installed
                    // For AUR packages: check if target version is different from installed version
                    let has_update = if upgradable_set.contains(&item.name) {
                        // Package is in upgradable set (pacman -Qu)
                        true
                    } else if !item.version.is_empty() {
                        // Normalize target version by removing revision suffix (same as installed version normalization)
                        let normalized_target_version =
                            item.version.split('-').next().unwrap_or(&item.version);
                        // Compare normalized target version with normalized installed version
                        // This works for both official and AUR packages
                        crate::logic::deps::get_installed_version(&item.name).is_ok_and(
                            |installed_version| normalized_target_version != installed_version,
                        )
                    } else {
                        // No version info available, no update
                        false
                    };

                    // Only show reinstall confirmation if installed AND no update available
                    // If update is available, it should go through normal update flow
                    !has_update
                })
                .cloned()
                .collect();

            if installed_packages.is_empty() {
                // Check if this is a batch update scenario requiring confirmation
                // Only show if there's actually an update available (package is upgradable)
                // AND the package has installed packages in its "Required By" field (dependency risk)
                let has_versions = app.install_list.iter().any(|item| {
                    matches!(item.source, crate::state::Source::Official { .. })
                        && !item.version.is_empty()
                });
                let has_upgrade_available = app.install_list.iter().any(|item| {
                    matches!(item.source, crate::state::Source::Official { .. })
                        && upgradable_set.contains(&item.name)
                });

                // Only show warning if package has installed packages in "Required By" (dependency risk)
                let has_installed_required_by = app.install_list.iter().any(|item| {
                    matches!(item.source, crate::state::Source::Official { .. })
                        && crate::index::is_installed(&item.name)
                        && crate::logic::deps::has_installed_required_by(&item.name)
                });

                if has_versions && has_upgrade_available && has_installed_required_by {
                    // Show confirmation modal for batch updates (only if update is actually available
                    // AND package has installed dependents that could be affected)
                    app.modal = crate::state::Modal::ConfirmBatchUpdate {
                        items: app.install_list.clone(),
                        dry_run: app.dry_run,
                    };
                } else {
                    let items = app.install_list.clone();
                    crate::install::start_integrated_install_all(app, &items, app.dry_run);
                    app.toast_message = Some(crate::i18n::t(
                        app,
                        "app.toasts.installing_preflight_skipped",
                    ));
                    app.toast_expires_at =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
                }
            } else {
                // Show reinstall confirmation modal
                // Store both installed packages (for display) and all packages (for installation)
                app.modal = crate::state::Modal::ConfirmReinstall {
                    items: installed_packages,
                    all_items: app.install_list.clone(),
                    header_chips: crate::state::modal::PreflightHeaderChips::default(),
                };
            }
        } else {
            open_preflight_install_modal(app);
        }
    } else if app.installed_only_mode
        && matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove)
    {
        if !app.remove_list.is_empty() {
            if skip {
                let names: Vec<String> = app.remove_list.iter().map(|p| p.name.clone()).collect();
                crate::install::start_integrated_remove_all(
                    app,
                    &names,
                    app.dry_run,
                    app.remove_cascade_mode,
                );
                app.toast_message =
                    Some(crate::i18n::t(app, "app.toasts.removing_preflight_skipped"));
                app.toast_expires_at =
                    Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
                app.remove_list.clear();
                app.remove_list_names.clear();
                app.remove_state.select(None);
            } else {
                open_preflight_remove_modal(app);
            }
        }
    } else if app.installed_only_mode
        && matches!(
            app.right_pane_focus,
            crate::state::RightPaneFocus::Downgrade
        )
        && !app.downgrade_list.is_empty()
    {
        if skip {
            let names: Vec<String> = app.downgrade_list.iter().map(|p| p.name.clone()).collect();
            let joined = names.join(" ");
            let tool = match crate::logic::privilege::active_tool() {
                Ok(t) => t,
                Err(msg) => {
                    app.toast_message = Some(msg);
                    app.toast_expires_at =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(8));
                    return;
                }
            };
            let bin = tool.binary_name();
            let cmd = if app.dry_run {
                format!("echo DRY RUN: {bin} downgrade {joined}")
            } else {
                format!(
                    "if (command -v downgrade >/dev/null 2>&1) || {bin} pacman -Qi downgrade >/dev/null 2>&1; then {bin} downgrade {joined}; else echo 'downgrade tool not found. Install \"downgrade\" package.'; fi"
                )
            };
            crate::install::spawn_shell_commands_in_terminal(&[cmd]);
            app.downgrade_list.clear();
            app.downgrade_list_names.clear();
            app.downgrade_state.select(None);
        } else {
            open_preflight_downgrade_modal(app);
        }
    }
}

/// What: Handle navigation down (j/Down) in the active pane.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - No return value; updates selection in the active pane
///
/// Details:
/// - Moves selection down in Install/Remove/Downgrade based on mode and focus
fn handle_navigation_down(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
    if !app.installed_only_mode
        || matches!(app.right_pane_focus, crate::state::RightPaneFocus::Install)
    {
        let inds = crate::ui::helpers::filtered_install_indices(app);
        if inds.is_empty() {
            return;
        }
        let sel = app.install_state.selected().unwrap_or(0);
        let max = inds.len().saturating_sub(1);
        let new = std::cmp::min(sel + 1, max);
        app.install_state.select(Some(new));
        refresh_install_details(app, details_tx);
    } else if matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove) {
        let len = app.remove_list.len();
        if len == 0 {
            return;
        }
        let sel = app.remove_state.selected().unwrap_or(0);
        let max = len.saturating_sub(1);
        let new = std::cmp::min(sel + 1, max);
        app.remove_state.select(Some(new));
        refresh_remove_details(app, details_tx);
    } else if matches!(
        app.right_pane_focus,
        crate::state::RightPaneFocus::Downgrade
    ) {
        let len = app.downgrade_list.len();
        if len == 0 {
            return;
        }
        let sel = app.downgrade_state.selected().unwrap_or(0);
        let max = len.saturating_sub(1);
        let new = std::cmp::min(sel + 1, max);
        app.downgrade_state.select(Some(new));
        super::utils::refresh_downgrade_details(app, details_tx);
    }
}

/// What: Handle navigation up (k/Up) in the active pane.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - No return value; updates selection in the active pane
///
/// Details:
/// - Moves selection up in Install/Remove/Downgrade based on mode and focus
fn handle_navigation_up(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
    if !app.installed_only_mode
        || matches!(app.right_pane_focus, crate::state::RightPaneFocus::Install)
    {
        let inds = crate::ui::helpers::filtered_install_indices(app);
        if inds.is_empty() {
            return;
        }
        if let Some(sel) = app.install_state.selected() {
            let new = sel.saturating_sub(1);
            app.install_state.select(Some(new));
            refresh_install_details(app, details_tx);
        }
    } else if matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove) {
        if let Some(sel) = app.remove_state.selected() {
            let new = sel.saturating_sub(1);
            app.remove_state.select(Some(new));
            refresh_remove_details(app, details_tx);
        }
    } else if matches!(
        app.right_pane_focus,
        crate::state::RightPaneFocus::Downgrade
    ) && let Some(sel) = app.downgrade_state.selected()
    {
        let new = sel.saturating_sub(1);
        app.downgrade_state.select(Some(new));
        super::utils::refresh_downgrade_details(app, details_tx);
    }
}

/// What: Delete the selected item from the active list.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - No return value; removes item and updates selection
///
/// Details:
/// - Handles deletion from Install/Remove/Downgrade lists based on mode and focus
fn handle_delete_item(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
    if app.installed_only_mode {
        match app.right_pane_focus {
            crate::state::RightPaneFocus::Downgrade => {
                if let Some(sel) = app.downgrade_state.selected()
                    && sel < app.downgrade_list.len()
                {
                    if let Some(removed_item) = app.downgrade_list.get(sel) {
                        app.downgrade_list_names
                            .remove(&removed_item.name.to_lowercase());
                    }
                    app.downgrade_list.remove(sel);
                    let len = app.downgrade_list.len();
                    if len == 0 {
                        app.downgrade_state.select(None);
                    } else {
                        let new_sel = sel.min(len - 1);
                        app.downgrade_state.select(Some(new_sel));
                        super::utils::refresh_downgrade_details(app, details_tx);
                    }
                }
            }
            crate::state::RightPaneFocus::Remove => {
                if let Some(sel) = app.remove_state.selected()
                    && sel < app.remove_list.len()
                {
                    if let Some(removed_item) = app.remove_list.get(sel) {
                        app.remove_list_names
                            .remove(&removed_item.name.to_lowercase());
                    }
                    app.remove_list.remove(sel);
                    let len = app.remove_list.len();
                    if len == 0 {
                        app.remove_state.select(None);
                    } else {
                        let new_sel = sel.min(len - 1);
                        app.remove_state.select(Some(new_sel));
                        refresh_remove_details(app, details_tx);
                    }
                }
            }
            crate::state::RightPaneFocus::Install => {
                delete_from_install_list(app, details_tx);
            }
        }
    } else {
        delete_from_install_list(app, details_tx);
    }
}

/// What: Delete selected item from Install list.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - No return value; removes item and updates selection
///
/// Details:
/// - Handles deletion from Install list with filtered indices
fn delete_from_install_list(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
    let inds = crate::ui::helpers::filtered_install_indices(app);
    if inds.is_empty() {
        return;
    }
    if let Some(vsel) = app.install_state.selected() {
        let i = inds.get(vsel).copied().unwrap_or(0);
        if i < app.install_list.len() {
            if let Some(removed_item) = app.install_list.get(i) {
                app.install_list_names
                    .remove(&removed_item.name.to_lowercase());
            }
            app.install_list.remove(i);
            app.install_dirty = true;
            // Clear dependency cache when list changes
            app.install_list_deps.clear();
            app.install_list_files.clear();
            app.deps_resolving = false;
            app.files_resolving = false;
            let vis_len = inds.len().saturating_sub(1); // one less visible
            if vis_len == 0 {
                app.install_state.select(None);
            } else {
                let new_sel = if vsel >= vis_len { vis_len - 1 } else { vsel };
                app.install_state.select(Some(new_sel));
                refresh_install_details(app, details_tx);
            }
        }
    }
}

/// What: Clear the active list based on mode and focus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - No return value; clears the appropriate list and resets selection
///
/// Details:
/// - Clears Install/Remove/Downgrade list based on mode and focus
fn handle_clear_list(app: &mut AppState) {
    if app.installed_only_mode {
        match app.right_pane_focus {
            crate::state::RightPaneFocus::Downgrade => {
                app.downgrade_list.clear();
                app.downgrade_list_names.clear();
                app.downgrade_state.select(None);
            }
            crate::state::RightPaneFocus::Remove => {
                app.remove_list.clear();
                app.remove_list_names.clear();
                app.remove_state.select(None);
            }
            crate::state::RightPaneFocus::Install => {
                app.install_list.clear();
                app.install_list_names.clear();
                app.install_state.select(None);
                app.install_dirty = true;
                // Clear dependency cache when list is cleared
                app.install_list_deps.clear();
                app.install_list_files.clear();
                app.deps_resolving = false;
                app.files_resolving = false;
            }
        }
    } else {
        app.install_list.clear();
        app.install_list_names.clear();
        app.install_state.select(None);
        app.install_dirty = true;
        // Clear dependency cache when list is cleared
        app.install_list_deps.clear();
        app.deps_resolving = false;
    }
}