tuisage 0.1.4

TUI application for interacting with CLI commands defined by usage specs
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
//! Reusable UI widget helpers and custom widgets for TuiSage panels.
//!
//! These helpers extract common patterns from the command, flag, and argument
//! list renderers to ensure consistent behavior across panels.
//!
//! Custom widgets implement [`ratatui::widgets::Widget`] for self-contained,
//! composable rendering of UI sections like the command preview and help bar.

use std::collections::{HashMap, HashSet};

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Padding, Paragraph, StatefulWidget, Widget, Wrap},
};

use crate::app::{fuzzy_match_indices, App, Focus, MatchScores};

use nucleo_matcher::{Config, Matcher};
use ratatui_themes::ThemePalette;

/// Semantic color palette derived from the active theme.
/// Maps abstract UI roles to concrete `Color` values.
pub struct UiColors {
    pub command: Color,
    pub flag: Color,
    pub arg: Color,
    pub value: Color,
    pub required: Color,
    pub help: Color,
    pub active_border: Color,
    pub inactive_border: Color,
    pub selected_bg: Color,
    pub hover_bg: Color,
    pub editing_bg: Color,
    pub preview_cmd: Color,
    pub choice: Color,
    pub default_val: Color,
    pub count: Color,
    pub bg: Color,
    pub bar_bg: Color,
}

impl UiColors {
    pub fn from_palette(p: &ThemePalette) -> Self {
        let bar_bg = match p.bg {
            Color::Rgb(r, g, b) => Color::Rgb(
                r.saturating_add(10),
                g.saturating_add(10),
                b.saturating_add(15),
            ),
            _ => Color::Rgb(30, 30, 40),
        };

        let selected_bg = match p.selection {
            Color::Rgb(r, g, b) => Color::Rgb(r, g, b),
            _ => Color::Rgb(40, 40, 60),
        };

        // Hover bg is a subtler version of selected_bg, blended toward the background
        let hover_bg = match (p.bg, p.selection) {
            (Color::Rgb(br, bg_g, bb), Color::Rgb(sr, sg, sb)) => {
                Color::Rgb(
                    ((br as u16 + sr as u16) / 2) as u8,
                    ((bg_g as u16 + sg as u16) / 2) as u8,
                    ((bb as u16 + sb as u16) / 2) as u8,
                )
            }
            _ => Color::Rgb(30, 30, 45),
        };

        let editing_bg = match p.selection {
            Color::Rgb(r, g, b) => Color::Rgb(
                r.saturating_add(15),
                g.saturating_sub(5),
                b.saturating_sub(10),
            ),
            _ => Color::Rgb(50, 30, 30),
        };

        Self {
            command: p.info,
            flag: p.warning,
            arg: p.success,
            value: p.accent,
            required: p.error,
            help: p.muted,
            active_border: p.accent,
            inactive_border: p.muted,
            selected_bg,
            hover_bg,
            editing_bg,
            preview_cmd: p.fg,
            choice: p.info,
            default_val: p.muted,
            count: p.secondary,
            bg: p.bg,
            bar_bg,
        }
    }
}

/// State for computing panel-level styling decisions.
/// Built once per panel per render, then passed to item-level helpers.
pub struct PanelState {
    pub is_focused: bool,
    pub is_filtering: bool,
    pub has_filter: bool,
    pub border_color: Color,
    pub filter_text: String,
    pub match_scores: HashMap<String, MatchScores>,
}

impl PanelState {
    /// Build panel state from the app for a given focus panel.
    pub fn from_app(app: &App, panel: Focus, colors: &UiColors) -> Self {
        let is_focused = app.focus() == panel;
        let is_filtering = app.filtering && app.focus() == panel;
        let has_filter = app.filter_active() && app.focus() == panel;
        let border_color = if is_focused || is_filtering {
            colors.active_border
        } else {
            colors.inactive_border
        };
        let filter_text = if app.focus() == panel {
            app.filter().to_string()
        } else {
            String::new()
        };

        PanelState {
            is_focused,
            is_filtering,
            has_filter,
            border_color,
            filter_text,
            match_scores: HashMap::new(),
        }
    }

