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

use crate::logic::send_query;
use crate::sources::VoteAction;
use crate::state::{AppState, PackageItem, QueryInput};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use super::super::utils::matches_any;
use super::helpers::navigate_pane;
use super::preflight_helpers::open_preflight_modal;
use crate::events::utils::{
    byte_index_for_char, char_count, move_sel_cached_with_vote_state, refresh_install_details,
};

/// What: Handle numeric selection (1-9) for config menu items.
///
/// Inputs:
/// - `idx`: Numeric index (0-8) from key press
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if handled, `false` otherwise
///
/// Details:
/// - Opens the selected config file in a terminal editor.
/// - Handles settings, theme, and keybinds.
fn handle_config_menu_numeric_selection(idx: usize, app: &mut AppState) -> bool {
    if !app.config_menu_open {
        return false;
    }

    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 target = match idx {
        0 => settings_path,
        1 => theme_path,
        2 => keybinds_path,
        _ => {
            app.config_menu_open = false;
            return 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;
    true
}

/// What: Handle menu toggle key events.
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if a menu toggle was handled, `false` otherwise
///
/// Details:
/// - Toggles config, options, or panels menu.
/// - Ensures only one menu is open at a time.
pub fn handle_menu_toggles(ke: &KeyEvent, app: &mut AppState) -> bool {
    let km = &app.keymap;

    if matches_any(ke, &km.config_menu_toggle) {
        app.config_menu_open = !app.config_menu_open;
        if app.config_menu_open {
            app.options_menu_open = false;
            app.panels_menu_open = false;
            app.sort_menu_open = false;
            app.sort_menu_auto_close_at = None;
        }
        return true;
    }

    if matches_any(ke, &km.options_menu_toggle) {
        app.options_menu_open = !app.options_menu_open;
        if app.options_menu_open {
            app.config_menu_open = false;
            app.panels_menu_open = false;
            app.sort_menu_open = false;
            app.sort_menu_auto_close_at = None;
        }
        return true;
    }

    if matches_any(ke, &km.panels_menu_toggle) {
        app.panels_menu_open = !app.panels_menu_open;
        if app.panels_menu_open {
            app.config_menu_open = false;
            app.options_menu_open = false;
            app.sort_menu_open = false;
            app.sort_menu_auto_close_at = None;
        }
        return true;
    }

    false
}

/// What: Handle export of install list to file.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - None (modifies app state directly)
///
/// Details:
/// - Exports current Install List package names to config export dir.
/// - Creates files with format: `install_list_YYYYMMDD_serial.txt`
/// - Shows toast messages for success or failure.
pub fn handle_export(app: &mut AppState) {
    if app.installed_only_mode {
        return;
    }

    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;
    }

    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");
        }
    }
}

/// What: Handle text selection movement (left/right).
///
/// Inputs:
/// - `app`: Mutable application state
/// - `direction`: Direction to move (-1 for left, 1 for right)
///
/// Output:
/// - None (modifies app state directly)
///
/// Details:
/// - Begins selection if not already started.
/// - Moves caret in the specified direction within input bounds.
/// - Handles both News mode and normal search mode.
fn handle_selection_move(app: &mut AppState, direction: isize) {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        if app.news_search_select_anchor.is_none() {
            app.news_search_select_anchor = Some(app.news_search_caret);
        }

        let cc = char_count(&app.news_search_input);
        let cur = isize::try_from(app.news_search_caret).unwrap_or(0) + direction;
        let new_ci = if cur < 0 {
            0
        } else {
            usize::try_from(cur).unwrap_or(0)
        };
        app.news_search_caret = new_ci.min(cc);
    } else {
        if app.search_select_anchor.is_none() {
            app.search_select_anchor = Some(app.search_caret);
        }

        let cc = char_count(&app.input);
        let cur = isize::try_from(app.search_caret).unwrap_or(0) + direction;
        let new_ci = if cur < 0 {
            0
        } else {
            usize::try_from(cur).unwrap_or(0)
        };
        app.search_caret = new_ci.min(cc);
    }
}

