mnml-rs 0.2.14

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

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::app::App;
use crate::ui::theme;

/// Default height (rows) for the hover-help panel — the seed value
/// for `[ui] hover_help_height` config field, which is user-tunable
/// via drag-to-resize on the top border (persists on drag-end).
/// The runtime value lives on `App::hover_help_height`.
///
/// 1 separator + 1 header + wrapped body + 1 blank trailer so the
/// last text line isn't flush against the statusbar directly below
/// (breathing room, 2026-08-10). R8 vscode-mouse feedback: without
/// the separator the box shares tree_rail bg and reads as accidental
/// tree overflow. The dim `─` rule at row 0 (now decorated with a
/// `═` grip center) draws the eye + serves as the drag handle.
pub const DEFAULT_INFO_BOX_HEIGHT: u16 = 8;

/// Paint the info box over `area`. Caller reserves the rows only when
/// `app.config.ui.hover_help` is on AND the left panel is tall enough
/// to spare `app.hover_help_height` rows (config-seeded from
/// `DEFAULT_INFO_BOX_HEIGHT`, user-tunable via drag-resize).
///
/// Layout (Info View v0.3 Phase 1.6, matches `docs/design/info-view-v0.3.md`):
///
/// ```text
///   ─────────────────────────  ← row 0: divider from tree rail
///    Slack Boards              ← row 1: TITLE bar (distinct bg, bold)
///                              ← row 2: spacer
///    Slack Canvases share the  ← row 3+: body (word-wrapped, regular)
///    same OAuth token…
///    [Ctrl+K b] Toggle bufferline  ← shortcuts (bracket accent + label)
///                              ← trailing blank (cushion for statusbar)
/// ```
/// Delay between the mouse settling on a new hover target and the
/// info-box swapping to its copy. Suppresses rapid text flashes when
/// the user drags across tree rows or chips (2026-08-12 report).
/// Bumped from 120 → 350 (#1093, 2026-08-20) so the panel doesn't
/// evaporate while the user drags the mouse from the trigger toward
/// the panel to click a button inside it. 350ms is long enough to
/// cross the corridor between a statusline chip and the panel; still
/// short enough that a resolved fresh target commits fast when the
/// mouse actually settles. First swap ever renders with no delay so
/// opening the panel isn't laggy.
const HOVER_HELP_DEBOUNCE_MS: u128 = 350;

pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) {
    if area.height == 0 || area.width == 0 {
        return;
    }
    app.rects.hover_help_strip = Some(area);
    // Cleared up front so a tiny panel (early-returns below before the
    // body renders) doesn't leave a stale, unreachable click target
    // from the previous frame's taller layout.
    app.rects.hover_help_try_it.clear();
    app.rects.hover_help_docs = None;
    let t = theme::cur();
    // Body bg is slightly darker than the tree rail so the box reads
    // as its own pane. Title bar uses `bg2` (the menu / popup fill,
    // usually noticeably lighter than the tree rail's bg_dark) so the
    // topic band reads as a distinct "help header" — user 2026-08-11
    // feedback: prior `bg_dark` was visually indistinguishable from
    // the tree above it, so the title looked like accidental text
    // rather than a titled help pane.
    let body_bg = t.bg_darker;
    let title_bg = t.bg2;
    frame.render_widget(Paragraph::new("").style(Style::default().bg(body_bg)), area);

    let copy = debounced_help_copy(app);

    // Row 0 — flat divider. #1089 (2026-08-19) — user asked to
    // remove the `═════` drag grip (visual noise, competed with
    // the section header directly above for attention). The whole
    // row is still the hit-target for the drag-resize handler in
    // `tui/mouse/mod.rs` — the affordance is now the vertical
    // resize cursor on hover instead of a permanent glyph.
    let w = area.width as usize;
    let sep_style = Style::default()
        .fg(t.comment)
        .bg(body_bg)
        .add_modifier(Modifier::DIM);
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled("".repeat(w), sep_style))),
        Rect {
            x: area.x,
            y: area.y,
            width: area.width,
            height: 1,
        },
    );
    if area.height <= 1 {
        return;
    }

    // Row 1 — TITLE bar (topic name, distinct bg, bold) + kebab
    // affordance at the right edge. `⋮` (U+22EE, vertical 3-dot)
    // matches the widget kebab glyph in `src/ui/dock.rs`.
    let kebab_glyph = "";
    // Reserve 2 cells at the right for the glyph + 1 padding cell
    // (so it doesn't butt against the frame). Title text truncates
    // to fit; area.width >= 3 is required for the kebab to appear.
    let kebab_cells = 2u16;
    let title_avail = area.width.saturating_sub(kebab_cells);
    // Title starts flush-left with 1-cell inset. The `?` prefix
    // (2026-08-11) got dropped 2026-08-12 — user feedback: the glyph
    // read as accidental character in the corner, not a help sigil.
    // The distinct title-bar bg (`bg2`) already differentiates the
    // help header from the body without needing a leading icon.
    let prefix_cells = 1u16;
    let title_body_avail = title_avail.saturating_sub(prefix_cells);
    let title_text: String = copy
        .title
        .chars()
        .take(title_body_avail.saturating_sub(1) as usize)
        .collect();
    let title_body = pad_line(&title_text, title_body_avail as usize);
    let mut title_spans = vec![
        Span::styled(" ", Style::default().bg(title_bg)),
        Span::styled(
            title_body,
            Style::default()
                .fg(t.fg)
                .bg(title_bg)
                .add_modifier(Modifier::BOLD),
        ),
    ];
    if area.width >= 3 {
        title_spans.push(Span::styled(
            kebab_glyph,
            Style::default().fg(t.comment).bg(title_bg),
        ));
        title_spans.push(Span::styled(" ", Style::default().bg(title_bg)));
        app.rects.hover_help_kebab = Some(Rect {
            x: area.x + area.width - kebab_cells,
            y: area.y + 1,
            width: 1,
            height: 1,
        });
    } else {
        app.rects.hover_help_kebab = None;
    }
    frame.render_widget(
        Paragraph::new(Line::from(title_spans)),
        Rect {
            x: area.x,
            y: area.y + 1,
            width: area.width,
            height: 1,
        },
    );
    if area.height <= 2 {
        return;
    }

    // Rows 2..N — spacer + body + optional aside + optional shortcuts
    // + optional `Try it →` action buttons. 1-cell gutter left + right;
    // trailing row stays blank as cushion before the statusbar directly
    // below.
    //
    // `line_actions` runs parallel to `lines` — `Some(command_id)` marks
    // a row as a clickable `Try it →` action button, `None` is plain
    // prose/spacer. Kept parallel (rather than embedding the id in the
    // `Line` itself) so the scroll/clip math below can slice both
    // together and land on the exact screen rect a click needs to hit.
    let content_w = area.width.saturating_sub(2) as usize;
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut line_actions: Vec<Option<String>> = Vec::new();
    // Spacer row between title bar and body.
    lines.push(spacer(body_bg));
    line_actions.push(None);
    // Body — regular weight, comment-color (softer than fg-bold so the
    // TITLE bar owns the visual weight).
    for line in wrap_words(&copy.body, content_w) {
        lines.push(Line::from(vec![
            Span::styled(" ", Style::default().bg(body_bg)),
            Span::styled(line, Style::default().fg(t.fg).bg(body_bg)),
        ]));
        line_actions.push(None);
    }
    // Aside — italic caveat.
    if let Some(aside) = &copy.aside {
        for line in wrap_words(aside, content_w) {
            lines.push(Line::from(vec![
                Span::styled(" ", Style::default().bg(body_bg)),
                Span::styled(
                    line,
                    Style::default()
                        .fg(t.comment)
                        .bg(body_bg)
                        .add_modifier(Modifier::ITALIC),
                ),
            ]));
            line_actions.push(None);
        }
    }
    // Shortcut hints — `[Chord] Label` per row. Only if there's room
    // after the body; otherwise skip (body reads first).
    let max_body_rows = area.height.saturating_sub(3) as usize;
    let rows_left = max_body_rows.saturating_sub(lines.len());
    if rows_left > 0 && !copy.shortcuts.is_empty() {
        // Blank spacer between prose and shortcuts.
        lines.push(spacer(body_bg));
        line_actions.push(None);
        for hint in copy.shortcuts.iter().take(rows_left.saturating_sub(1)) {
            lines.push(Line::from(vec![
                Span::styled(" ", Style::default().bg(body_bg)),
                Span::styled(
                    format!("[{}]", hint.chord),
                    Style::default()
                        .fg(t.cyan)
                        .bg(body_bg)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    format!(" {}", hint.label),
                    Style::default().fg(t.fg).bg(body_bg),
                ),
            ]));
            line_actions.push(None);
        }
    }
    // `Try it →` action buttons — 0-3 clickable palette-command links,
    // Info View v0.3's `try_it` field. Framework carried this data
    // since Phase 1 but nothing rendered or dispatched it (102 curated
    // entries had dead `try_it` links until 2026-08-16). Rendered last
    // (after shortcuts) so the reference material reads before the
    // calls-to-action; each gets its own row so the click rect maps
    // 1:1 to a command id via `line_actions`.
    let rows_left = max_body_rows.saturating_sub(lines.len());
    if rows_left > 0 && !copy.try_it.is_empty() {
        lines.push(spacer(body_bg));
        line_actions.push(None);
        for link in copy.try_it.iter().take(rows_left.saturating_sub(1)) {
            lines.push(Line::from(vec![
                Span::styled(" ", Style::default().bg(body_bg)),
                Span::styled(
                    format!("{}", link.label),
                    Style::default()
                        .fg(t.green)
                        .bg(body_bg)
                        .add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                ),
            ]));
            line_actions.push(Some(link.command_id.clone()));
        }
    }
    // `→ Manual` docs link — opens the corresponding site manual page
    // in the OS browser. Rendered last, own row; tracked separately
    // from `line_actions` (which is command-id-keyed) since this is a
    // URL, not a palette command.
    let rows_left = max_body_rows.saturating_sub(lines.len());
    let docs_line_idx = if rows_left > 0 {
        copy.docs.as_ref().map(|_| {
            lines.push(Line::from(vec![
                Span::styled(" ", Style::default().bg(body_bg)),
                Span::styled(
                    "→ Manual",
                    Style::default()
                        .fg(t.cyan)
                        .bg(body_bg)
                        .add_modifier(Modifier::UNDERLINED),
                ),
            ]));
            line_actions.push(None);
            lines.len() - 1
        })
    } else {
        None
    };

    // Body starts at row 2 (after divider + title). Height reserves
    // 1 trailing row as cushion.
    let body_rect = Rect {
        x: area.x,
        y: area.y + 2,
        width: area.width,
        height: area.height.saturating_sub(3),
    };
    let cap = body_rect.height as usize;
    let total_lines = lines.len();
    let overflow = total_lines > cap;
    // Clamp scroll so we can always fill the visible window from the
    // scroll offset. `hover_help_scroll` is user-controlled via wheel
    // (see mouse handler); clamp here so a stale value on a shorter
    // committed body doesn't paint blank rows.
    let max_scroll = total_lines.saturating_sub(cap) as u16;
    let scroll = app.hover_help_scroll.min(max_scroll);
    // Persist the clamp so subsequent wheel events see the true value.
    app.hover_help_scroll = scroll;
    // Pair each visible line with its action (if any) so `Try it →`
    // rows land a click rect at the exact screen row they paint on —
    // scroll-aware, so scrolling the panel keeps the rect in sync with
    // whichever action row is currently visible.
    let scrollbar_reserved = if overflow { 1u16 } else { 0 };
    let mut try_it_rects: Vec<(Rect, String)> = Vec::new();
    let mut docs_rect: Option<(Rect, String)> = None;
    // `.enumerate()` runs before `.skip()` so `orig_idx` stays the
    // ORIGINAL (pre-scroll) line index — needed to spot the docs-link
    // row (`docs_line_idx`) — while `screen_row` (from the fresh
    // `.enumerate()` after skip/take) is the on-screen row for the rect.
    let visible: Vec<Line<'static>> = lines
        .into_iter()
        .zip(line_actions)
        .enumerate()
        .skip(scroll as usize)
        .take(cap)
        .enumerate()
        .map(|(screen_row, (orig_idx, (line, action)))| {
            let row_rect = Rect {
                x: body_rect.x,
                y: body_rect.y + screen_row as u16,
                width: body_rect.width.saturating_sub(scrollbar_reserved),
                height: 1,
            };
            if let Some(cmd) = action {
                try_it_rects.push((row_rect, cmd));
            }
            if docs_line_idx == Some(orig_idx)
                && let Some(url) = &copy.docs
            {
                docs_rect = Some((row_rect, url.clone()));
            }
            line
        })
        .collect();
    app.rects.hover_help_try_it = try_it_rects;
    app.rects.hover_help_docs = docs_rect;
    if overflow {
        // Reserve 1 col on the right for the scrollbar; render body in
        // the remaining width.
        let scrollbar_col = body_rect.x + body_rect.width.saturating_sub(1);
        let content_rect = Rect {
            width: body_rect.width.saturating_sub(1),
            ..body_rect
        };
        frame.render_widget(Paragraph::new(visible), content_rect);
        // Scrollbar: full track in comment color, thumb in cyan sized
        // proportional to visible/total ratio, positioned per scroll
        // offset. Min thumb = 1 row.
        let track_h = body_rect.height as usize;
        let thumb_h = ((cap * track_h) / total_lines).max(1);
        let thumb_y_off = if max_scroll == 0 {
            0
        } else {
            ((scroll as usize) * (track_h.saturating_sub(thumb_h))) / (max_scroll as usize)
        };
        for i in 0..track_h {
            let is_thumb = i >= thumb_y_off && i < thumb_y_off + thumb_h;
            let (glyph, color) = if is_thumb {
                ("", t.cyan)
            } else {
                ("", t.comment)
            };
            frame.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    glyph,
                    Style::default().fg(color).bg(body_bg),
                ))),
                Rect {
                    x: scrollbar_col,
                    y: body_rect.y + i as u16,
                    width: 1,
                    height: 1,
                },
            );
        }
    } else {
        frame.render_widget(Paragraph::new(visible), body_rect);
    }
}