    /// Set match scores (call after construction with panel-specific scores).
    pub fn with_scores(mut self, scores: HashMap<String, MatchScores>) -> Self {
        self.match_scores = scores;
        self
    }

    /// Whether any filter is visually active (typing or applied).
    pub fn filter_visible(&self) -> bool {
        self.is_filtering || self.has_filter
    }
}

/// Build the panel title string with optional filter indicator.
pub fn panel_title(name: &str, ps: &PanelState) -> String {
    if ps.filter_visible() {
        format!(" {} 🔍 {} ", name, ps.filter_text)
    } else {
        format!(" {} ", name)
    }
}

/// Build a styled `Block` for a panel with consistent border and title styling.
/// The `with_padding` flag controls whether horizontal padding is added
/// (Flags and Args panels use padding; Commands panel does not).
pub fn panel_block(title: String, ps: &PanelState) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(ps.border_color))
        .title(title)
        .title_style(Style::default().fg(ps.border_color).bold())
}

/// Push the selection cursor indicator (`▶ ` or `  `) onto spans.
pub fn push_selection_cursor<'a>(spans: &mut Vec<Span<'a>>, is_selected: bool, colors: &UiColors) {
    if is_selected {
        spans.push(Span::styled(
            "",
            Style::default()
                .fg(colors.active_border)
                .add_modifier(Modifier::BOLD),
        ));
    } else {
        spans.push(Span::styled("  ", Style::default()));
    }
}

/// Compute the highlight styles for an item based on selection and match state.
/// Returns `(normal_style, highlight_style)` for use with `build_highlighted_text`.
fn highlight_styles(
    base_color: Color,
    bg_color: Color,
    is_selected: bool,
) -> (Style, Style) {
    if is_selected {
        (
            Style::default()
                .fg(base_color)
                .add_modifier(Modifier::BOLD),
            Style::default()
                .fg(bg_color)
                .bg(base_color)
                .add_modifier(Modifier::BOLD),
        )
    } else {
        (
            Style::default().fg(base_color),
            Style::default()
                .fg(base_color)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
        )
    }
}

/// Common context for rendering an item within a filtered panel.
/// Groups the match-state fields that are passed to multiple helpers.
pub struct ItemContext {
    pub is_selected: bool,
    pub is_match: bool,
    pub name_matches: bool,
    pub help_matches: bool,
}

impl ItemContext {
    /// Build from match state lookup.
    pub fn new(key: &str, is_selected: bool, ps: &PanelState) -> Self {
        let (is_match, name_matches, help_matches) = item_match_state(key, ps);
        Self {
            is_selected,
            is_match,
            name_matches,
            help_matches,
        }
    }
}

/// Push highlighted (or plain) name text onto spans, applying the correct styling
/// based on selection state, filter match state, and whether this field matched.
///
/// The 4 styling states:
/// 1. Selected + name matches filter → inverted highlight on matched chars
/// 2. Not selected + not matching at all → dimmed
/// 3. Not selected + name matches → bold+underlined on matched chars
/// 4. No filter or matched via other field only → normal (bold if selected)
pub fn push_highlighted_name(
    spans: &mut Vec<Span<'static>>,
    text: &str,
    base_color: Color,
    ctx: &ItemContext,
    ps: &PanelState,
    colors: &UiColors,
) {
    let has_scores = !ps.match_scores.is_empty();

    if ctx.is_selected {
        if has_scores && ctx.name_matches {
            let (normal, highlight) = highlight_styles(base_color, colors.bg, true);
            let highlighted = build_highlighted_text(text, &ps.filter_text, normal, highlight);
            spans.extend(highlighted);
        } else {
            spans.push(Span::styled(
                text.to_string(),
                Style::default()
                    .fg(base_color)
                    .add_modifier(Modifier::BOLD),
            ));
        }
    } else if !ctx.is_match && has_scores {
        // Non-matching item during filtering → dimmed
        spans.push(Span::styled(
            text.to_string(),
            Style::default().fg(colors.help).add_modifier(Modifier::DIM),
        ));
    } else if has_scores && ctx.name_matches {
        let (normal, highlight) = highlight_styles(base_color, colors.bg, false);
        let highlighted = build_highlighted_text(text, &ps.filter_text, normal, highlight);
        spans.extend(highlighted);
    } else {
        // Normal display (no filter, or matched via help only)
        spans.push(Span::styled(
            text.to_string(),
            Style::default().fg(base_color),
        ));
    }
}