/// What: Handle deletion of selected text range.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `query_tx`: Channel to send debounced search queries
///
/// Output:
/// - `true` if deletion occurred, `false` otherwise
///
/// Details:
/// - Deletes the selected range between anchor and caret.
/// - Updates input and triggers query refresh.
/// - Handles both News mode and normal search mode.
fn handle_selection_delete(
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<QueryInput>,
) -> bool {
    let (anchor_opt, caret, input_text) =
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            (
                app.news_search_select_anchor.take(),
                app.news_search_caret,
                &mut app.news_search_input,
            )
        } else {
            (
                app.search_select_anchor.take(),
                app.search_caret,
                &mut app.input,
            )
        };

    let Some(anchor) = anchor_opt else {
        return false;
    };

    let a = anchor.min(caret);
    let b = anchor.max(caret);
    if a == b {
        return false;
    }

    let bs = byte_index_for_char(input_text, a);
    let be = byte_index_for_char(input_text, b);
    let mut new_input = String::with_capacity(input_text.len());
    new_input.push_str(&input_text[..bs]);
    new_input.push_str(&input_text[be..]);
    *input_text = new_input;

    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        app.news_search_caret = a;
        app.refresh_news_results();
    } else {
        app.search_caret = a;
        send_query(app, query_tx);
    }

    app.last_input_change = std::time::Instant::now();
    app.last_saved_value = None;
    true
}

/// What: Handle navigation key events (j/k, arrow keys, Ctrl+D/U).
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request details for the focused item
///
/// Output:
/// - `true` if navigation was handled, `false` otherwise
///
/// Details:
/// - Handles vim-like navigation: j/k for single line, arrow keys from keymap, Ctrl+D/U for page movement.
fn handle_navigation(
    ke: &KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
) -> bool {
    let km = &app.keymap;

    // Check keymap-based arrow keys first (works same in normal and insert mode)
    if matches_any(ke, &km.search_move_up) {
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            crate::events::utils::move_news_selection(app, -1);
        } else {
            move_sel_cached_with_vote_state(app, -1, details_tx, comments_tx);
        }
        return true;
    }
    if matches_any(ke, &km.search_move_down) {
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            crate::events::utils::move_news_selection(app, 1);
        } else {
            move_sel_cached_with_vote_state(app, 1, details_tx, comments_tx);
        }
        return true;
    }
    if matches_any(ke, &km.search_page_up) {
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            crate::events::utils::move_news_selection(app, -10);
        } else {
            move_sel_cached_with_vote_state(app, -10, details_tx, comments_tx);
        }
        return true;
    }
    if matches_any(ke, &km.search_page_down) {
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            crate::events::utils::move_news_selection(app, 10);
        } else {
            move_sel_cached_with_vote_state(app, 10, details_tx, comments_tx);
        }
        return true;
    }

    // Vim-like navigation (j/k, Ctrl+D/U)
    match (ke.code, ke.modifiers) {
        (KeyCode::Char('j'), _) => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                crate::events::utils::move_news_selection(app, 1);
            } else {
                move_sel_cached_with_vote_state(app, 1, details_tx, comments_tx);
            }
            true
        }
        (KeyCode::Char('k'), _) => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                crate::events::utils::move_news_selection(app, -1);
            } else {
                move_sel_cached_with_vote_state(app, -1, details_tx, comments_tx);
            }
            true
        }
        (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
            move_sel_cached_with_vote_state(app, 10, details_tx, comments_tx);
            true
        }
        (KeyCode::Char('u'), KeyModifiers::CONTROL) => {
            move_sel_cached_with_vote_state(app, -10, details_tx, comments_tx);
            true
        }
        _ => false,
    }
}