fn spacer<'a>(bg: ratatui::style::Color) -> Line<'a> {
    Line::from(Span::styled(" ", Style::default().bg(bg)))
}

fn pad_line(s: &str, width: usize) -> String {
    let w = s.chars().count();
    if w >= width {
        s.to_string()
    } else {
        format!("{}{}", s, " ".repeat(width - w))
    }
}

/// Minimal word-wrap into lines of at most `width` chars. Preserves
/// word boundaries; oversized words get a hard break rather than
/// overflow. No hyphenation — this is UI help, not typesetting.
fn wrap_words(text: &str, width: usize) -> Vec<String> {
    if width == 0 || text.is_empty() {
        return vec![String::new()];
    }
    let mut out: Vec<String> = Vec::new();
    let mut line = String::new();
    for word in text.split_whitespace() {
        let word_len = word.chars().count();
        if word_len > width {
            // Push the current line, then hard-break the oversized word.
            if !line.is_empty() {
                out.push(std::mem::take(&mut line));
            }
            let mut chars = word.chars();
            loop {
                let chunk: String = chars.by_ref().take(width).collect();
                if chunk.is_empty() {
                    break;
                }
                if chunk.chars().count() == width {
                    out.push(chunk);
                } else {
                    line = chunk;
                    break;
                }
            }
            continue;
        }
        let needed = if line.is_empty() {
            word_len
        } else {
            line.chars().count() + 1 + word_len
        };
        if needed > width {
            out.push(std::mem::take(&mut line));
            line = word.to_string();
        } else {
            if !line.is_empty() {
                line.push(' ');
            }
            line.push_str(word);
        }
    }
    if !line.is_empty() {
        out.push(line);
    }
    if out.is_empty() {
        out.push(String::new());
    }
    out
}