/// Push right-aligned help text onto spans with optional filter highlighting.
/// Handles padding calculation, dim for non-matches, and character highlighting.
/// Build a styled `Line` for help text, suitable for right-aligned overlay rendering.
///
/// Returns styled spans with filter highlighting and dim support.
pub fn build_help_line(
    help: &str,
    ctx: &ItemContext,
    ps: &PanelState,
    colors: &UiColors,
) -> Line<'static> {
    let has_scores = !ps.match_scores.is_empty();

    let spans = if !ctx.is_match && has_scores {
        // Non-matching → dim help text
        vec![Span::styled(
            help.to_string(),
            Style::default().fg(colors.help).add_modifier(Modifier::DIM),
        )]
    } else if has_scores && ctx.help_matches {
        // Help text matches the filter → highlight matched characters
        let (normal, highlight) = highlight_styles(colors.help, colors.bg, ctx.is_selected);
        build_highlighted_text(help, &ps.filter_text, normal, highlight)
    } else {
        vec![Span::styled(
            help.to_string(),
            Style::default().fg(colors.help),
        )]
    };

    Line::from(spans)
}

/// Render right-aligned help text overlays on top of a rendered List.
///
/// After the List widget has been rendered, this function writes help text
/// directly to the frame buffer at the correct row positions, right-aligned
/// within the panel's inner area. This avoids manual space-padding and
/// prevents truncation issues.
///
/// `help_entries` maps item index → styled help Line.
/// `scroll_offset` is the List's current scroll position.
/// `inner` is the inner rect of the panel (after borders and padding).
pub fn render_help_overlays(
    buf: &mut Buffer,
    help_entries: &[(usize, Line<'static>)],
    scroll_offset: usize,
    inner: Rect,
) {
    let visible_rows = inner.height as usize;
    if inner.width < 2 {
        return;
    }

    for &(item_idx, ref help_line) in help_entries {
        // Skip items above the scroll viewport
        if item_idx < scroll_offset {
            continue;
        }
        let row_in_view = item_idx - scroll_offset;
        if row_in_view >= visible_rows {
            continue;
        }

        let y = inner.y + row_in_view as u16;
        let help_width = help_line.width() as u16;
        if help_width == 0 || help_width >= inner.width {
            continue;
        }

        // Position the help text right-aligned with a 1-char gap before it.
        // Only render if it doesn't overlap with existing row content.
        let total_width = help_width + 1; // 1 char gap before help text
        if total_width >= inner.width {
            continue;
        }
        let help_x = inner.x + inner.width - total_width;

        // Find rightmost non-empty cell in this row to avoid overwriting content
        let mut content_end = inner.x;
        for x in (inner.x..inner.x + inner.width).rev() {
            let cell = &buf[(x, y)];
            if cell.symbol() != " " {
                content_end = x + 1;
                break;
            }
        }
        // Skip if help text would overlap existing content
        if help_x < content_end {
            continue;
        }

        let help_rect = Rect::new(help_x, y, total_width, 1);
        let spaced_line = Line::from(
            std::iter::once(Span::raw(" "))
                .chain(help_line.spans.iter().cloned())
                .collect::<Vec<_>>(),
        );
        let para = Paragraph::new(spaced_line);
        para.render(help_rect, buf);
    }
}

/// Push inline edit cursor spans (before_cursor + ▎ + after_cursor).
pub fn push_edit_cursor(
    spans: &mut Vec<Span<'static>>,
    before_cursor: &str,
    after_cursor: &str,
    colors: &UiColors,
) {
    spans.push(Span::styled(
        before_cursor.to_string(),
        Style::default()
            .fg(colors.value)
            .add_modifier(Modifier::UNDERLINED),
    ));
    spans.push(Span::styled(
        "",
        Style::default()
            .fg(colors.value)
            .add_modifier(Modifier::SLOW_BLINK),
    ));
    spans.push(Span::styled(
        after_cursor.to_string(),
        Style::default()
            .fg(colors.value)
            .add_modifier(Modifier::UNDERLINED),
    ));
}

/// Return the background style for a selected item (editing vs normal selection).
pub fn selection_bg(is_editing: bool, colors: &UiColors) -> Style {
    let bg = if is_editing {
        colors.editing_bg
    } else {
        colors.selected_bg
    };
    Style::default().bg(bg)
}

/// Look up per-field match scores for a given item key.
/// Returns `(is_match, name_matches, help_matches)`.
pub fn item_match_state(key: &str, ps: &PanelState) -> (bool, bool, bool) {
    let scores = ps.match_scores.get(key);
    let is_match = scores.map(|s| s.overall()).unwrap_or(1) > 0 || ps.match_scores.is_empty();
    let name_matches = scores.map(|s| s.name_score).unwrap_or(0) > 0;
    let help_matches = scores.map(|s| s.help_score).unwrap_or(0) > 0;
    (is_match, name_matches, help_matches)
}

/// Build spans with highlighted characters based on fuzzy match indices.
pub fn build_highlighted_text(
    text: &str,
    pattern: &str,
    normal_style: Style,
    highlight_style: Style,
) -> Vec<Span<'static>> {
    let mut matcher = Matcher::new(Config::DEFAULT);
    let (_score, indices) = fuzzy_match_indices(text, pattern, &mut matcher);

    if indices.is_empty() {
        return vec![Span::styled(text.to_string(), normal_style)];
    }

    let mut spans = Vec::new();
    let chars: Vec<char> = text.chars().collect();
    let mut last_idx = 0;

    for &match_idx in &indices {
        let idx = match_idx as usize;
        if idx >= chars.len() {
            continue;
        }

        if last_idx < idx {
            let before: String = chars[last_idx..idx].iter().collect();
            if !before.is_empty() {
                spans.push(Span::styled(before, normal_style));
            }
        }

        spans.push(Span::styled(chars[idx].to_string(), highlight_style));
        last_idx = idx + 1;
    }

    if last_idx < chars.len() {
        let after: String = chars[last_idx..].iter().collect();
        if !after.is_empty() {
            spans.push(Span::styled(after, normal_style));
        }
    }

    spans
}

// ── Custom Widgets ──────────────────────────────────────────────────

/// A widget that renders the assembled command preview with colorized tokens.
///
/// Displays the command string in a bordered block, with syntax-aware coloring
/// for the binary name, subcommands, flags, and positional arguments.
pub struct CommandPreview<'a> {
    /// The full built command string.
    pub command: &'a str,
    /// Binary name from the spec.
    pub bin: &'a str,
    /// Subcommand names in the current command path.
    pub subcommands: &'a [String],
    /// Whether the preview panel currently has focus.
    pub is_focused: bool,
    pub colors: &'a UiColors,
}