/// What: Handle space key events (add to list or downgrade).
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request details for the focused item
/// - `add_tx`: Channel to add items to the Install/Remove lists
///
/// Output:
/// - `true` if space key was handled, `false` otherwise
///
/// Details:
/// - Ctrl+Space: Adds to downgrade list (installed-only mode only).
/// - Space: Adds to install list or remove list depending on mode.
fn handle_space_key(
    ke: &KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    add_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    match (ke.code, ke.modifiers) {
        (KeyCode::Char(' '), KeyModifiers::CONTROL) => {
            if app.installed_only_mode
                && let Some(item) = app.results.get(app.selected).cloned()
            {
                crate::logic::add_to_downgrade_list(app, item);
                crate::events::utils::refresh_downgrade_details(app, details_tx);
            }
            true
        }
        (KeyCode::Char(' '), _) => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                if let Some(item) = app.news_results.get(app.news_selected).cloned() {
                    let url_opt = item.url.clone();
                    let mut content = app.news_content.clone().or_else(|| {
                        url_opt
                            .as_ref()
                            .and_then(|u| app.news_content_cache.get(u).cloned())
                    });
                    let mut html_path = None;
                    if let Some(url) = &url_opt
                        && let Ok(html) = crate::util::curl::curl_text(url)
                    {
                        let dir = crate::theme::lists_dir().join("news_html");
                        let _ = std::fs::create_dir_all(&dir);
                        let mut hasher = DefaultHasher::new();
                        item.id.hash(&mut hasher);
                        let fname = format!("{:016x}.html", hasher.finish());
                        let path = dir.join(fname);
                        if std::fs::write(&path, &html).is_ok() {
                            html_path = Some(path.to_string_lossy().to_string());
                            if content.is_none() {
                                content = Some(crate::sources::parse_news_html(&html));
                            }
                        }
                    }
                    let bookmark = crate::state::types::NewsBookmark {
                        item,
                        content,
                        html_path,
                    };
                    app.add_news_bookmark(bookmark);
                    app.toast_message = Some(crate::i18n::t(
                        app,
                        "app.results.options_menu.news_management",
                    ));
                    app.toast_expires_at =
                        Some(std::time::Instant::now() + std::time::Duration::from_secs(2));
                }
                return true;
            }
            if let Some(item) = app.results.get(app.selected).cloned() {
                if app.installed_only_mode {
                    crate::logic::add_to_remove_list(app, item);
                    crate::events::utils::refresh_remove_details(app, details_tx);
                } else {
                    let _ = add_tx.send(item);
                }
            }
            true
        }
        _ => false,
    }
}

/// What: Handle preflight modal opening.
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if preflight was opened, `false` otherwise
///
/// Details:
/// - Opens preflight modal for the selected package using configured key or Enter.
fn handle_preflight_open(ke: &KeyEvent, app: &mut AppState) -> bool {
    // Don't open preflight if Ctrl is held (might be Ctrl+M interpreted as Enter)
    if ke.modifiers.contains(KeyModifiers::CONTROL) {
        tracing::debug!(
            "[NormalMode] Key with Ctrl detected in handle_preflight_open, ignoring (likely Ctrl+M): code={:?}",
            ke.code
        );
        return false;
    }

    let should_open = matches_any(ke, &app.keymap.search_install)
        || matches!(ke.code, KeyCode::Char('\n' | '\r') | KeyCode::Enter);

    if should_open && let Some(item) = app.results.get(app.selected).cloned() {
        tracing::debug!("[NormalMode] Opening preflight for package: {}", item.name);
        open_preflight_modal(app, vec![item], true);
        return true;
    }
    false
}

/// What: Handle pane navigation (Left/Right arrows and `pane_next`).
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request details for the focused item
/// - `preview_tx`: Channel to request preview details when moving focus
///
/// Output:
/// - `true` if pane navigation was handled, `false` otherwise
///
/// Details:
/// - Handles Left/Right arrow keys and configured `pane_next` key.
/// - Switches focus between panes and updates details accordingly.
fn handle_pane_navigation(
    ke: &KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    match ke.code {
        KeyCode::Right => {
            navigate_pane(app, "right", details_tx, preview_tx);
            true
        }
        KeyCode::Left => {
            navigate_pane(app, "left", details_tx, preview_tx);
            true
        }
        _ if matches_any(ke, &app.keymap.pane_next) => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                app.focus = crate::state::Focus::Install;
                return true;
            }
            if app.installed_only_mode {
                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));
                }
                app.focus = crate::state::Focus::Install;
                crate::events::utils::refresh_downgrade_details(app, details_tx);
            } else {
                if app.install_state.selected().is_none() && !app.install_list.is_empty() {
                    app.install_state.select(Some(0));
                }
                app.focus = crate::state::Focus::Install;
                refresh_install_details(app, details_tx);
            }
            true
        }
        _ => false,
    }
}

