pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Menu mouse event handling (sort, options, config, panels, import/export).

use std::time::Instant;

use tokio::sync::mpsc;

use crate::events::utils::refresh_selected_details;
use crate::i18n;
use crate::state::{AppState, PackageItem};

use super::menu_options;

/// Check if a point is within a rectangle.
///
/// What: Determines if mouse coordinates are inside a given rectangle.
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `rect`: Optional rectangle as (x, y, width, height)
///
/// Output:
/// - `true` if point is within rectangle, `false` otherwise
///
/// Details:
/// - Returns `false` if rectangle is `None`
const fn point_in_rect(mx: u16, my: u16, rect: Option<(u16, u16, u16, u16)>) -> bool {
    if let Some((x, y, w, h)) = rect {
        mx >= x && mx < x + w && my >= y && my < y + h
    } else {
        false
    }
}

/// Handle click on Import button.
///
/// What: Opens `ImportHelp` modal when Import button is clicked.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
fn handle_import_button(app: &mut AppState) -> bool {
    app.modal = crate::state::Modal::ImportHelp;
    false
}

/// Handle click on Updates button.
///
/// What: Opens the available updates modal with scrollable list and triggers refresh.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
///
/// Details:
/// - Loads updates from `~/.config/pacsea/lists/available_updates.txt`
/// - Opens Updates modal with scroll support
/// - Triggers a refresh of the updates list to ensure current data
/// - Opens the modal only after refresh completes
#[allow(clippy::missing_const_for_fn)]
pub fn handle_updates_button(app: &mut AppState) -> bool {
    // Trigger refresh of updates list when button is clicked
    app.refresh_updates = true;
    app.updates_loading = true;
    // Set flag to open modal after refresh completes
    app.pending_updates_modal = true;
    // Don't open modal yet - wait for refresh to complete
    false
}