impl<'a> CommandPreview<'a> {
    pub fn new(
        command: &'a str,
        bin: &'a str,
        subcommands: &'a [String],
        is_focused: bool,
        colors: &'a UiColors,
    ) -> Self {
        Self {
            command,
            bin,
            subcommands,
            is_focused,
            colors,
        }
    }

    /// Colorize the command string by categorizing each token.
    fn colorize(&self, bold: Modifier) -> Vec<Span<'static>> {
        let subcommand_names: HashSet<&str> =
            self.subcommands.iter().map(|s| s.as_str()).collect();

        let tokens: Vec<&str> = self.command.split_whitespace().collect();
        let mut spans = Vec::new();
        let mut i = 0;
        let mut expect_flag_value = false;

        while i < tokens.len() {
            if i > 0 {
                spans.push(Span::raw(" "));
            }

            let token = tokens[i];

            if i == 0 && token == self.bin {
                spans.push(Span::styled(
                    token.to_string(),
                    Style::default()
                        .fg(self.colors.preview_cmd)
                        .add_modifier(bold | Modifier::BOLD),
                ));
            } else if expect_flag_value {
                spans.push(Span::styled(
                    token.to_string(),
                    Style::default().fg(self.colors.value).add_modifier(bold),
                ));
                expect_flag_value = false;
            } else if token.starts_with('-') {
                spans.push(Span::styled(
                    token.to_string(),
                    Style::default().fg(self.colors.flag).add_modifier(bold),
                ));
                if let Some(&next) = tokens.get(i + 1) {
                    if !next.starts_with('-') && !subcommand_names.contains(next) {
                        expect_flag_value = true;
                    }
                }
            } else if subcommand_names.contains(token) {
                spans.push(Span::styled(
                    token.to_string(),
                    Style::default().fg(self.colors.command).add_modifier(bold),
                ));
            } else {
                spans.push(Span::styled(
                    token.to_string(),
                    Style::default().fg(self.colors.arg).add_modifier(bold),
                ));
            }

            i += 1;
        }