/// The hover-help text pair: primary (bold) + optional secondary.
/// Delegates to the same describe logic as `ui::tooltip::describe`
/// but stripped down to just the text (no anchor rect needed here).
///
/// Fallback ladder when no chip is hovered:
///   1. Focus target — the tree row / right-panel pane / bottom-panel
///      pane the keyboard is on. Only when `app.focus != Pane`.
///      R6 nvchad SEV-3 2026-08-09: prior order swallowed tree focus
///      because the active-pane branch always matched — a vim user
///      on keyboard-only walking the tree never saw the row they were
///      hovering.
///   2. Active pane summary (file / URL / kind) — for `Focus::Pane`
///      or when the focus target had nothing useful to show.
///   3. Focus hint pointing at the palette (last resort).
/// Debounce wrapper around [`pick_help_copy`]. The panel only swaps
/// to a new copy after that copy has been the "current" pick for
/// [`HOVER_HELP_DEBOUNCE_MS`] straight. Rapid mouse drags across
/// rows/chips keep resetting the pending timer, so the committed
/// text stays stable. First paint (no committed yet) renders
/// immediately so opening isn't perceived as laggy.
///
/// Debounce key = `InfoViewCopy.title`. Two distinct targets that
/// produce identical titles will look like "same" for debounce
/// purposes — acceptable trade-off vs. plumbing a proper target key
/// or deriving PartialEq on the whole struct.
fn debounced_help_copy(app: &mut App) -> crate::ui::info_view::InfoViewCopy {
    let fresh = pick_help_copy(app);
    // #1093 (2026-08-20) — hard freeze while the cursor is over the
    // panel itself. #947 already prevents `hover_chip` from mutating
    // in this state, but a pending commit that started BEFORE the
    // cursor entered would still fire and blank the copy. Bail early:
    // keep whatever's committed, drop any in-flight pending. This is
    // what lets a mouse user reach the panel's `[Try it]` / docs
    // rects without them evaporating.
    if let Some(panel) = app.rects.hover_help_strip
        && let Some((mx, my)) = app.mouse_pos
        && crate::app::dispatch::contains(panel, mx, my)
        && let Some(committed) = app.hover_help_committed.clone()
    {
        app.hover_help_pending = None;
        return committed;
    }
    // Never any committed → first paint, render immediately.
    let Some(committed) = app.hover_help_committed.clone() else {
        app.hover_help_committed = Some(fresh.clone());
        app.hover_help_pending = None;
        return fresh;
    };
    // Fresh already matches committed → nothing to swap. Drop pending.
    if committed.title == fresh.title {
        app.hover_help_pending = None;
        return committed;
    }
    // Fresh differs. Check the pending slot.
    let now = std::time::Instant::now();
    match &app.hover_help_pending {
        Some((pending_copy, first_seen))
            if pending_copy.title == fresh.title
                && first_seen.elapsed().as_millis() >= HOVER_HELP_DEBOUNCE_MS =>
        {
            // Pending has settled long enough. Commit + reset scroll —
            // a new target means back to the top of the fresh content.
            app.hover_help_committed = Some(fresh.clone());
            app.hover_help_pending = None;
            app.hover_help_scroll = 0;
            fresh
        }
        Some((pending_copy, _)) if pending_copy.title == fresh.title => {
            // Same pending target still settling. Keep old committed.
            committed
        }
        _ => {
            // New pending candidate (or first pending). Reset timer.
            app.hover_help_pending = Some((fresh.clone(), now));
            committed
        }
    }
}

fn pick_help_copy(app: &App) -> crate::ui::info_view::InfoViewCopy {
    use crate::ui::info_view::InfoViewCopy;
    // Info View v0.3 Phase 1.6 — InfoViewCopy is now the primary shape.
    // Curated `info_view_copy::lookup` entries render richly (title +
    // body + shortcuts). Legacy tooltip callers get their
    // (primary, secondary) pair mapped onto title + body so nothing
    // regresses while the copy dictionary catches up.
    if let Some((chip, _)) = app.hover_chip {
        let target = crate::ui::info_view::InfoViewTarget::Chip(chip);
        if let Some(copy) = crate::ui::info_view_copy::lookup(app, &target) {
            return copy;
        }
        if let Some((primary, secondary)) = crate::ui::tooltip::describe_text(chip, app) {
            return InfoViewCopy {
                title: primary,
                body: secondary.unwrap_or_default(),
                ..Default::default()
            };
        }
    }
    if let Some(copy) = describe_focus_target_copy(app) {
        return copy;
    }
    if let Some(cur) = app.active
        && let Some(pane) = app.panes.get(cur)
        && let Some((primary, secondary)) = describe_active_pane(pane)
    {
        return InfoViewCopy {
            title: primary,
            body: secondary.unwrap_or_default(),
            ..Default::default()
        };
    }
    // Empty state — one-liner per focus surface. Title names the
    // surface; body gives the essential action.
    let (title, body) = match app.focus {
        crate::focus::Focus::Tree => (
            "Sidebar",
            "Arrows or j/k walk rows. Enter opens the selection. Ctrl+Shift+P opens the palette.",
        ),
        crate::focus::Focus::Pane => (
            "Editor",
            "Hover a chip, tab, or tree row for help. Ctrl+Shift+P opens the palette.",
        ),
        crate::focus::Focus::RightPanel => (
            "Right panel",
            "Arrows walk rows. Enter jumps to the source. F6 cycles focus.",
        ),
        crate::focus::Focus::BottomPanel => (
            "Bottom panel",
            "Arrows walk rows. Ctrl+Shift+J hides. F6 cycles focus.",
        ),
    };
    InfoViewCopy {
        title: title.to_string(),
        body: body.to_string(),
        ..Default::default()
    }
}

/// InfoViewCopy shape of describe_focus_target. When the focus target
/// has a curated tree-row entry, prefer that; else synthesize from
/// the ad-hoc friendly-lang strings.
fn describe_focus_target_copy(app: &App) -> Option<crate::ui::info_view::InfoViewCopy> {
    use crate::ui::info_view::InfoViewCopy;
    let (primary, secondary) = describe_focus_target(app)?;
    Some(InfoViewCopy {
        title: primary,
        body: secondary.unwrap_or_default(),
        ..Default::default()
    })
}