/// What: Handle input clearing.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `query_tx`: Channel to send debounced search queries
///
/// Output:
/// - None (modifies app state directly)
///
/// Details:
/// - Clears the entire search input and resets caret/selection.
fn handle_input_clear(app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>) {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        if !app.news_search_input.is_empty() {
            app.news_search_input.clear();
            app.news_search_caret = 0;
            app.news_search_select_anchor = None;
            app.last_input_change = std::time::Instant::now();
            app.last_saved_value = None;
            app.refresh_news_results();
        }
    } else if !app.input.is_empty() {
        app.input.clear();
        app.search_caret = 0;
        app.search_select_anchor = None;
        app.last_input_change = std::time::Instant::now();
        app.last_saved_value = None;
        send_query(app, query_tx);
    }
}

/// What: Mark or unmark the selected News Feed item as read.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `mark_read`: Whether to mark as read (`true`) or unread (`false`)
///
/// Output:
/// - `true` if state changed (set updated), `false` otherwise
///
/// Details:
/// - Updates both the ID-based read set and the legacy URL set when available.
/// - Refreshes news results to honor read/unread filtering.
fn mark_news_feed_item(app: &mut AppState, mark_read: bool) -> bool {
    let Some(item) = app.news_results.get(app.news_selected).cloned() else {
        return false;
    };

    let is_read_before = app.news_read_ids.contains(&item.id)
        || item
            .url
            .as_ref()
            .is_some_and(|u| app.news_read_urls.contains(u));

    let mut changed = false;

    if mark_read {
        if !is_read_before {
            app.news_read_ids_dirty = true;
            app.news_read_dirty = app.news_read_dirty || item.url.is_some();
            changed = true;
        }
        app.news_read_ids.insert(item.id.clone());
        if let Some(url) = item.url.as_ref() {
            app.news_read_urls.insert(url.clone());
        }
    } else {
        if is_read_before {
            app.news_read_ids_dirty = true;
            app.news_read_dirty = app.news_read_dirty || item.url.is_some();
            changed = true;
        }
        app.news_read_ids.remove(&item.id);
        if let Some(url) = item.url.as_ref() {
            app.news_read_urls.remove(url);
        }
    }

    if changed {
        app.refresh_news_results();
    }
    changed
}

/// What: Toggle read/unread state for the selected News Feed item.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if state changed (toggled), `false` otherwise
///
/// Details:
/// - Considers both ID-based and legacy URL-based read state for determining current status.
fn toggle_news_feed_item(app: &mut AppState) -> bool {
    let Some(item) = app.news_results.get(app.news_selected).cloned() else {
        return false;
    };
    let is_read = app.news_read_ids.contains(&item.id)
        || item
            .url
            .as_ref()
            .is_some_and(|u| app.news_read_urls.contains(u));
    if is_read {
        mark_news_feed_item(app, false)
    } else {
        mark_news_feed_item(app, true)
    }
}

/// What: Handle news mode keybindings.
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if a news keybinding was handled, `false` otherwise
///
/// Details:
/// - Handles mark read, mark unread, and toggle read keybindings in News mode.
fn handle_news_mode_keybindings(ke: &KeyEvent, app: &mut AppState) -> bool {
    if !matches!(app.app_mode, crate::state::types::AppMode::News) {
        return false;
    }

    if matches_any(ke, &app.keymap.news_mark_read_feed) {
        if mark_news_feed_item(app, true) {
            return true;
        }
    } else if matches_any(ke, &app.keymap.news_mark_unread_feed) {
        if mark_news_feed_item(app, false) {
            return true;
        }
    } else if matches_any(ke, &app.keymap.news_toggle_read_feed) && toggle_news_feed_item(app) {
        return true;
    }

    false
}

/// What: Handle keymap-based action keybindings.
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `app`: Mutable application state
/// - `query_tx`: Channel to send debounced search queries
///
/// Output:
/// - `true` if a keymap action was handled, `false` otherwise
///
/// Details:
/// - Handles status, import, export, updates, insert mode, selection, delete, and clear actions.
fn handle_keymap_actions(
    ke: &KeyEvent,
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<QueryInput>,
) -> bool {
    if matches_any(ke, &app.keymap.search_normal_open_status) {
        crate::util::open_url("https://status.archlinux.org");
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_import) {
        if !app.installed_only_mode {
            app.modal = crate::state::Modal::ImportHelp;
        }
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_export) {
        handle_export(app);
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_updates) {
        if matches!(app.app_mode, crate::state::types::AppMode::News) {
            crate::events::mouse::handle_news_button(app);
        } else {
            crate::events::mouse::handle_updates_button(app);
        }
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_insert) {
        app.search_normal_mode = false;
        app.search_select_anchor = None;
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_select_left) {
        handle_selection_move(app, -1);
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_select_right) {
        handle_selection_move(app, 1);
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_delete) {
        handle_selection_delete(app, query_tx);
        return true;
    }

    if matches_any(ke, &app.keymap.search_normal_clear) {
        handle_input_clear(app, query_tx);
        return true;
    }

    false
}