        spans
    }
}

impl Widget for CommandPreview<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let border_color = if self.is_focused {
            self.colors.active_border
        } else {
            self.colors.inactive_border
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::default().fg(border_color))
            .title(" Command ")
            .title_style(Style::default().fg(border_color).bold())
            .padding(Padding::horizontal(1));

        let prefix = if self.is_focused { "" } else { "$ " };
        let bold = if self.is_focused {
            Modifier::BOLD
        } else {
            Modifier::empty()
        };

        let mut spans = vec![Span::styled(prefix, Style::default().fg(self.colors.command))];
        spans.extend(self.colorize(bold));

        let paragraph = Paragraph::new(Line::from(spans))
            .block(block)
            .wrap(Wrap { trim: false });

        paragraph.render(area, buf);
    }
}

/// A single keyboard shortcut entry: a key (e.g. `"↑↓"`) and its description
/// (e.g. `"navigate"`).
pub struct Keybind<'a> {
    pub key: &'a str,
    pub desc: &'a str,
}

/// A widget that renders the context-sensitive help/status bar.
///
/// Shows keyboard shortcuts for the current mode on the left and
/// the active theme indicator on the right.
pub struct HelpBar<'a> {
    /// Structured key/description pairs to display.
    pub keybinds: &'a [Keybind<'a>],
    /// Theme display name for the right-aligned indicator.
    pub theme_display: &'a str,
    pub colors: &'a UiColors,
}

impl<'a> HelpBar<'a> {
    pub fn new(keybinds: &'a [Keybind<'a>], theme_display: &'a str, colors: &'a UiColors) -> Self {
        Self {
            keybinds,
            theme_display,
            colors,
        }
    }

    /// Returns the Rect where the theme indicator is rendered,
    /// for use in mouse click hit-testing.
    pub fn theme_indicator_rect(&self, area: Rect) -> Rect {
        let theme_indicator = format!("T: [{}] ", self.theme_display);
        let theme_indicator_len = theme_indicator.len() as u16;
        let indicator_x = area.x + area.width.saturating_sub(theme_indicator_len);
        Rect::new(indicator_x, area.y, theme_indicator_len, 1)
    }

    /// Build styled spans for the keybinds.
    ///
    /// Each entry's key is rendered in the high-contrast `active_border` color
    /// and its description in the subdued `help` color.  Entries are separated
    /// by two spaces.  Returns the spans and their total display width.
    fn styled_keybind_spans(&self) -> (Vec<Span<'a>>, u16) {
        let mut spans: Vec<Span<'a>> = vec![Span::raw(" ")];
        let mut total_len: u16 = 1; // leading space

        for (i, kb) in self.keybinds.iter().enumerate() {
            if i > 0 {
                spans.push(Span::raw("  "));
                total_len += 2;
            }
            spans.push(Span::styled(kb.key, Style::default().fg(self.colors.active_border)));
            spans.push(Span::raw(" "));
            spans.push(Span::styled(kb.desc, Style::default().fg(self.colors.help)));
            total_len += (kb.key.chars().count() + 1 + kb.desc.chars().count()) as u16;
        }

        (spans, total_len)
    }
}

