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
use crossterm::event::KeyEvent;
use tokio::sync::mpsc;

use crate::state::{AppState, PackageItem};
use std::time::Instant;

/// What: Check if a key event matches any chord in a list, handling Shift+char edge cases.
///
/// Inputs:
/// - `ke`: Key event from terminal
/// - `list`: List of configured key chords to match against
///
/// Output:
/// - `true` if the key event matches any chord in the list, `false` otherwise
///
/// Details:
/// - Treats Shift+<char> from config as equivalent to uppercase char without Shift from terminal.
/// - Handles cases where terminals report Shift inconsistently.
#[must_use]
pub fn matches_any(ke: &KeyEvent, list: &[crate::theme::KeyChord]) -> bool {
    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);
                if !cfg_has_shift {
                    return false;
                }
                // Accept uppercase event regardless of SHIFT flag
                if ev_ch == cfg_ch.to_ascii_uppercase() {
                    return true;
                }
                // Accept lowercase char if terminal reports SHIFT in modifiers
                if ke.modifiers.contains(crossterm::event::KeyModifiers::SHIFT)
                    && ev_ch.to_ascii_lowercase() == cfg_ch
                {
                    return true;
                }
                false
            }
            _ => false,
        }
    })
}

/// What: Return the number of Unicode scalar values (characters) in the input.
///
/// Input: `s` string to measure
/// Output: Character count as `usize`
///
/// Details: Counts Unicode scalar values using `s.chars().count()`.
#[must_use]
pub fn char_count(s: &str) -> usize {
    s.chars().count()
}

/// What: Convert a character index to a byte index for slicing.
///
/// Input: `s` source string; `ci` character index
/// Output: Byte index into `s` corresponding to `ci`
///
/// Details: Returns 0 for `ci==0`; returns `s.len()` when `ci>=char_count(s)`; otherwise maps
/// the character index to a byte offset via `char_indices()`.
#[must_use]
pub fn byte_index_for_char(s: &str, ci: usize) -> usize {
    let cc = char_count(s);
    if ci == 0 {
        return 0;
    }
    if ci >= cc {
        return s.len();
    }
    s.char_indices()
        .map(|(i, _)| i)
        .nth(ci)
        .map_or(s.len(), |i| i)
}

/// What: Advance selection in the Recent pane to the next/previous match of the pane-find pattern.
///
/// Input: `app` mutable application state; `forward` when true searches downward, else upward
/// Output: No return value; updates `history_state` selection when a match is found
///
/// Details: Searches within the filtered Recent indices and wraps around the list; matching is
/// case-insensitive against the current pane-find pattern.
pub fn find_in_recent(app: &mut AppState, forward: bool) {
    let Some(pattern) = app.pane_find.clone() else {
        return;
    };
    let inds = crate::ui::helpers::filtered_recent_indices(app);
    if inds.is_empty() {
        return;
    }
    let start = app.history_state.selected().unwrap_or(0);
    let mut vi = start;
    let n = inds.len();
    for _ in 0..n {
        vi = if forward {
            (vi + 1) % n
        } else if vi == 0 {
            n - 1
        } else {
            vi - 1
        };
        let i = inds[vi];
        if let Some(s) = app.recent_value_at(i)
            && s.to_lowercase().contains(&pattern.to_lowercase())
        {
            app.history_state.select(Some(vi));
            break;
        }
    }
}