/// Describe whatever is under keyboard focus when it's NOT a pane —
/// tree cursor row, right-panel pane, or bottom-panel pane. Returns
/// None when focus IS on a pane (caller falls through to
/// `describe_active_pane`) or when the focus target has no useful
/// description (empty tree / empty panel).
fn describe_focus_target(app: &App) -> Option<(String, Option<String>)> {
    match app.focus {
        crate::focus::Focus::Pane => None,
        crate::focus::Focus::Tree => {
            // R11 nvchad SEV-3 2026-08-14 — the tree-row branch used
            // to fire for every activity section, so the info panel
            // said `app.ts — TypeScript source` even while the HTTP /
            // Integrations / Agents section was drawing in the
            // sidebar. When a non-Explorer section is active, the
            // "tree cursor" isn't visible; return a section-level
            // hint instead so the panel reflects what the user is
            // actually looking at.
            if let Some(section_hint) = section_focus_hint(app.active_section) {
                return Some(section_hint);
            }
            // At rest on the auto-selected row 0, the panel used to
            // narrate `.cargo/` (or whatever the first workspace child
            // was) — clutter, not signal. Fall through to the Sidebar
            // empty-state hint until the user actually navigates.
            // Mouse hover keeps working through the chip path. 2026-08-11.
            if app.tree.cursor() == 0 {
                return None;
            }
            let row = app.tree.selected_row()?;
            let name = row
                .path
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_else(|| row.path.to_string_lossy().into_owned());
            // Info View v0.3 Phase 1.5 — prefer a curated tree-row
            // entry when one exists (language-specific hint copy).
            let target = crate::ui::info_view::InfoViewTarget::TreeRow {
                label: name.clone(),
                is_dir: row.is_dir,
            };
            if let Some(copy) = crate::ui::info_view_copy::lookup(app, &target) {
                return Some(copy.to_flat_pair());
            }
            let (primary, secondary) = if row.is_dir {
                (
                    format!("{name}/"),
                    Some("Directory. Enter or Right expands / opens. j/k walks rows.".to_string()),
                )
            } else {
                // R6 R2 multilang-dev SEV-3 2026-08-09 — show the
                // file's language on the tree row (`App.tsx` → "TypeScript
                // (JSX)"), not just the generic "File." blurb. The
                // editor-pane branch already surfaces `language_ext`
                // once a file is open; users deserve the same signal
                // while browsing so they can decide whether to open
                // an unfamiliar file without opening it first.
                let ext = row
                    .path
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|s| s.to_ascii_lowercase())
                    .unwrap_or_default();
                let lang = friendly_lang(&ext);
                let primary_with_lang = if lang.is_empty() {
                    name
                } else {
                    format!("{name}  ·  {lang}")
                };
                (
                    primary_with_lang,
                    Some(
                        "File. Enter opens it in a new tab. Right-click for cut / copy / paste / rename."
                            .to_string(),
                    ),
                )
            };
            Some((primary, secondary))
        }
        crate::focus::Focus::RightPanel => {
            let pane_idx = *app.right_panel_panes.get(app.right_panel_active_idx)?;
            let pane = app.panes.get(pane_idx)?;
            let (primary, _) = describe_active_pane(pane)?;
            Some((
                primary,
                Some(
                    "Right-panel focus. Arrows walk rows. Enter jumps. F6 cycles focus."
                        .to_string(),
                ),
            ))
        }
        crate::focus::Focus::BottomPanel => {
            let pane_idx = *app.bottom_panel_panes.get(app.bottom_panel_active_idx)?;
            let pane = app.panes.get(pane_idx)?;
            let (primary, _) = describe_active_pane(pane)?;
            Some((
                primary,
                Some(
                    "Bottom-panel focus. Arrows walk rows. Ctrl+Shift+J hides. F6 cycles focus."
                        .to_string(),
                ),
            ))
        }
    }
}

/// R11 nvchad SEV-3 2026-08-14 — return a section-level info-panel
/// hint for non-Explorer activity sections so the panel matches
/// what's drawing in the sidebar (HTTP / Integrations / Agents /
/// …) instead of the underlying tree cursor's file row. Returns
/// `None` for `Explorer` / `LauncherIcon` — caller falls through to
/// tree-row logic. Kept short + generic; per-row copy would need
/// per-section highlighted-row state which we don't expose here.
fn section_focus_hint(section: crate::app::ActivitySection) -> Option<(String, Option<String>)> {
    use crate::app::ActivitySection::*;
    let (title, body) = match section {
        Explorer | LauncherIcon(_) => return None,
        Search => (
            "Search",
            "Workspace search. `/` filters. Enter jumps to the match.",
        ),
        Git => (
            "Git",
            "Branch + worktree. Enter checks out. Right-click for stash / log / status.",
        ),
        Debug => (
            "Debug",
            "Debug panel. F5 starts, Shift+F5 continues, F10 steps over, F11 steps in.",
        ),
        Integrations => (
            "Integrations",
            "Installed integrations. Enter fires the command. Right-click for Configure / Uninstall.",
        ),
        Sessions => (
            "Sessions",
            "Open Pty sessions. Click a tab to focus. `×` closes.",
        ),
        Agents => (
            "Agents",
            "Claude / Codex dashboard. Space multi-selects, Enter opens, `k` kills.",
        ),
        CloudAgents => (
            "Cloud agents",
            "ECS runner rows. Enter opens the run detail; right-click for CloudWatch / PR / copy runId.",
        ),
        Http => (
            "HTTP",
            "Request workflow — `.http` / `.curl` browser, recent, envs. Enter opens a request.",
        ),
        Notes => (
            "Notes",
            "Workspace scratch notes under `.mnml/notes/`. Enter opens, `+ New` creates.",
        ),
        Todos => (
            "Todos",
            "Workspace TODO list. Enter jumps to the anchoring source line.",
        ),
        Findings => (
            "Findings",
            "`.mnml/findings/*.md` viewer. Enter opens the finding as a preview pane.",
        ),
        Mount(_) => (
            "Integration mount",
            "External integration pane hosted in the sidebar.",
        ),
    };
    Some((title.to_string(), Some(body.to_string())))
}