impl Widget for HelpBar<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let theme_indicator = format!("T: [{}] ", self.theme_display);
        let theme_indicator_len = theme_indicator.len() as u16;

        let (mut spans, keybinds_len) = self.styled_keybind_spans();
        let padding_len = area.width.saturating_sub(keybinds_len + theme_indicator_len);
        let padding = " ".repeat(padding_len as usize);

        spans.push(Span::styled(padding, Style::default()));
        spans.push(Span::styled(
            theme_indicator,
            Style::default().fg(self.colors.active_border).italic(),
        ));

        let paragraph = Paragraph::new(Line::from(spans))
            .style(Style::default().bg(self.colors.bar_bg));

        paragraph.render(area, buf);
    }
}

/// A widget that renders a bordered selectable list overlay.
///
/// Used for both the choice select dropdown and the theme picker.
/// Clears the area behind it, draws a bordered block with a title,
/// and renders selectable items with a `▶` cursor indicator.
/// Optionally shows descriptions alongside items.
pub struct SelectList<'a> {
    /// Title shown in the block border (empty string = no title).
    pub title: String,
    /// Item labels to display.
    pub items: &'a [String],
    /// Optional descriptions for each item (parallel to `items`).
    pub descriptions: &'a [Option<String>],
    /// Currently selected index (None = no selection).
    pub selected: Option<usize>,
    /// Currently hovered index (None = no hover).
    pub hovered: Option<usize>,
    /// Whether to show the ▶ selection cursor prefix.
    pub show_cursor: bool,
    /// Which borders to show (defaults to ALL).
    pub borders: Borders,
    /// Style for unselected items.
    pub item_color: Color,
    /// Style for the selected item (text color).
    pub selected_color: Color,
    pub colors: &'a UiColors,
}

impl<'a> SelectList<'a> {
    pub fn new(
        title: String,
        items: &'a [String],
        selected: Option<usize>,
        item_color: Color,
        selected_color: Color,
        colors: &'a UiColors,
    ) -> Self {
        Self {
            title,
            items,
            descriptions: &[],
            selected,
            hovered: None,
            show_cursor: false,
            borders: Borders::ALL,
            item_color,
            selected_color,
            colors,
        }
    }

    /// Set descriptions to display alongside items.
    pub fn with_descriptions(mut self, descriptions: &'a [Option<String>]) -> Self {
        self.descriptions = descriptions;
        self
    }

    /// Show ▶ prefix cursor for the selected item.
    pub fn with_cursor(mut self) -> Self {
        self.show_cursor = true;
        self
    }

    /// Set which borders to show.
    pub fn with_borders(mut self, borders: Borders) -> Self {
        self.borders = borders;
        self
    }

    /// Set the hovered index.
    pub fn with_hovered(mut self, hovered: Option<usize>) -> Self {
        self.hovered = hovered;
        self
    }
}

impl Widget for SelectList<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let mut state = SelectListScrollState::default();
        StatefulWidget::render(self, area, buf, &mut state);
    }
}

/// Scroll state for `SelectList`, tracking the computed scroll offset and visible items.
/// Pass this to `StatefulWidget::render` to get the scroll offset back for mouse handling.
#[derive(Debug, Clone, Default)]
pub struct SelectListScrollState {
    /// The scroll offset computed during rendering (items scrolled past the top).
    pub scroll_offset: usize,
    /// Number of visible item rows in the viewport.
    pub visible_items: usize,
}