/// What: Advance selection in the Install pane to the next/previous item matching the pane-find pattern.
///
/// Input: `app` mutable application state; `forward` when true searches downward, else upward
/// Output: No return value; updates `install_state` selection when a match is found
///
/// Details: Operates on visible indices and tests case-insensitive matches against package name
/// or description; wraps around the list.
pub fn find_in_install(app: &mut AppState, forward: bool) {
    let Some(pattern) = app.pane_find.clone() else {
        return;
    };
    let inds = crate::ui::helpers::filtered_install_indices(app);
    if inds.is_empty() {
        return;
    }
    let start = app.install_state.selected().unwrap_or(0);
    let mut vi = start;
    let n = inds.len();
    for _ in 0..n {
        vi = if forward {
            (vi + 1) % n
        } else if vi == 0 {
            n - 1
        } else {
            vi - 1
        };
        let i = inds[vi];
        if let Some(p) = app.install_list.get(i)
            && (p.name.to_lowercase().contains(&pattern.to_lowercase())
                || p.description
                    .to_lowercase()
                    .contains(&pattern.to_lowercase()))
        {
            app.install_state.select(Some(vi));
            break;
        }
    }
}

/// What: Ensure details reflect the currently selected result.
///
/// Input: `app` mutable application state; `details_tx` channel for details requests
/// Output: No return value; uses cache or sends a details request
///
/// Details: If details for the selected item exist in the cache, they are applied immediately;
/// otherwise, the item is sent over `details_tx` to be fetched asynchronously.
pub fn refresh_selected_details(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    if let Some(item) = app.results.get(app.selected).cloned() {
        // Reset scroll when package changes
        app.details_scroll = 0;
        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
            app.details = cached;
        } else {
            let _ = details_tx.send(item);
        }
        queue_selected_aur_vote_state_check(app);
    }
}

/// What: Queue a live AUR vote-state check for the currently selected result.
///
/// Inputs:
/// - `app`: Mutable application state with current results selection.
///
/// Output:
/// - None (updates vote-state cache and pending request fields).
///
/// Details:
/// - Only queues checks for selected AUR packages when AUR voting is enabled.
/// - Marks selected package as `Loading` and stores a single pending request.
/// - Replaces an older pending request when selection changes rapidly.
pub fn queue_selected_aur_vote_state_check(app: &mut AppState) {
    let settings = crate::theme::settings();
    if !settings.aur_vote_enabled {
        return;
    }
    if !app.aur_vote_state_lookup_supported {
        return;
    }
    let Some(item) = app.results.get(app.selected) else {
        return;
    };
    if !matches!(item.source, crate::state::Source::Aur) {
        return;
    }

    let pkgbase = item.name.clone();
    if let Some(previous) = app.pending_aur_vote_state_request.replace(pkgbase.clone())
        && previous != pkgbase
        && matches!(
            app.aur_vote_state_by_pkgbase.get(&previous),
            Some(crate::state::app_state::AurVoteStateUi::Loading)
        )
    {
        app.aur_vote_state_by_pkgbase
            .insert(previous, crate::state::app_state::AurVoteStateUi::Unknown);
    }
    let should_mark_loading = !matches!(
        app.aur_vote_state_by_pkgbase.get(&pkgbase),
        Some(
            crate::state::app_state::AurVoteStateUi::Voted
                | crate::state::app_state::AurVoteStateUi::NotVoted
        )
    );
    if should_mark_loading {
        app.aur_vote_state_by_pkgbase
            .insert(pkgbase, crate::state::app_state::AurVoteStateUi::Loading);
    }
}

/// What: Move selection and queue live AUR vote-state check for selected package.
///
/// Inputs:
/// - `app`: Mutable application state.
/// - `delta`: Signed selection movement.
/// - `details_tx`: Channel for async details requests.
/// - `comments_tx`: Channel for async AUR comments requests.
///
/// Output:
/// - None (mutates selection/details state and queues optional vote-state check).
///
/// Details:
/// - Uses existing `logic::move_sel_cached` for selection/details coordination.
/// - Then schedules live vote-state check for selected AUR package.
pub fn move_sel_cached_with_vote_state(
    app: &mut AppState,
    delta: isize,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
) {
    crate::logic::move_sel_cached(app, delta, details_tx, comments_tx);
    queue_selected_aur_vote_state_check(app);
}