/// Map a lower-case file extension to a friendly language name for
/// the hover-help tree-row line. Unknown extensions fall back to
/// the uppercased ext (`.foo` → "FOO"). Empty ext (no extension)
/// returns "" — caller skips the ` · LANG` suffix.
///
/// R6 R2 multilang-dev SEV-3 2026-08-09 — the editor-pane branch
/// exposes `language_ext.to_ascii_uppercase()`; this widens the same
/// signal to the tree-row branch AND gives a friendly display name
/// for the common cases so a `.tsx` file reads "TypeScript (JSX)"
/// instead of "TSX".
fn friendly_lang(ext: &str) -> String {
    match ext {
        "" => String::new(),
        "rs" => "Rust".into(),
        "ts" => "TypeScript".into(),
        "tsx" => "TypeScript (JSX)".into(),
        "js" => "JavaScript".into(),
        "jsx" => "JavaScript (JSX)".into(),
        "py" => "Python".into(),
        "go" => "Go".into(),
        "rb" => "Ruby".into(),
        "java" => "Java".into(),
        "kt" | "kts" => "Kotlin".into(),
        "swift" => "Swift".into(),
        "c" => "C".into(),
        "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "hh" => "C++".into(),
        "h" => "C header".into(),
        "cs" => "C#".into(),
        "php" => "PHP".into(),
        "sh" | "bash" | "zsh" => "Shell".into(),
        "lua" => "Lua".into(),
        "vim" => "Vim script".into(),
        "md" | "markdown" => "Markdown".into(),
        "json" => "JSON".into(),
        "yaml" | "yml" => "YAML".into(),
        "toml" => "TOML".into(),
        "xml" => "XML".into(),
        "html" | "htm" => "HTML".into(),
        "css" => "CSS".into(),
        "scss" | "sass" => "Sass".into(),
        "sql" => "SQL".into(),
        "dockerfile" => "Dockerfile".into(),
        "makefile" | "mk" => "Makefile".into(),
        "proto" => "Protobuf".into(),
        "graphql" | "gql" => "GraphQL".into(),
        "http" | "curl" | "rest" => "HTTP request".into(),
        "svg" => "SVG".into(),
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" => "Image".into(),
        "pdf" => "PDF".into(),
        "txt" | "text" => "Text".into(),
        _ => ext.to_ascii_uppercase(),
    }
}

fn describe_active_pane(pane: &crate::pane::Pane) -> Option<(String, Option<String>)> {
    use crate::pane::Pane;
    match pane {
        Pane::Editor(b) => Some(describe_editor_pane(pane, b)),
        Pane::Request(_) => Some((
            pane.title(),
            Some("Request pane — Enter to send, Ctrl+S saves as .http/.curl.".into()),
        )),
        Pane::Pty(_) => Some((
            pane.title(),
            Some("Terminal pane — Ctrl+Alt+H to detach, Ctrl+Alt+K to kill.".into()),
        )),
        Pane::MdPreview(_) => Some((
            pane.title(),
            Some("Rendered markdown preview — click header chip to jump back to source.".into()),
        )),
        Pane::Ai(_) => Some((
            pane.title(),
            Some("Claude / Codex session — type at the bottom prompt.".into()),
        )),
        Pane::ClaudeAgents(p) => {
            // R6 R2 claude-agents-power SEV-3 2026-08-09 — the
            // Agents dashboard is dense enough that the generic
            // pane title tells the user nothing. Pull the
            // currently-selected row and describe it: source /
            // workspace / state / model / last activity.
            //
            // R8 fix 2026-08-10 — go through `selected_row()` so a
            // filtered / sorted list picks the ROW UNDER THE CURSOR,
            // not `rows[i]` at the raw underlying index (which reads
            // out of sync when either filter or sort is active).
            if let Some(row) = p.selected_row() {
                let source = match row.source {
                    crate::claude_agents::AgentSource::Claude => "Claude Code",
                    crate::claude_agents::AgentSource::Codex => "Codex",
                    crate::claude_agents::AgentSource::Ecs => "ECS runner",
                    crate::claude_agents::AgentSource::AnthropicManaged => "Anthropic Managed",
                };
                let state = format!("{:?}", row.state);
                let workspace = if row.workspace.is_empty() {
                    "(unknown)".to_string()
                } else {
                    row.workspace.clone()
                };
                let short_id = row.session_id.chars().take(8).collect::<String>();
                let primary = format!("{source} · {workspace} · {state} · {short_id}");
                let secondary = Some(
                    "Agents dashboard — j/k walks rows, K kills, Enter drills in, / filters."
                        .to_string(),
                );
                Some((primary, secondary))
            } else {
                Some((
                    pane.title(),
                    Some(
                        "Agents dashboard — no sessions found. j/k walks rows once populated, / filters."
                            .into(),
                    ),
                ))
            }
        }
        _ => Some((pane.title(), None)),
    }
}