impl StatefulWidget for SelectList<'_> {
    type State = SelectListScrollState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        use ratatui::widgets::{Scrollbar, ScrollbarOrientation, ScrollbarState};

        // Clear area behind the overlay
        ratatui::widgets::Clear.render(area, buf);

        let mut block = Block::default()
            .borders(self.borders)
            .border_style(Style::default().fg(self.colors.active_border));
        if !self.title.is_empty() {
            block = block
                .title(self.title)
                .title_style(
                    Style::default()
                        .fg(self.colors.active_border)
                        .add_modifier(Modifier::BOLD),
                );
        }

        let items: Vec<ratatui::widgets::ListItem> = if self.items.is_empty() {
            vec![ratatui::widgets::ListItem::new(Line::from(Span::styled(
                "(no matches)",
                Style::default().fg(self.colors.help).italic(),
            )))]
        } else {
            self.items
                .iter()
                .enumerate()
                .map(|(i, label)| {
                    let is_selected = self.selected == Some(i);
                    let style = if is_selected {
                        Style::default()
                            .fg(self.selected_color)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(self.item_color)
                    };

                    let mut spans = Vec::new();
                    if self.show_cursor {
                        let prefix = if is_selected { "" } else { "  " };
                        spans.push(Span::styled(
                            prefix,
                            if is_selected {
                                Style::default()
                                    .fg(self.colors.active_border)
                                    .add_modifier(Modifier::BOLD)
                            } else {
                                Style::default()
                            },
                        ));
                    }
                    spans.push(Span::styled(label.clone(), style));

                    // Add description if present
                    if let Some(Some(desc)) = self.descriptions.get(i) {
                        spans.push(Span::styled(
                            format!("  {}", desc),
                            Style::default().fg(self.colors.help),
                        ));
                    }

                    let mut item = ratatui::widgets::ListItem::new(Line::from(spans));
                    if is_selected {
                        item = item.style(Style::default().bg(self.colors.selected_bg));
                    } else if self.hovered == Some(i) {
                        item = item.style(Style::default().bg(self.colors.hover_bg));
                    }
                    item
                })
                .collect()
        };

        // Calculate visible items based on which borders are present
        let border_height = if self.borders.contains(Borders::TOP) { 1 } else { 0 }
            + if self.borders.contains(Borders::BOTTOM) { 1 } else { 0 };
        let visible_items = area.height.saturating_sub(border_height) as usize;
        state.visible_items = visible_items;

        let mut list_state = ratatui::widgets::ListState::default().with_selected(
            if self.items.is_empty() {
                None
            } else {
                self.selected
            },
        );

        let scroll_offset = if let Some(sel) = self.selected {
            if visible_items > 0 && sel >= visible_items {
                sel.saturating_sub(visible_items - 1)
            } else {
                0
            }
        } else {
            0
        };
        list_state = list_state.with_offset(scroll_offset);
        state.scroll_offset = scroll_offset;

        let list = ratatui::widgets::List::new(items).block(block);
        ratatui::widgets::StatefulWidget::render(list, area, buf, &mut list_state);

        // Render scrollbar if content overflows
        let total_items = self.items.len();
        if total_items > visible_items && visible_items > 0 {
            let inner = area.inner(ratatui::layout::Margin {
                horizontal: 0,
                vertical: if self.borders.contains(Borders::TOP) { 1 } else { 0 },
            });
            // Adjust inner height if bottom border is present
            let scrollbar_area = if self.borders.contains(Borders::BOTTOM) {
                Rect::new(inner.x, inner.y, inner.width, inner.height.saturating_sub(
                    if self.borders.contains(Borders::BOTTOM) { 1 } else { 0 }
                ))
            } else {
                inner
            };
            let mut scrollbar_state = ScrollbarState::new(total_items.saturating_sub(visible_items))
                .position(scroll_offset);
            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .track_symbol(Some(""))
                .thumb_symbol("")
                .track_style(Style::default().fg(self.colors.inactive_border))
                .thumb_style(Style::default().fg(self.colors.active_border));
            StatefulWidget::render(scrollbar, scrollbar_area, buf, &mut scrollbar_state);
        }
    }
}