/// Handle click on News button.
///
/// What: Switch to News management view.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
///
/// Details:
/// - Switches app mode to `News` and selects first result when available.
/// - Preserves existing `pending_news` data (no modal conversion/opening).
/// - Shows "No News available" toast when there are no visible news entries.
pub fn handle_news_button(app: &mut AppState) -> bool {
    app.app_mode = crate::state::types::AppMode::News;
    crate::theme::save_app_start_mode(true);
    app.refresh_news_results();
    if app.news_results.is_empty() {
        app.news_list_state.select(None);
        app.news_selected = 0;
        app.toast_message = Some(crate::i18n::t(app, "app.toasts.no_new_news"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
    } else {
        app.news_selected = app
            .news_selected
            .min(app.news_results.len().saturating_sub(1));
        app.news_list_state.select(Some(app.news_selected));
    }
    false
}

/// Handle click on Export button.
///
/// What: Exports install list to timestamped file in export directory.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
///
/// Details:
/// - Shows toast message if list is empty or export fails
fn handle_export_button(app: &mut AppState) -> bool {
    let mut names: Vec<String> = app.install_list.iter().map(|p| p.name.clone()).collect();
    names.sort();
    if names.is_empty() {
        app.toast_message = Some(crate::i18n::t(app, "app.toasts.install_list_empty"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        return false;
    }
    let export_dir = crate::theme::config_dir().join("export");
    let _ = std::fs::create_dir_all(&export_dir);
    let date_str = crate::util::today_yyyymmdd_utc();
    let mut serial: u32 = 1;
    let file_path = loop {
        let fname = format!("install_list_{date_str}_{serial}.txt");
        let path = export_dir.join(&fname);
        if !path.exists() {
            break path;
        }
        serial += 1;
        if serial > 9999 {
            break export_dir.join(format!("install_list_{date_str}_fallback.txt"));
        }
    };
    let body = names.join("\n");
    match std::fs::write(&file_path, body) {
        Ok(()) => {
            app.toast_message = Some(crate::i18n::t_fmt1(
                app,
                "app.toasts.exported_to",
                file_path.display(),
            ));
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
            tracing::info!(path = %file_path.display().to_string(), count = names.len(), "export: wrote install list");
        }
        Err(e) => {
            let error_msg = format!("{e}");
            app.toast_message = Some(crate::i18n::t_fmt1(
                app,
                "app.toasts.export_failed",
                &error_msg,
            ));
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(5));
            tracing::error!(error = %e, path = %file_path.display().to_string(), "export: failed to write install list");
        }
    }
    false
}

/// Handle click on Arch status label.
///
/// What: Opens status.archlinux.org URL in browser.
///
/// Output:
/// - `false` if handled
fn handle_arch_status() -> bool {
    crate::util::open_url("https://status.archlinux.org");
    false
}

/// Handle click on sort menu button.
///
/// What: Toggles sort menu open/closed state.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
#[allow(clippy::missing_const_for_fn)]
fn handle_sort_button(app: &mut AppState) -> bool {
    app.sort_menu_open = !app.sort_menu_open;
    if app.sort_menu_open {
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
    } else {
        app.sort_menu_auto_close_at = None;
    }
    false
}

/// Handle click on options menu button.
///
/// What: Toggles options menu and closes other menus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
#[allow(clippy::missing_const_for_fn)]
fn handle_options_button(app: &mut AppState) -> bool {
    app.options_menu_open = !app.options_menu_open;
    if app.options_menu_open {
        app.panels_menu_open = false;
        app.config_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
    }
    false
}

/// Handle click on config menu button.
///
/// What: Toggles config menu and closes other menus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
#[allow(clippy::missing_const_for_fn)]
fn handle_config_button(app: &mut AppState) -> bool {
    app.config_menu_open = !app.config_menu_open;
    if app.config_menu_open {
        app.options_menu_open = false;
        app.panels_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
    }
    false
}

/// Handle click on panels menu button.
///
/// What: Toggles panels menu and closes other menus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
#[allow(clippy::missing_const_for_fn)]
fn handle_panels_button(app: &mut AppState) -> bool {
    app.panels_menu_open = !app.panels_menu_open;
    if app.panels_menu_open {
        app.options_menu_open = false;
        app.config_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
    }
    false
}

/// Handle click on collapsed menu button.
///
/// What: Toggles collapsed menu and closes other menus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if handled
#[allow(clippy::missing_const_for_fn)]
fn handle_collapsed_menu_button(app: &mut AppState) -> bool {
    app.collapsed_menu_open = !app.collapsed_menu_open;
    if app.collapsed_menu_open {
        app.options_menu_open = false;
        app.config_menu_open = false;
        app.panels_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
    }
    false
}

/// Handle click inside sort menu.
///
/// What: Changes sort mode based on clicked row and refreshes results.
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
fn handle_sort_menu_click(
    _mx: u16,
    my: u16,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> Option<bool> {
    if let Some((_x, y, _w, _h)) = app.sort_menu_rect {
        let row = my.saturating_sub(y) as usize;
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            match row {
                0 => app.news_sort_mode = crate::state::types::NewsSortMode::DateDesc,
                1 => app.news_sort_mode = crate::state::types::NewsSortMode::DateAsc,
                2 => app.news_sort_mode = crate::state::types::NewsSortMode::Title,
                3 => app.news_sort_mode = crate::state::types::NewsSortMode::SourceThenTitle,
                4 => app.news_sort_mode = crate::state::types::NewsSortMode::SeverityThenDate,
                5 => app.news_sort_mode = crate::state::types::NewsSortMode::UnreadThenDate,
                _ => return None,
            }
            app.refresh_news_results();
        } else {
            match row {
                0 => {
                    app.sort_mode = crate::state::SortMode::RepoThenName;
                    crate::theme::save_sort_mode(app.sort_mode);
                }
                1 => {
                    app.sort_mode = crate::state::SortMode::AurPopularityThenOfficial;
                    crate::theme::save_sort_mode(app.sort_mode);
                }
                2 => {
                    app.sort_mode = crate::state::SortMode::BestMatches;
                    crate::theme::save_sort_mode(app.sort_mode);
                }
                _ => return None,
            }
            crate::logic::sort_results_preserve_selection(app);
            if app.results.is_empty() {
                app.list_state.select(None);
            } else {
                app.selected = 0;
                app.list_state.select(Some(0));
                refresh_selected_details(app, details_tx);
            }
        }
        app.sort_menu_open = false;
        app.sort_menu_auto_close_at = None;
        Some(false)
    } else {
        None
    }
}

/// Handle click inside options menu.
///
/// What: Handles clicks on options menu items (installed-only, update, optional deps, repositories, mode toggle).
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
fn handle_options_menu_click(
    _mx: u16,
    my: u16,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> Option<bool> {
    if let Some((_x, y, _w, _h)) = app.options_menu_rect {
        let row = my.saturating_sub(y) as usize;
        let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News);
        if news_mode {
            match row {
                0 => handle_system_update_option(app),
                1 => handle_optional_deps_option(app),
                2 => handle_repositories_option(app),
                3 => handle_mode_toggle(app, details_tx),
                _ => return None,
            }
        } else {
            match row {
                0 => handle_installed_only_toggle(app, details_tx),
                1 => handle_system_update_option(app),
                2 => handle_optional_deps_option(app),
                3 => handle_repositories_option(app),
                4 => handle_mode_toggle(app, details_tx),
                _ => return None,
            }
        }
        app.options_menu_open = false;
        Some(false)
    } else {
        None
    }
}

/// Handle installed-only mode toggle.
///
/// What: Toggles between showing all packages and only explicitly installed packages.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Details:
/// - When enabling, saves installed packages list to config directory
fn handle_installed_only_toggle(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    use std::collections::HashSet;
    if app.installed_only_mode {
        if let Some(prev) = app.results_backup_for_toggle.take() {
            app.all_results = prev;
        }
        app.installed_only_mode = false;
        app.right_pane_focus = crate::state::RightPaneFocus::Install;
        crate::logic::apply_filters_and_sort_preserve_selection(app);
        crate::events::utils::refresh_selected_details(app, details_tx);
    } else {
        app.results_backup_for_toggle = Some(app.all_results.clone());
        let explicit = crate::index::explicit_names();
        let mut items: Vec<crate::state::PackageItem> = crate::index::all_official()
            .into_iter()
            .filter(|p| explicit.contains(&p.name))
            .collect();
        let official_names: HashSet<String> = items.iter().map(|p| p.name.clone()).collect();
        for name in explicit {
            if !official_names.contains(&name) {
                let is_eos = crate::index::is_eos_name(&name);
                let src = if is_eos {
                    crate::state::Source::Official {
                        repo: "EOS".to_string(),
                        arch: String::new(),
                    }
                } else {
                    crate::state::Source::Aur
                };
                items.push(crate::state::PackageItem {
                    name: name.clone(),
                    version: String::new(),
                    description: String::new(),
                    source: src,
                    popularity: None,
                    out_of_date: None,
                    orphaned: false,
                });
            }
        }
        app.all_results = items;
        app.installed_only_mode = true;
        app.right_pane_focus = crate::state::RightPaneFocus::Remove;
        crate::logic::apply_filters_and_sort_preserve_selection(app);
        crate::events::utils::refresh_selected_details(app, details_tx);

        let path = crate::theme::config_dir().join("installed_packages.txt");
        // Query pacman directly with current mode to ensure file reflects the setting
        let names = crate::index::query_explicit_packages_sync(app.installed_packages_mode);
        let body = names.join("\n");
        let _ = std::fs::write(path, body);
    }
}

/// What: Toggle between package mode and news feed mode.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details when switching back to package mode
pub(in crate::events) fn handle_mode_toggle(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        app.app_mode = crate::state::types::AppMode::Package;
        if app.results.is_empty() {
            app.list_state.select(None);
        } else {
            app.selected = app.selected.min(app.results.len().saturating_sub(1));
            app.list_state.select(Some(app.selected));
            refresh_selected_details(app, details_tx);
        }
    } else {
        app.app_mode = crate::state::types::AppMode::News;
        if app.news_results.is_empty() {
            app.news_list_state.select(None);
            app.news_selected = 0;
        } else {
            app.news_selected = 0;
            app.news_list_state.select(Some(0));
        }
    }
    crate::theme::save_app_start_mode(matches!(app.app_mode, crate::state::types::AppMode::News));
}

/// What: Toggle news maximum age filter between 7, 30, 90 days, and no limit.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - None (modifies app state directly)
///
/// Details:
/// - Cycles through age options: 7 days → 30 days → 90 days → no limit → 7 days
/// - Refreshes news results after changing the filter
pub(in crate::events) fn handle_news_age_toggle(app: &mut AppState) {
    const AGES: [Option<u32>; 4] = [Some(7), Some(30), Some(90), None];
    let current = app.news_max_age_days;
    let next = AGES
        .iter()
        .cycle()
        .skip_while(|&&v| v != current)
        .nth(1)
        .copied()
        .unwrap_or(Some(7));
    app.news_max_age_days = next;
    app.refresh_news_results();
    let age_label = app.news_max_age_days.map_or_else(
        || i18n::t(app, "app.results.options_menu.news_age_all"),
        |d| i18n::t_fmt1(app, "app.results.options_menu.news_age_days", d.to_string()),
    );
    app.toast_message = Some(age_label);
    app.toast_expires_at = Some(Instant::now() + std::time::Duration::from_secs(3));
    crate::theme::save_news_max_age_days(app.news_max_age_days);
}

/// Handle system update option.
///
/// What: Opens `SystemUpdate` modal with default settings.
///
/// Inputs:
/// - `app`: Mutable application state
fn handle_system_update_option(app: &mut AppState) {
    let countries = vec![
        "Worldwide".to_string(),
        "Germany".to_string(),
        "United States".to_string(),
        "United Kingdom".to_string(),
        "France".to_string(),
        "Netherlands".to_string(),
        "Sweden".to_string(),
        "Canada".to_string(),
        "Australia".to_string(),
        "Japan".to_string(),
    ];
    let prefs = crate::theme::settings();
    let initial_country_idx = {
        let sel = prefs
            .selected_countries
            .split(',')
            .next()
            .map_or_else(|| "Worldwide".to_string(), |s| s.trim().to_string());
        countries.iter().position(|c| c == &sel).unwrap_or(0)
    };
    app.modal = crate::state::Modal::SystemUpdate {
        do_mirrors: false,
        do_pacman: true,
        force_sync: false,
        do_aur: true,
        do_cache: false,
        country_idx: initial_country_idx,
        countries,
        mirror_count: prefs.mirror_count,
        cursor: 0,
    };
}

/// What: Opens the read-only Repositories modal (`repos.conf` merged with `/etc/pacman.conf`).
///
/// Inputs:
/// - `app`: Mutable application state.
///
/// Output:
/// - None (sets `Modal::Repositories`).
///
/// Details:
/// - Does not write to `/etc`; apply/edit flows are deferred to a later phase.
fn handle_repositories_option(app: &mut AppState) {
    #[cfg(not(target_os = "linux"))]
    {
        app.modal = crate::state::Modal::Alert {
            message: crate::i18n::t(app, "app.modals.repositories.unsupported_platform"),
        };
        return;
    }
    #[cfg(target_os = "linux")]
    {
        let (rows, repos_conf_error, pacman_warnings) =
            crate::logic::repos::build_repositories_modal_fields_default();
        app.modal = crate::state::Modal::Repositories {
            rows,
            selected: 0,
            scroll: 0,
            repos_conf_error,
            pacman_warnings,
        };
    }
}

/// What: Opens the TUI optional-dependencies review modal.
///
/// Inputs:
/// - `app`: Mutable application state (sets modal and SSH help check).
///
/// Output:
/// - None (mutates `app`).
///
/// Details:
/// - Spawns a background AUR SSH help check like other optional-deps entry points.
fn handle_optional_deps_option(app: &mut AppState) {
    let rows = menu_options::build_optional_deps_rows(app);
    app.modal = crate::state::Modal::OptionalDeps {
        rows,
        selected: 0,
        selected_pkg_names: std::collections::HashSet::new(),
    };
    let ssh_command = crate::theme::settings().aur_vote_ssh_command;
    app.pending_aur_ssh_help_check_result = Some(
        crate::logic::ssh_setup::spawn_aur_ssh_help_check(ssh_command),
    );
}

/// Handle click inside config menu.
///
/// What: Opens config files in terminal editors based on clicked row.
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
///
/// Details:
fn handle_config_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> {
    if let Some((_x, y, _w, _h)) = app.config_menu_rect {
        let row = my.saturating_sub(y) as usize;
        let settings_path = crate::theme::config_dir().join("settings.conf");
        let theme_path = crate::theme::config_dir().join("theme.conf");
        let keybinds_path = crate::theme::config_dir().join("keybinds.conf");
        let repos_path = crate::theme::config_dir().join("repos.conf");

        let target = match row {
            0 => settings_path,
            1 => theme_path,
            2 => keybinds_path,
            3 => repos_path,
            _ => {
                app.config_menu_open = false;
                app.artix_filter_menu_open = false;
                app.custom_repos_filter_menu_open = false;
                return Some(false);
            }
        };

        #[cfg(target_os = "windows")]
        {
            crate::util::open_file(&target);
        }
        #[cfg(not(target_os = "windows"))]
        {
            let editor_cmd = crate::install::editor_open_config_command(&target);
            let cmds = vec![editor_cmd];
            std::thread::spawn(move || {
                crate::install::spawn_shell_commands_in_terminal(&cmds);
            });
        }

        app.config_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
        Some(false)
    } else {
        None
    }
}

/// Handle click inside panels menu.
///
/// What: Toggles panel visibility based on clicked row.
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
fn handle_panels_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> {
    if let Some((_x, y, _w, _h)) = app.panels_menu_rect {
        let row = my.saturating_sub(y) as usize;
        let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News);
        if news_mode {
            match row {
                0 => {
                    app.show_news_history_pane = !app.show_news_history_pane;
                    if !app.show_news_history_pane
                        && matches!(app.focus, crate::state::Focus::Recent)
                    {
                        app.focus = crate::state::Focus::Search;
                    }
                }
                1 => {
                    app.show_news_bookmarks_pane = !app.show_news_bookmarks_pane;
                    if !app.show_news_bookmarks_pane
                        && matches!(app.focus, crate::state::Focus::Install)
                    {
                        app.focus = crate::state::Focus::Search;
                    }
                }
                2 => {
                    app.show_keybinds_footer = !app.show_keybinds_footer;
                    crate::theme::save_show_keybinds_footer(app.show_keybinds_footer);
                }
                _ => return None,
            }
        } else {
            match row {
                0 => {
                    app.show_recent_pane = !app.show_recent_pane;
                    if !app.show_recent_pane && matches!(app.focus, crate::state::Focus::Recent) {
                        app.focus = crate::state::Focus::Search;
                    }
                    crate::theme::save_show_recent_pane(app.show_recent_pane);
                }
                1 => {
                    app.show_install_pane = !app.show_install_pane;
                    if !app.show_install_pane && matches!(app.focus, crate::state::Focus::Install) {
                        app.focus = crate::state::Focus::Search;
                    }
                    crate::theme::save_show_install_pane(app.show_install_pane);
                }
                2 => {
                    app.show_keybinds_footer = !app.show_keybinds_footer;
                    crate::theme::save_show_keybinds_footer(app.show_keybinds_footer);
                }
                _ => return None,
            }
        }
        Some(false)
    } else {
        None
    }
}

/// Handle click inside collapsed menu.
///
/// What: Opens the appropriate menu based on clicked row.
///
/// Inputs:
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
///
/// Details:
/// - Row 0: Opens Config/Lists menu
/// - Row 1: Opens Panels menu
/// - Row 2: Opens Options menu
#[allow(clippy::missing_const_for_fn)]
fn handle_collapsed_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> {
    if let Some((_x, y, _w, _h)) = app.collapsed_menu_rect {
        let row = my.saturating_sub(y) as usize;
        app.collapsed_menu_open = false;
        match row {
            0 => {
                app.config_menu_open = true;
                app.options_menu_open = false;
                app.panels_menu_open = false;
                app.artix_filter_menu_open = false;
                app.custom_repos_filter_menu_open = false;
            }
            1 => {
                app.panels_menu_open = true;
                app.options_menu_open = false;
                app.config_menu_open = false;
                app.artix_filter_menu_open = false;
                app.custom_repos_filter_menu_open = false;
            }
            2 => {
                app.options_menu_open = true;
                app.panels_menu_open = false;
                app.config_menu_open = false;
                app.artix_filter_menu_open = false;
                app.custom_repos_filter_menu_open = false;
            }
            _ => return None,
        }
        Some(false)
    } else {
        None
    }
}

/// Close all open menus.
///
/// What: Closes all menus when clicking outside any menu.
///
/// Inputs:
/// - `app`: Mutable application state
#[allow(clippy::missing_const_for_fn)]
fn close_all_menus(app: &mut AppState) {
    if app.sort_menu_open {
        app.sort_menu_open = false;
        app.sort_menu_auto_close_at = None;
    }
    if app.options_menu_open {
        app.options_menu_open = false;
    }
    if app.panels_menu_open {
        app.panels_menu_open = false;
    }
    if app.config_menu_open {
        app.config_menu_open = false;
    }
    if app.collapsed_menu_open {
        app.collapsed_menu_open = false;
    }
    app.artix_filter_menu_open = false;
    app.custom_repos_filter_menu_open = false;
}

/// What: Detect clicks meant for Artix or `repos.conf` overflow filter UI.
///
/// Inputs:
/// - `mx` / `my`: Mouse coordinates.
/// - `app`: State carrying Artix / custom repo chip rects and open dropdown hit rects.
///
/// Output:
/// - `true` when the point hits the main Artix chip, the custom `[Repos]` chip, or either overflow menu.
///
/// Details:
/// - Menu dispatch runs before filter mouse handling. The generic "click outside closes menus" path
///   must not clear these flags when the same click will toggle a chip or a checkbox row; otherwise
///   the filter pass sees menus already closed and ignores the action.
const fn click_on_filter_overflow_targets(mx: u16, my: u16, app: &AppState) -> bool {
    point_in_rect(mx, my, app.results_filter_artix_rect)
        || point_in_rect(mx, my, app.results_filter_custom_repos_rect)
        || point_in_rect(mx, my, app.artix_filter_menu_rect)
        || point_in_rect(mx, my, app.custom_repos_filter_menu_rect)
}

/// Handle mouse events for menus (sort, options, config, panels, import/export).
///
/// What: Process mouse interactions with menu buttons, dropdown menus, and action buttons
/// in the title bar and Install pane.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state containing menu state and UI rectangles
/// - `details_tx`: Channel to request package details when selection changes
///
/// Output:
/// - `Some(bool)` if the event was handled (consumed by a menu), `None` if not handled.
///   The boolean value indicates whether the application should exit (always `false` here).
///
/// Details:
/// - Import/Export buttons: Import opens `ImportHelp` modal; Export writes install list to timestamped file.
/// - Arch status label: Opens status.archlinux.org URL.
/// - Sort menu: Toggle button opens/closes sort menu; menu items change sort mode and refresh results.
/// - Options menu: Toggle button opens/closes menu; items toggle installed-only mode, open `SystemUpdate`/News,
///   or build `OptionalDeps` modal.
/// - Config menu: Toggle button opens/closes menu; items open config files in terminal editors.
/// - Panels menu: Toggle button opens/closes menu; items toggle Recent/Install panes and keybinds footer.
/// - Menu auto-close: Clicking outside any open menu closes it.
pub(super) fn handle_menus_mouse(
    mx: u16,
    my: u16,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> Option<bool> {
    // Check button clicks first
    // In News mode, check news button first; otherwise check updates button
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        if point_in_rect(mx, my, app.news_button_rect) {
            return Some(handle_news_button(app));
        }
    } else if point_in_rect(mx, my, app.updates_button_rect) {
        return Some(handle_updates_button(app));
    }
    if point_in_rect(mx, my, app.install_import_rect) {
        return Some(handle_import_button(app));
    }
    if point_in_rect(mx, my, app.install_export_rect) {
        return Some(handle_export_button(app));
    }
    if point_in_rect(mx, my, app.arch_status_rect) {
        return Some(handle_arch_status());
    }
    if point_in_rect(mx, my, app.news_age_button_rect) {
        handle_news_age_toggle(app);
        return Some(false);
    }
    if point_in_rect(mx, my, app.sort_button_rect) {
        return Some(handle_sort_button(app));
    }
    if point_in_rect(mx, my, app.options_button_rect) {
        return Some(handle_options_button(app));
    }
    if point_in_rect(mx, my, app.config_button_rect) {
        return Some(handle_config_button(app));
    }
    if point_in_rect(mx, my, app.panels_button_rect) {
        return Some(handle_panels_button(app));
    }
    if point_in_rect(mx, my, app.collapsed_menu_button_rect) {
        return Some(handle_collapsed_menu_button(app));
    }

    // Check menu clicks if menus are open
    if app.sort_menu_open && point_in_rect(mx, my, app.sort_menu_rect) {
        return handle_sort_menu_click(mx, my, app, details_tx);
    }
    if app.options_menu_open && point_in_rect(mx, my, app.options_menu_rect) {
        return handle_options_menu_click(mx, my, app, details_tx);
    }
    if app.config_menu_open && point_in_rect(mx, my, app.config_menu_rect) {
        return handle_config_menu_click(mx, my, app);
    }
    if app.panels_menu_open && point_in_rect(mx, my, app.panels_menu_rect) {
        return handle_panels_menu_click(mx, my, app);
    }
    if app.collapsed_menu_open && point_in_rect(mx, my, app.collapsed_menu_rect) {
        return handle_collapsed_menu_click(mx, my, app);
    }

    // Click outside standard menus closes them. Defer clearing Artix / custom-repo overflow menus when
    // the coordinates target those controls — filter mouse handling runs next.
    if !click_on_filter_overflow_targets(mx, my, app) {
        close_all_menus(app);
    }
    None
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use crate::state::types::AppMode;
    use crate::util::parse_update_entry;

    fn seed_news_age_translations(app: &mut crate::state::AppState) {
        let mut translations = HashMap::new();
        translations.insert(
            "app.results.options_menu.news_age_all".to_string(),
            "News age: all time".to_string(),
        );
        translations.insert(
            "app.results.options_menu.news_age_days".to_string(),
            "News age: {} days".to_string(),
        );
        app.translations = translations.clone();
        app.translations_fallback = translations;
    }

    /// What: Test that updates parsing correctly extracts old and new versions.
    ///
    /// Inputs:
    /// - Sample update file content with format `"name - old_version -> name - new_version"`
    ///
    /// Output:
    /// - Verifies that `old_version` and `new_version` are correctly parsed and different
    ///
    /// Details:
    /// - Creates a temporary updates file with known content
    /// - Calls `handle_updates_button` to parse it
    /// - Verifies that the parsed entries have correct old and new versions
    #[test]
    fn test_updates_parsing_extracts_correct_versions() {
        // Test the parsing logic with various formats
        let test_cases = vec![
            (
                "package-a - 1.0.0 -> package-a - 2.0.0",
                "package-a",
                "1.0.0",
                "2.0.0",
            ),
            (
                "package-b - 3.1.0 -> package-b - 3.2.0",
                "package-b",
                "3.1.0",
                "3.2.0",
            ),
            (
                "bat - 0.26.0-1 -> bat - 0.26.0-1",
                "bat",
                "0.26.0-1",
                "0.26.0-1",
            ),
            (
                "comgr - 2:6.4.4-2 -> comgr - 2:6.4.4-2",
                "comgr",
                "2:6.4.4-2",
                "2:6.4.4-2",
            ),
        ];

        for (input, expected_name, expected_old, expected_new) in test_cases {
            let entries: Vec<(String, String, String)> =
                input.lines().filter_map(parse_update_entry).collect();

            assert_eq!(entries.len(), 1, "Failed to parse: {input}");
            let (name, old_version, new_version) = &entries[0];
            assert_eq!(name, expected_name, "Wrong name for: {input}");
            assert_eq!(old_version, expected_old, "Wrong old_version for: {input}");
            assert_eq!(new_version, expected_new, "Wrong new_version for: {input}");
        }
    }

    #[test]
    fn news_age_toggle_sets_toast_and_cycles_value() {
        let mut app = crate::state::AppState::default();
        seed_news_age_translations(&mut app);
        app.news_max_age_days = Some(7);
        app.app_mode = AppMode::News;

        handle_news_age_toggle(&mut app);

        assert_eq!(app.news_max_age_days, Some(30));
        assert!(app.toast_message.as_ref().is_some());
        assert!(app.toast_expires_at.is_some());
    }

    // Removed: News options menu no longer includes a News age entry.

    /// What: Test that `handle_news_button` preserves `pending_news` for repeated presses.
    ///
    /// Inputs:
    /// - `AppState` with `news_ready` set to true and `pending_news` populated
    ///
    /// Output:
    /// - App mode switches to `News`
    /// - `pending_news` remains available after first call
    /// - Repeated call keeps mode in `News`
    /// - `pending_news` remains available after second call
    ///
    /// Details:
    /// - Regression guard for preserving `pending_news` on repeated button presses.
    #[test]
    fn test_handle_news_button_preserves_pending_news() {
        let mut app = crate::state::AppState::default();

        // Set up news items
        let news_items = vec![
            crate::state::NewsItem {
                date: "2025-01-01".to_string(),
                title: "Test News 1".to_string(),
                url: "https://example.com/news1".to_string(),
            },
            crate::state::NewsItem {
                date: "2025-01-02".to_string(),
                title: "Test News 2".to_string(),
                url: "https://example.com/news2".to_string(),
            },
        ];

        app.news_ready = true;
        app.pending_news = Some(news_items);

        // First call - should switch to News mode
        handle_news_button(&mut app);

        // Verify app switched modes and did not consume pending_news
        assert!(matches!(app.app_mode, AppMode::News));

        // Verify pending_news is still available (not consumed)
        assert!(
            app.pending_news.is_some(),
            "pending_news should still be available after first open"
        );
        if let Some(pending) = &app.pending_news {
            assert_eq!(pending.len(), 2, "pending_news should still have 2 items");
            assert_eq!(pending[0].title, "Test News 1");
        }

        // Second call - should still keep News mode and preserve pending_news
        handle_news_button(&mut app);

        assert!(matches!(app.app_mode, AppMode::News));

        // Verify pending_news is still available after second call
        assert!(
            app.pending_news.is_some(),
            "pending_news should still be available after second open"
        );
        if let Some(pending) = &app.pending_news {
            assert_eq!(
                pending.len(),
                2,
                "pending_news should still have 2 items after second open"
            );
        }
    }

    #[test]
    /// What: Ensure menu dispatch does not clear the custom-repo filter dropdown before filters run.
    ///
    /// Inputs:
    /// - `AppState` with `custom_repos_filter_menu_open` and a menu hit rect; click coordinates inside it.
    ///
    /// Output:
    /// - After `handle_menus_mouse`, the menu remains open.
    ///
    /// Details:
    /// - Regression: `close_all_menus` used to run on every unhandled menu click and cleared
    ///   `custom_repos_filter_menu_open`, so the subsequent filter pass ignored checkbox toggles.
    fn handle_menus_mouse_leaves_custom_repos_dropdown_open_for_filter_pass() {
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut app = crate::state::AppState {
            custom_repos_filter_menu_open: true,
            custom_repos_filter_menu_rect: Some((50u16, 3u16, 24u16, 5u16)),
            ..crate::state::AppState::default()
        };
        let mx = 55u16;
        let my = 5u16;
        assert!(super::click_on_filter_overflow_targets(mx, my, &app));
        let r = super::handle_menus_mouse(mx, my, &mut app, &tx);
        assert!(r.is_none());
        assert!(app.custom_repos_filter_menu_open);
    }
}