/// Move news selection by delta, keeping it in view.
pub fn move_news_selection(app: &mut AppState, delta: isize) {
    if app.news_results.is_empty() {
        app.news_selected = 0;
        app.news_list_state.select(None);
        app.details.url.clear();
        return;
    }
    let len = app.news_results.len();
    if app.news_selected >= len {
        app.news_selected = len.saturating_sub(1);
    }
    app.news_list_state.select(Some(app.news_selected));
    let steps = delta.unsigned_abs();
    for _ in 0..steps {
        if delta.is_negative() {
            app.news_list_state.select_previous();
        } else {
            app.news_list_state.select_next();
        }
    }
    let sel = app.news_list_state.selected().unwrap_or(0);
    app.news_selected = std::cmp::min(sel, len.saturating_sub(1));
    app.news_list_state.select(Some(app.news_selected));
    update_news_url(app);
}

/// What: Compute updates-modal scroll offset that keeps the selected entry visible.
///
/// Inputs:
/// - `entry_line_starts`: Mapping from entry index to first rendered line in wrapped output.
/// - `total_lines`: Total rendered line count across wrapped updates rows.
/// - `content_rect`: Optional updates content rectangle tuple `(x, y, width, height)`.
/// - `selected`: Selected entry index.
/// - `total_items`: Number of entries in the updates list.
/// - `current_scroll`: Existing scroll offset before adjustment.
///
/// Output:
/// - Returns the next clamped scroll offset as `u16`.
///
/// Details:
/// - Derives `visible_lines` from `content_rect` height and falls back to `1` when absent.
/// - Uses rendered-line mapping to support wrapped rows consistently.
/// - Clamps output to valid range to prevent underflow/overscroll.
#[must_use]
pub fn compute_updates_modal_scroll_for_selection(
    entry_line_starts: &[u16],
    total_lines: u16,
    content_rect: Option<(u16, u16, u16, u16)>,
    selected: usize,
    total_items: usize,
    current_scroll: u16,
) -> u16 {
    let selected_line = entry_line_starts
        .get(selected)
        .copied()
        .unwrap_or_else(|| u16::try_from(selected).unwrap_or(u16::MAX));
    let visible_lines = content_rect.map_or(1, |(_, _, _, h)| h.max(1));
    let mut scroll = current_scroll;

    if selected_line < scroll {
        scroll = selected_line;
    } else if selected_line >= scroll.saturating_add(visible_lines) {
        scroll = selected_line.saturating_sub(visible_lines.saturating_sub(1));
    }

    let fallback_total = u16::try_from(total_items).unwrap_or(u16::MAX);
    let max_scroll = total_lines
        .max(fallback_total)
        .saturating_sub(visible_lines);
    scroll.min(max_scroll)
}

/// What: Compute visible updates indices for a slash-filter query.
///
/// Inputs:
/// - `entries`: Full updates entries (`name`, `old_version`, `new_version`).
/// - `query`: Filter query string entered in Updates modal.
///
/// Output:
/// - Stable vector of original-entry indices that match query order.
///
/// Details:
/// - Empty/whitespace query returns all entries.
/// - Matching is fuzzy + case-insensitive against package name and source label.
/// - Source labels are lowercase: `pacman` for official packages and `aur` for AUR packages.
#[must_use]
pub fn compute_updates_filtered_indices(
    entries: &[(String, String, String)],
    query: &str,
) -> Vec<usize> {
    let normalized = query.trim();
    if normalized.is_empty() {
        return (0..entries.len()).collect();
    }

    let query_lower = normalized.to_lowercase();

    entries
        .iter()
        .enumerate()
        .filter_map(|(idx, (name, _, _))| {
            let source_label = if crate::index::find_package_by_name(name).is_some() {
                "pacman"
            } else {
                "aur"
            };
            let name_lower = name.to_lowercase();
            let matches_name = crate::util::fuzzy_match_rank(&name_lower, &query_lower).is_some();
            let matches_source =
                crate::util::fuzzy_match_rank(source_label, &query_lower).is_some();
            if matches_name || matches_source {
                Some(idx)
            } else {
                None
            }
        })
        .collect()
}