/// What: Handle AUR vote key actions in Search normal mode.
///
/// Inputs:
/// - `ke`: Key event from terminal.
/// - `app`: Mutable application state.
///
/// Output:
/// - `true` when key was consumed for vote flow; otherwise `false`.
///
/// Details:
/// - `Ctrl+e` opens a vote/unvote confirmation based on current cached vote-state.
/// - Only available in package mode and for selected AUR items.
/// - Uses app runtime dry-run indicator in confirmation content.
fn handle_aur_vote_action(ke: &KeyEvent, app: &mut AppState) -> bool {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        return false;
    }

    let trigger_pressed = match (ke.code, ke.modifiers) {
        (KeyCode::Char('e' | 'E'), mods)
            if mods.contains(KeyModifiers::CONTROL) && !mods.contains(KeyModifiers::ALT) =>
        {
            !mods.contains(KeyModifiers::SHIFT)
        }
        _ => false,
    };
    if !trigger_pressed {
        return false;
    }

    let Some(item) = app.results.get(app.selected) else {
        return true;
    };
    if !matches!(item.source, crate::state::Source::Aur) {
        app.toast_message = Some("AUR vote is only available for AUR packages.".to_string());
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        return true;
    }
    let action = match app.aur_vote_state_by_pkgbase.get(&item.name) {
        Some(crate::state::app_state::AurVoteStateUi::Voted) => VoteAction::Unvote,
        _ => VoteAction::Vote,
    };

    let settings = crate::theme::settings();
    if !settings.aur_vote_enabled {
        app.modal = crate::state::Modal::Alert {
            message: "AUR voting is disabled. Enable aur_vote_enabled in settings.conf."
                .to_string(),
        };
        return true;
    }

    if app.pending_aur_vote_request.is_some() {
        app.toast_message = Some("An AUR vote request is already queued.".to_string());
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        return true;
    }
    if app.pending_aur_vote_intent.is_some() {
        app.toast_message = Some("An AUR vote confirmation is already open.".to_string());
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        return true;
    }

    let action_label = match action {
        VoteAction::Vote => "vote",
        VoteAction::Unvote => "unvote",
    };
    let dry_run_line = if app.dry_run {
        "Dry-run enabled: no remote mutation will be performed."
    } else {
        "This action will contact aur.archlinux.org over SSH."
    };
    app.pending_aur_vote_intent = Some((item.name.clone(), action));
    app.modal = crate::state::Modal::ConfirmAurVote {
        pkgbase: item.name.clone(),
        action,
        message: format!(
            "Confirm AUR {action_label} for '{}'?\n\n{dry_run_line}\n\nPress Enter to continue, Esc/q to cancel.",
            item.name
        ),
    };
    true
}