/// Editor-pane hover-help copy. Priority-based — the first source of
/// signal that hits wins, since we only get one primary+secondary pair
/// to render. Ranked:
///
///   1. Diagnostic at cursor line (highest signal — user is looking at
///      an error/warning). Merges LSP + external-linter lists.
///   2. Word under cursor (LSP-ish symbol name). No hover fetch — just
///      the identifier + language + the shortcuts to drill into it.
///   3. Fallback: file title + language + cursor position + line count +
///      preview/pinned/dirty adornments.
///
/// Task #935. R8+ tester rounds asked "how can the hover help be more
/// helpful when editing code" — this branch used to be dead weight
/// (just the filename you already see in the tab).
fn describe_editor_pane(
    pane: &crate::pane::Pane,
    b: &crate::buffer::Buffer,
) -> (String, Option<String>) {
    use crate::lsp::Severity;
    let title = pane.title();
    let (row, col) = b.editor.row_col();
    let lang = b
        .language_ext
        .as_deref()
        .map(|e| e.to_ascii_uppercase())
        .unwrap_or_else(|| "TEXT".to_string());

    // Priority 1: diagnostic at cursor line. LSP + linter lists both
    // count; pick the most severe if multiple hit. Uses inclusive-of-
    // start / exclusive-of-end range check to match how gutter signs
    // paint.
    let cursor_line = row as u32;
    let sev_rank = |s: Severity| match s {
        Severity::Error => 4,
        Severity::Warning => 3,
        Severity::Info => 2,
        Severity::Hint => 1,
    };
    let mut best: Option<&crate::lsp::Diagnostic> = None;
    for d in b.diagnostics.iter().chain(b.linter_diagnostics.iter()) {
        if cursor_line >= d.range.start.line && cursor_line <= d.range.end.line {
            match best {
                None => best = Some(d),
                Some(cur) if sev_rank(d.severity) > sev_rank(cur.severity) => best = Some(d),
                _ => {}
            }
        }
    }
    if let Some(d) = best {
        let sev_label = match d.severity {
            Severity::Error => "Error",
            Severity::Warning => "Warning",
            Severity::Info => "Info",
            Severity::Hint => "Hint",
        };
        let src = d
            .source
            .as_deref()
            .filter(|s| !s.is_empty())
            .map(|s| format!(" · {s}"))
            .unwrap_or_default();
        let msg = one_line_trunc(&d.message, 160);
        let primary = format!("{sev_label} at L{}:{}  ·  {title}{src}", row + 1, col + 1);
        // R13 vscode-keyboard SEV-2 F-1 2026-08-15 — was advertising
        // only the vim-leader shortcut; standard-mode users saw
        // `<leader>` and had no chord. `Ctrl+.` is bound to
        // `lsp.code_action` in both input modes.
        let secondary = Some(format!(
            "{msg}  ·  [Ctrl+.] Code actions · [<leader>ca] (vim) · [<leader>d] Diagnostics list",
        ));
        return (primary, secondary);
    }

    // Priority 2: word under cursor (identifier only — word_under_cursor
    // already returns "" for punctuation / whitespace). Skip when the
    // buffer is empty or the cursor sits between tokens.
    let sym = b.editor.word_under_cursor();
    if !sym.is_empty() && sym.chars().count() <= 48 {
        let primary = format!("{sym}  ·  {lang}  ·  {title}  ·  L{}:{}", row + 1, col + 1);
        let secondary =
            Some("[gd] Definition · [gr] References · [K] Hover · [F2] Rename".to_string());
        return (primary, secondary);
    }

    // Priority 3: quiet fallback. Now includes L:C so the panel isn't a
    // static restatement of the tab title.
    let lines = b.editor.text().lines().count().max(1);
    let dirty = if b.dirty { " · unsaved" } else { "" };
    let primary = format!(
        "{title}  ·  {lang}  ·  L{}:{}  ·  {lines} lines{dirty}",
        row + 1,
        col + 1,
    );
    let secondary = if b.is_preview {
        Some("Preview tab — first edit or double-click promotes it.".to_string())
    } else if b.is_pinned {
        Some("Pinned — stays at the front of the bufferline.".to_string())
    } else {
        // R13 vscode-keyboard SEV-2 F-1 — also show the standard-
        // mode Ctrl+. shortcut for code actions.
        Some(
            "[gd] Definition · [gr] References · [Ctrl+.] Code actions · [Ctrl+P] Files"
                .to_string(),
        )
    };
    (primary, secondary)
}