/// Synchronize details URL and content with currently selected news item.
/// Also triggers content fetching if channel is provided and content is not cached.
pub fn update_news_url(app: &mut AppState) {
    if let Some(item) = app.news_results.get(app.news_selected)
        && let Some(url) = &item.url
    {
        app.details.url.clone_from(url);
        // Check if content is cached
        let mut cached = app.news_content_cache.get(url).cloned();
        if let Some(ref c) = cached
            && url.contains("://archlinux.org/packages/")
            && !c.starts_with("Package Info:")
        {
            // Cached pre-metadata version: force refresh
            cached = None;
            tracing::debug!(
                url,
                "news content cache missing package metadata; will refetch"
            );
        }
        app.news_content = cached;
        if app.news_content.is_some() {
            tracing::debug!(url, "news content served from cache");
        } else {
            // Content not cached - set debounce timer to wait 0.5 seconds before fetching
            app.news_content_debounce_timer = Some(std::time::Instant::now());
            tracing::debug!(url, "news content not cached, setting debounce timer");
        }
        app.news_content_scroll = 0;
    } else {
        app.details.url.clear();
        app.news_content = None;
        app.news_content_debounce_timer = None;
    }
    app.news_content_loading = false;
}

/// Request news content fetch if not cached or loading.
/// Implements 0.5 second debounce - only requests after user stays on item for 0.5 seconds.
pub fn maybe_request_news_content(
    app: &mut AppState,
    news_content_req_tx: &mpsc::UnboundedSender<String>,
) {
    // Only request if in news mode with a selected item that has a URL
    if !matches!(app.app_mode, crate::state::types::AppMode::News) {
        tracing::trace!("news_content: skip request, not in news mode");
        return;
    }
    if app.news_content_loading {
        tracing::debug!(
            selected = app.news_selected,
            "news_content: skip request, already loading"
        );
        return;
    }
    if let Some(item) = app.news_results.get(app.news_selected)
        && let Some(url) = &item.url
        && app.news_content.is_none()
        && !app.news_content_cache.contains_key(url)
    {
        // Check debounce timer - only request after 0.5 seconds of staying on the item
        // 500ms balances user experience with server load: long enough to avoid excessive
        // fetches during rapid navigation, short enough to feel responsive.
        const DEBOUNCE_DELAY_MS: u64 = 500;
        if let Some(timer) = app.news_content_debounce_timer {
            // Safe to unwrap: elapsed will be small (well within u64)
            #[allow(clippy::cast_possible_truncation)]
            let elapsed = timer.elapsed().as_millis() as u64;
            if elapsed < DEBOUNCE_DELAY_MS {
                // Debounce not expired yet - wait longer
                tracing::trace!(
                    selected = app.news_selected,
                    url,
                    elapsed_ms = elapsed,
                    remaining_ms = DEBOUNCE_DELAY_MS - elapsed,
                    "news_content: debounce timer not expired, waiting"
                );
                return;
            }
            // Debounce expired - clear timer and proceed with request
            app.news_content_debounce_timer = None;
        } else {
            // No debounce timer set - this shouldn't happen, but set it now
            app.news_content_debounce_timer = Some(std::time::Instant::now());
            tracing::debug!(
                selected = app.news_selected,
                url,
                "news_content: no debounce timer, setting one now"
            );
            return;
        }

        app.news_content_loading = true;
        app.news_content_loading_since = Some(Instant::now());
        tracing::debug!(
            selected = app.news_selected,
            title = item.title,
            url,
            "news_content: requesting article content (debounce expired)"
        );
        if let Err(e) = news_content_req_tx.send(url.clone()) {
            tracing::warn!(
                error = %e,
                selected = app.news_selected,
                title = item.title,
                url,
                "news_content: failed to enqueue content request"
            );
            app.news_content_loading = false;
            app.news_content_loading_since = None;
            app.news_content = Some(format!("Failed to load content: {e}"));
            app.toast_message = Some("News content request failed".to_string());
            app.toast_expires_at = Some(Instant::now() + std::time::Duration::from_secs(3));
        }
    } else {
        tracing::trace!(
            selected = app.news_selected,
            has_item = app.news_results.get(app.news_selected).is_some(),
            has_url = app
                .news_results
                .get(app.news_selected)
                .and_then(|it| it.url.as_ref())
                .is_some(),
            content_cached = app
                .news_results
                .get(app.news_selected)
                .and_then(|it| it.url.as_ref())
                .is_some_and(|u| app.news_content_cache.contains_key(u)),
            has_content = app.news_content.is_some(),
            "news_content: skip request (cached/absent URL/already loaded)"
        );
    }
}