/// What: Handle key events in Normal mode for the Search pane.
///
/// Inputs:
/// - `ke`: Key event received from the terminal
/// - `app`: Mutable application state
/// - `query_tx`: Channel to send debounced search queries
/// - `details_tx`: Channel to request details for the focused item
/// - `add_tx`: Channel to add items to the Install/Remove lists
/// - `preview_tx`: Channel to request preview details when moving focus
///
/// Output:
/// - `true` if the key was handled and should stop further processing; `false` otherwise
///
/// Details:
/// - Handles vim-like navigation, selection, deletion, menu toggles, import/export, and preflight opening.
/// - Supports numeric selection for config menu items.
pub fn handle_normal_mode(
    ke: KeyEvent,
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<QueryInput>,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    add_tx: &mpsc::UnboundedSender<PackageItem>,
    preview_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
) -> bool {
    // Handle numeric selection for config menu (1-9)
    if let KeyCode::Char(ch) = ke.code
        && ch.is_ascii_digit()
        && ch != '0'
    {
        let idx = (ch as u8 - b'1') as usize;
        if handle_config_menu_numeric_selection(idx, app) {
            return false;
        }
    }

    // Handle news mode keybindings
    if handle_news_mode_keybindings(&ke, app) {
        return false;
    }

    // Handle menu toggles
    let menu_toggled = {
        let km = &app.keymap;
        matches_any(&ke, &km.config_menu_toggle)
            || matches_any(&ke, &km.options_menu_toggle)
            || matches_any(&ke, &km.panels_menu_toggle)
    };
    if menu_toggled && handle_menu_toggles(&ke, app) {
        return false;
    }

    // Handle keymap-based actions
    if handle_keymap_actions(&ke, app, query_tx) {
        return false;
    }

    // Handle AUR vote/unvote action keys.
    if handle_aur_vote_action(&ke, app) {
        return false;
    }

    // Handle navigation keys
    if handle_navigation(&ke, app, details_tx, comments_tx) {
        return false;
    }

    // Handle space key
    if handle_space_key(&ke, app, details_tx, add_tx) {
        return false;
    }

    // Handle preflight opening
    if handle_preflight_open(&ke, app) {
        return false;
    }

    // Handle pane navigation
    if handle_pane_navigation(&ke, app, details_tx, preview_tx) {
        return false;
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::types::{AppMode, NewsFeedItem, NewsFeedSource};
    use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
    use tokio::sync::mpsc;

    fn make_news_item(id: &str, url: &str) -> NewsFeedItem {
        NewsFeedItem {
            id: id.to_string(),
            date: "2025-01-01".to_string(),
            title: format!("Item {id}"),
            summary: None,
            url: Some(url.to_string()),
            source: NewsFeedSource::ArchNews,
            severity: None,
            packages: vec![],
        }
    }

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent {
            code,
            modifiers: KeyModifiers::empty(),
            kind: KeyEventKind::Press,
            state: KeyEventState::empty(),
        }
    }

    #[test]
    fn mark_news_feed_item_sets_read_state() {
        let item = make_news_item("one", "https://example.com/one");
        let mut app = AppState {
            app_mode: AppMode::News,
            news_items: vec![item.clone()],
            news_results: vec![item],
            news_selected: 0,
            news_max_age_days: None,
            ..AppState::default()
        };

        let changed = mark_news_feed_item(&mut app, true);
        assert!(changed);
        assert!(app.news_read_ids.contains("one"));
        assert!(app.news_read_ids_dirty);
        assert!(app.news_read_urls.contains("https://example.com/one"));
        assert!(app.news_read_dirty);

        let changed_unread = mark_news_feed_item(&mut app, false);
        assert!(changed_unread);
        assert!(!app.news_read_ids.contains("one"));
        assert!(app.news_read_ids_dirty);
    }

    #[test]
    fn toggle_news_feed_item_respects_legacy_url_state() {
        let item = make_news_item("two", "https://example.com/two");
        let mut app = AppState {
            app_mode: AppMode::News,
            news_items: vec![item.clone()],
            news_results: vec![item],
            news_selected: 0,
            news_max_age_days: None,
            ..AppState::default()
        };
        app.news_read_urls.insert("https://example.com/two".into());
        app.news_read_dirty = true;

        let toggled = toggle_news_feed_item(&mut app);
        assert!(toggled);
        assert!(!app.news_read_ids.contains("two"));
        assert!(!app.news_read_urls.contains("https://example.com/two"));
        assert!(app.news_read_ids_dirty);
        assert!(app.news_read_dirty);
    }

    #[test]
    fn handle_normal_mode_marks_read_via_keybinding() {
        let item = make_news_item("three", "https://example.com/three");
        let mut app = AppState {
            app_mode: AppMode::News,
            news_items: vec![item.clone()],
            news_results: vec![item],
            news_selected: 0,
            ..AppState::default()
        };
        let (query_tx, _query_rx) = mpsc::unbounded_channel();
        let (details_tx, _details_rx) = mpsc::unbounded_channel();
        let (add_tx, _add_rx) = mpsc::unbounded_channel();
        let (preview_tx, _preview_rx) = mpsc::unbounded_channel();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel();

        let ke = key(KeyCode::Char('r'));
        let handled = handle_normal_mode(
            ke,
            &mut app,
            &query_tx,
            &details_tx,
            &add_tx,
            &preview_tx,
            &comments_tx,
        );
        assert!(!handled);
        assert!(app.news_read_ids.contains("three"));
    }
}