/// Collapse whitespace runs to single spaces and truncate to `max`
/// chars (adds `…` when truncated). Used to squeeze multi-line LSP
/// diagnostic messages into a single info-panel line.
fn one_line_trunc(s: &str, max: usize) -> String {
    let mut out = String::with_capacity(s.len().min(max + 4));
    let mut prev_ws = false;
    for c in s.chars() {
        if c.is_whitespace() {
            if !prev_ws && !out.is_empty() {
                out.push(' ');
                prev_ws = true;
            }
        } else {
            out.push(c);
            prev_ws = false;
        }
    }
    let trimmed = out.trim_end();
    if trimmed.chars().count() > max {
        let mut short: String = trimmed.chars().take(max).collect();
        short.push('');
        short
    } else {
        trimmed.to_string()
    }
}

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

    #[test]
    fn wrap_preserves_word_boundaries() {
        let out = wrap_words("the quick brown fox jumps over", 10);
        // Each line ≤ 10 chars, words intact.
        for line in &out {
            assert!(line.chars().count() <= 10, "line {line:?} exceeds width");
        }
        assert!(
            out.join(" ")
                .split_whitespace()
                .eq("the quick brown fox jumps over".split_whitespace())
        );
    }

    #[test]
    fn wrap_handles_oversized_word_hard_break() {
        let out = wrap_words("supercalifragilisticexpialidocious", 8);
        for line in &out {
            assert!(line.chars().count() <= 8);
        }
        assert_eq!(out.concat(), "supercalifragilisticexpialidocious");
    }

    #[test]
    fn wrap_empty_input_returns_one_empty_line() {
        assert_eq!(wrap_words("", 10), vec![String::new()]);
    }

    #[test]
    fn wrap_zero_width_returns_one_empty_line() {
        assert_eq!(wrap_words("hello world", 0), vec![String::new()]);
    }

    use super::friendly_lang;

    #[test]
    fn friendly_lang_known_extensions() {
        assert_eq!(friendly_lang("rs"), "Rust");
        assert_eq!(friendly_lang("tsx"), "TypeScript (JSX)");
        assert_eq!(friendly_lang("py"), "Python");
        assert_eq!(friendly_lang("go"), "Go");
        assert_eq!(friendly_lang("md"), "Markdown");
        assert_eq!(friendly_lang("yaml"), "YAML");
        assert_eq!(friendly_lang("yml"), "YAML");
    }

    #[test]
    fn friendly_lang_empty_ext_returns_empty() {
        assert_eq!(friendly_lang(""), "");
    }

    #[test]
    fn friendly_lang_unknown_ext_uppercased_fallback() {
        assert_eq!(friendly_lang("xyz"), "XYZ");
    }

    use super::one_line_trunc;

    #[test]
    fn one_line_trunc_collapses_whitespace_runs() {
        assert_eq!(
            one_line_trunc("expected  u32,\n   found  i64", 40),
            "expected u32, found i64"
        );
    }

    #[test]
    fn one_line_trunc_truncates_with_ellipsis() {
        let s = one_line_trunc(&"abcd".repeat(50), 10);
        assert!(s.ends_with(''));
        // 10 chars + 1 ellipsis.
        assert_eq!(s.chars().count(), 11);
    }

    #[test]
    fn one_line_trunc_short_input_unchanged() {
        assert_eq!(one_line_trunc("short", 40), "short");
    }

    // 2026-08-16 — regression coverage for wiring `InfoViewCopy::try_it`
    // + `::docs` into the panel (Info View v0.3's framework carried
    // both fields since Phase 1 but nothing rendered or dispatched
    // them until this session). Drives the real `draw()` fn against a
    // `TestBackend` so a future refactor that silently drops the click
    // rects gets caught here, not by a user reporting dead links.
    #[test]
    fn draw_populates_try_it_click_rects_for_a_chip_with_links() {
        use crate::app::App;
        use crate::config::Config;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let d = tempfile::tempdir().unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        // StatuslineMode has exactly one `try_it` link
        // (`editor.toggle_keymap`) plus a `docs` link — pick a chip
        // whose curated copy exercises both wired affordances.
        app.hover_chip = Some((crate::HoverChip::StatuslineMode, std::time::Instant::now()));
        let area = Rect {
            x: 0,
            y: 0,
            width: 30,
            height: 20,
        };
        let mut term = Terminal::new(TestBackend::new(30, 20)).unwrap();
        term.draw(|f| draw(f, &mut app, area)).unwrap();

        assert_eq!(
            app.rects.hover_help_try_it.len(),
            1,
            "StatuslineMode's one try_it link should produce one click rect"
        );
        let (rect, cmd_id) = &app.rects.hover_help_try_it[0];
        assert_eq!(cmd_id, "editor.toggle_keymap");
        assert!(
            area.intersects(*rect),
            "try_it rect must sit inside the panel area"
        );
        let (docs_rect, url) = app
            .rects
            .hover_help_docs
            .as_ref()
            .expect("StatuslineMode has a docs link");
        assert!(url.starts_with("https://mnml.sh/manual/"));
        assert!(area.intersects(*docs_rect));
    }

    #[test]
    fn draw_clears_stale_try_it_rects_when_panel_shrinks_to_a_sliver() {
        use crate::app::App;
        use crate::config::Config;
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let d = tempfile::tempdir().unwrap();
        let mut app = App::new(d.path().to_path_buf(), Config::default()).unwrap();
        app.hover_chip = Some((crate::HoverChip::StatuslineMode, std::time::Instant::now()));
        // First draw at full height populates a try_it rect.
        let mut term = Terminal::new(TestBackend::new(30, 20)).unwrap();
        term.draw(|f| {
            draw(
                f,
                &mut app,
                Rect {
                    x: 0,
                    y: 0,
                    width: 30,
                    height: 20,
                },
            )
        })
        .unwrap();
        assert_eq!(app.rects.hover_help_try_it.len(), 1);
        // Shrink to a 1-row sliver (early-returns before the body
        // renders) — the stale rect from the taller frame must not
        // survive, or a click there would fire a command with nothing
        // visibly clickable on screen.
        let mut term2 = Terminal::new(TestBackend::new(30, 1)).unwrap();
        term2
            .draw(|f| {
                draw(
                    f,
                    &mut app,
                    Rect {
                        x: 0,
                        y: 0,
                        width: 30,
                        height: 1,
                    },
                )
            })
            .unwrap();
        assert!(app.rects.hover_help_try_it.is_empty());
    }
}