/// What: Ensure details reflect the selected item in the Install pane.
///
/// Input: `app` mutable application state; `details_tx` channel for details requests
/// Output: No return value; focuses details on the selected Install item and uses cache or requests fetch
///
/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
/// cache when present; otherwise sends a request over `details_tx`.
pub fn refresh_install_details(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    let Some(vsel) = app.install_state.selected() else {
        return;
    };
    let inds = crate::ui::helpers::filtered_install_indices(app);
    if inds.is_empty() || vsel >= inds.len() {
        return;
    }
    let i = inds[vsel];
    if let Some(item) = app.install_list.get(i).cloned() {
        // Reset scroll when package changes
        app.details_scroll = 0;
        // Focus details on the install selection
        app.details_focus = Some(item.name.clone());

        // Provide an immediate placeholder reflecting the selection
        app.details.name.clone_from(&item.name);
        app.details.version.clone_from(&item.version);
        app.details.description.clear();
        match &item.source {
            crate::state::Source::Official { repo, arch } => {
                app.details.repository.clone_from(repo);
                app.details.architecture.clone_from(arch);
            }
            crate::state::Source::Aur => {
                app.details.repository = "AUR".to_string();
                app.details.architecture = "any".to_string();
            }
        }

        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
            app.details = cached;
        } else {
            let _ = details_tx.send(item);
        }
    }
}

/// What: Ensure details reflect the selected item in the Remove pane.
///
/// Input: `app` mutable application state; `details_tx` channel for details requests
/// Output: No return value; focuses details on the selected Remove item and uses cache or requests fetch
///
/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
/// cache when present; otherwise sends a request over `details_tx`.
pub fn refresh_remove_details(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
    let Some(vsel) = app.remove_state.selected() else {
        return;
    };
    if app.remove_list.is_empty() || vsel >= app.remove_list.len() {
        return;
    }
    if let Some(item) = app.remove_list.get(vsel).cloned() {
        // Reset scroll when package changes
        app.details_scroll = 0;
        app.details_focus = Some(item.name.clone());
        app.details.name.clone_from(&item.name);
        app.details.version.clone_from(&item.version);
        app.details.description.clear();
        match &item.source {
            crate::state::Source::Official { repo, arch } => {
                app.details.repository.clone_from(repo);
                app.details.architecture.clone_from(arch);
            }
            crate::state::Source::Aur => {
                app.details.repository = "AUR".to_string();
                app.details.architecture = "any".to_string();
            }
        }
        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
            app.details = cached;
        } else {
            let _ = details_tx.send(item);
        }
    }
}

/// What: Ensure details reflect the selected item in the Downgrade pane.
///
/// Input: `app` mutable application state; `details_tx` channel for details requests
/// Output: No return value; focuses details on the selected Downgrade item and uses cache or requests fetch
///
/// Details: Sets `details_focus`, populates a placeholder from the selected item, then uses the
/// cache when present; otherwise sends a request over `details_tx`.
pub fn refresh_downgrade_details(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    let Some(vsel) = app.downgrade_state.selected() else {
        return;
    };
    if app.downgrade_list.is_empty() || vsel >= app.downgrade_list.len() {
        return;
    }
    if let Some(item) = app.downgrade_list.get(vsel).cloned() {
        // Reset scroll when package changes
        app.details_scroll = 0;
        app.details_focus = Some(item.name.clone());
        app.details.name.clone_from(&item.name);
        app.details.version.clone_from(&item.version);
        app.details.description.clear();
        match &item.source {
            crate::state::Source::Official { repo, arch } => {
                app.details.repository.clone_from(repo);
                app.details.architecture.clone_from(arch);
            }
            crate::state::Source::Aur => {
                app.details.repository = "AUR".to_string();
                app.details.architecture = "any".to_string();
            }
        }
        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
            app.details = cached;
        } else {
            let _ = details_tx.send(item);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// What: Produce a baseline `AppState` tailored for utils tests.
    ///
    /// Inputs:
    /// - None; relies on `Default::default()` for deterministic state.
    ///
    /// Output:
    /// - Fresh `AppState` instance for individual unit tests.
    ///
    /// Details:
    /// - Centralizes setup so each test starts from a clean copy without repeated boilerplate.
    fn new_app() -> AppState {
        AppState::default()
    }

    #[test]
    /// What: Ensure `char_count` returns the number of Unicode scalar values.
    ///
    /// Inputs:
    /// - Strings `"abc"`, `"π"`, and `"aπb"`.
    ///
    /// Output:
    /// - Counts `3`, `1`, and `3` respectively.
    ///
    /// Details:
    /// - Demonstrates correct handling of multi-byte characters.
    fn char_count_basic() {
        assert_eq!(char_count("abc"), 3);
        assert_eq!(char_count("Ï€"), 1);
        assert_eq!(char_count("aπb"), 3);
    }

    #[test]
    /// What: Verify `byte_index_for_char` translates character indices to UTF-8 byte offsets.
    ///
    /// Inputs:
    /// - String `"aπb"` with char indices 0 through 3.
    ///
    /// Output:
    /// - Returns byte offsets `0`, `1`, `3`, and `len`.
    ///
    /// Details:
    /// - Confirms the function respects variable-width encoding.
    fn byte_index_for_char_basic() {
        let s = "aπb";
        assert_eq!(byte_index_for_char(s, 0), 0);
        assert_eq!(byte_index_for_char(s, 1), 1);
        assert_eq!(byte_index_for_char(s, 2), 1 + "Ï€".len());
        assert_eq!(byte_index_for_char(s, 3), s.len());
    }

    #[test]
    /// What: Ensure `find_in_recent` cycles through entries matching the pane filter.
    ///
    /// Inputs:
    /// - Recent list `alpha`, `beta`, `gamma` with filter `"a"`.
    ///
    /// Output:
    /// - Selection rotates among matching entries without panicking.
    ///
    /// Details:
    /// - Provides smoke coverage for the wrap-around logic inside the helper.
    fn find_in_recent_basic() {
        let mut app = new_app();
        app.load_recent_items(&["alpha".to_string(), "beta".to_string(), "gamma".to_string()]);
        app.pane_find = Some("a".into());
        app.history_state.select(Some(0));
        find_in_recent(&mut app, true);
        assert!(app.history_state.selected().is_some());
    }

    #[test]
    /// What: Check `find_in_install` advances selection to the next matching entry by name or description.
    ///
    /// Inputs:
    /// - Install list with `ripgrep` and `fd`, filter term `"rip"` while selection starts on the second item.
    ///
    /// Output:
    /// - Selection wraps to the first item containing the filter term.
    ///
    /// Details:
    /// - Protects against regressions in forward search and wrap-around behaviour.
    fn find_in_install_basic() {
        let mut app = new_app();
        app.install_list = vec![
            crate::state::PackageItem {
                name: "ripgrep".into(),
                version: "1".into(),
                description: "fast search".into(),
                source: crate::state::Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            },
            crate::state::PackageItem {
                name: "fd".into(),
                version: "1".into(),
                description: "find".into(),
                source: crate::state::Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            },
        ];
        app.pane_find = Some("rip".into());
        // Start from visible selection 1 so advancing wraps to 0 matching "ripgrep"
        app.install_state.select(Some(1));
        find_in_install(&mut app, true);
        assert_eq!(app.install_state.selected(), Some(0));
    }

    #[test]
    /// What: Ensure `refresh_selected_details` dispatches a fetch when cache misses occur.
    ///
    /// Inputs:
    /// - Results list with a single entry and an empty details cache.
    ///
    /// Output:
    /// - Sends the selected item through `details_tx`, confirming a fetch request.
    ///
    /// Details:
    /// - Uses an unbounded channel to observe the request without performing actual I/O.
    fn refresh_selected_details_requests_when_missing() {
        let mut app = new_app();
        app.results = vec![crate::state::PackageItem {
            name: "rg".into(),
            version: "1".into(),
            description: String::new(),
            source: crate::state::Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];
        app.selected = 0;
        let (tx, mut rx) = mpsc::unbounded_channel();
        refresh_selected_details(&mut app, &tx);
        let got = rx.try_recv().ok();
        assert!(got.is_some());
    }

    #[test]
    /// What: Ensure vote-state checks are skipped when live lookup is unsupported.
    ///
    /// Inputs:
    /// - A selected AUR package with cached `Voted` state and lookup support disabled.
    ///
    /// Output:
    /// - No pending request is queued and cached state remains unchanged.
    ///
    /// Details:
    /// - Prevents replacing persisted stable vote-state with transient loading state
    ///   after the runtime detects unsupported `list-votes`.
    fn queue_vote_state_check_skips_when_lookup_unsupported() {
        let mut app = new_app();
        app.results = vec![crate::state::PackageItem {
            name: "pacsea-bin".into(),
            version: "1".into(),
            description: String::new(),
            source: crate::state::Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];
        app.selected = 0;
        app.aur_vote_state_lookup_supported = false;
        app.aur_vote_state_by_pkgbase.insert(
            "pacsea-bin".into(),
            crate::state::app_state::AurVoteStateUi::Voted,
        );

        queue_selected_aur_vote_state_check(&mut app);

        assert!(app.pending_aur_vote_state_request.is_none());
        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::Voted)
        ));
    }

    #[test]
    /// What: Ensure queuing live vote-state checks does not overwrite stable cached state.
    ///
    /// Inputs:
    /// - Selected AUR package with existing `Voted` cache.
    ///
    /// Output:
    /// - Request is queued, but cached state stays `Voted` instead of switching to `Loading`.
    ///
    /// Details:
    /// - Prevents stable persisted state from disappearing during transient live checks.
    fn queue_vote_state_check_preserves_stable_cached_state() {
        let mut app = new_app();
        app.results = vec![crate::state::PackageItem {
            name: "pacsea-bin".into(),
            version: "1".into(),
            description: String::new(),
            source: crate::state::Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];
        app.selected = 0;
        app.aur_vote_state_by_pkgbase.insert(
            "pacsea-bin".into(),
            crate::state::app_state::AurVoteStateUi::Voted,
        );

        queue_selected_aur_vote_state_check(&mut app);

        assert_eq!(
            app.pending_aur_vote_state_request,
            Some("pacsea-bin".to_string())
        );
        assert!(matches!(
            app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
            Some(crate::state::app_state::AurVoteStateUi::Voted)
        ));
    }

    #[test]
    /// What: Ensure missing updates content rect falls back to one visible line.
    ///
    /// Inputs:
    /// - Wrapped line starts with no viewport rect and selection on later entry.
    ///
    /// Output:
    /// - Scroll moves to selected line and remains clamped.
    ///
    /// Details:
    /// - Guards deterministic behavior when geometry is unavailable.
    fn updates_scroll_fallback_visible_lines_when_rect_missing() {
        let scroll = compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, None, 1, 3, 0);
        assert_eq!(scroll, 3);
    }

    #[test]
    /// What: Ensure tiny viewport heights still keep selected wrapped line visible.
    ///
    /// Inputs:
    /// - Height-1 and height-2 content rects with later selected entries.
    ///
    /// Output:
    /// - Scroll adjusts forward without overshooting bounds.
    ///
    /// Details:
    /// - Prevents regressions in very small terminal layouts.
    fn updates_scroll_handles_tiny_viewport_heights() {
        let height_one = Some((0, 0, 40, 1));
        let scroll_one =
            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_one, 1, 3, 0);
        assert_eq!(scroll_one, 3);

        let height_two = Some((0, 0, 40, 2));
        let scroll_two =
            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_two, 2, 3, 0);
        assert_eq!(scroll_two, 4);
    }

    #[test]
    /// What: Ensure large viewport clamps updates modal scroll to top.
    ///
    /// Inputs:
    /// - Viewport height greater than total rendered lines.
    ///
    /// Output:
    /// - Scroll returns to zero.
    ///
    /// Details:
    /// - Confirms no overscroll when all rows fit on screen.
    fn updates_scroll_clamps_to_zero_when_viewport_exceeds_total() {
        let large_rect = Some((0, 0, 40, 20));
        let scroll =
            compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, large_rect, 2, 3, 10);
        assert_eq!(scroll, 0);
    }

    #[test]
    /// What: Ensure updates filter returns all indices for empty query.
    ///
    /// Inputs:
    /// - Three updates entries and an empty query.
    ///
    /// Output:
    /// - Returns all original entry indices in stable order.
    ///
    /// Details:
    /// - Guards no-op filter behavior when slash mode is entered/cleared.
    fn updates_filter_returns_all_indices_for_empty_query() {
        let entries = vec![
            ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
            ("fd".to_string(), "8".to_string(), "9".to_string()),
            ("bat".to_string(), "1".to_string(), "2".to_string()),
        ];
        let indices = compute_updates_filtered_indices(&entries, "");
        assert_eq!(indices, vec![0, 1, 2]);
    }

    #[test]
    /// What: Ensure updates filter performs fuzzy case-insensitive package matching.
    ///
    /// Inputs:
    /// - Entries containing "ripgrep" and query "RG".
    ///
    /// Output:
    /// - Includes the "ripgrep" entry index.
    ///
    /// Details:
    /// - Validates phase-4 matcher behavior for shorthand package queries.
    fn updates_filter_matches_package_name_fuzzy_case_insensitive() {
        let entries = vec![
            ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
            ("fd".to_string(), "8".to_string(), "9".to_string()),
        ];
        let indices = compute_updates_filtered_indices(&entries, "RG");
        assert_eq!(indices, vec![0]);
    }

    #[test]
    /// What: Ensure updates filter can match source labels.
    ///
    /// Inputs:
    /// - Entries expected to include AUR rows and query "aur".
    ///
    /// Output:
    /// - Every returned index maps to an AUR package.
    ///
    /// Details:
    /// - Verifies source-label matching path used by slash filter.
    fn updates_filter_matches_source_label() {
        let entries = vec![
            (
                "pacsea-bin".to_string(),
                "0.9".to_string(),
                "1.0".to_string(),
            ),
            (
                "pacsea-git".to_string(),
                "0.9".to_string(),
                "1.0".to_string(),
            ),
        ];
        let indices = compute_updates_filtered_indices(&entries, "aur");
        assert!(
            !indices.is_empty(),
            "expected at least one AUR package available in fixture"
        );
        for idx in indices {
            let (name, _, _) = &entries[idx];
            assert!(crate::index::find_package_by_name(name).is_none());
        }
    }
}