penknife 0.2.1

Git-style remotes for your documents: sync a folder of markdown to GitHub Gists, track drift per file, and copy anything as rich text to paste elsewhere
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
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use unicode_width::UnicodeWidthChar;

use crate::app::App;
use crate::ui::input::LineEditor;

/// Render a centered modal overlay sized as a percentage of the screen.
/// Used by the dialogs that are scrollable viewports (file picker, replace
/// review) where more room is simply better.
fn modal_area(area: Rect, width_pct: u16, height_pct: u16) -> Rect {
    let vertical = Layout::vertical([
        Constraint::Percentage((100 - height_pct) / 2),
        Constraint::Percentage(height_pct),
        Constraint::Percentage((100 - height_pct) / 2),
    ])
    .split(area);

    Layout::horizontal([
        Constraint::Percentage((100 - width_pct) / 2),
        Constraint::Percentage(width_pct),
        Constraint::Percentage((100 - width_pct) / 2),
    ])
    .split(vertical[1])[1]
}

/// Center a `w`×`h` rect within `area`, shrinking to fit if needed.
fn centered(area: Rect, w: u16, h: u16) -> Rect {
    let w = w.min(area.width);
    let h = h.min(area.height);
    Rect {
        x: area.x + (area.width - w) / 2,
        y: area.y + (area.height - h) / 2,
        width: w,
        height: h,
    }
}

/// Size a modal to its content: width fits the widest line (plus borders),
/// height fits the wrapped row count. Width is clamped between `min_width`
/// and the screen minus a small margin; when clamping forces wrapping, the
/// height estimate grows to match. Fixed-content dialogs use this so a
/// two-line confirm isn't a quarter of a 4K screen and a tall help page
/// isn't squeezed to 70% on a small one.
fn modal_for_lines(area: Rect, lines: &[Line], min_width: u16) -> Rect {
    let max_w = area.width.saturating_sub(4).max(1);
    let content_w = lines.iter().map(|l| l.width()).max().unwrap_or(0) as u16;
    let w = (content_w + 4).clamp(min_width.min(max_w), max_w);
    let inner_w = w.saturating_sub(2).max(1) as usize;
    let rows: usize = lines
        .iter()
        .map(|l| l.width().div_ceil(inner_w).max(1))
        .sum();
    let h = (rows.max(1) as u16).saturating_add(2);
    centered(area, w, h)
}

/// Render the help overlay.
pub fn render_help(f: &mut Frame, area: Rect, app: &App) {
    // Section headers and key/description pairs. Each pair is rendered with
    // the key chord in yellow/bold and the description in default white -
    // makes the table easier to scan than the previous monochrome block.
    let sections: &[(&str, &[(&str, &str)])] = &[
        (
            "Navigation",
            &[
                ("Tab", "Toggle focus: tree pane ↔ preview/diff pane"),
                ("j/k  ↑/↓", "Navigate the focused pane"),
                ("Enter  l  →", "Expand / select (tree pane)"),
                ("h  ←  Bksp", "Collapse (tree pane)"),
                ("PgUp/PgDn", "Scroll preview/diff (any focus)"),
                ("n / N", "Jump to next / previous non-synced file"),
            ],
        ),
        (
            "Gist actions",
            &[
                ("u", "Push selected file to gist"),
                ("d", "Pull remote into selected file"),
                ("c", "Copy gist URL to clipboard"),
                ("o", "Open gist URL in browser"),
                ("e", "Edit selected file in $EDITOR"),
                ("m", "Rename / move the selected file"),
                ("X", "Delete menu: remote gist, local file, or both"),
                ("D", "Diff local vs remote"),
                ("M", "Resolve ambiguous hydration matches"),
                ("L", "Link selected file to an existing gist by URL/ID"),
            ],
        ),
        (
            "Clipboard",
            &[
                ("C", "Copy selected file's contents (markdown) to clipboard"),
                ("p", "Copy as rich text (paste into Docs, email, Slack)"),
                ("V", "Paste clipboard (rich HTML → markdown) as new file"),
            ],
        ),
        (
            "Git (when root is in a repo)",
            &[("g", "Git menu: status / log / pull / push")],
        ),
        (
            "Files & roots",
            &[
                ("/", "Fuzzy file picker (fzf-style)"),
                ("f", "Find in files (content search, jump to match)"),
                ("O", "Pick sort order for the tree"),
                ("B", "Bulk ops menu (push/pull dirty, format JSON, prune)"),
                ("s", "Find & replace (recursive within current scope)"),
                ("I", "Import from URL (Google Doc or gist) as markdown"),
                ("R", "Switch root directory"),
                ("?", "This help"),
                ("q", "Quit"),
            ],
        ),
    ];

    let key_style = Style::default()
        .fg(Color::Yellow)
        .add_modifier(Modifier::BOLD);
    let header_style = Style::default()
        .fg(Color::Cyan)
        .add_modifier(Modifier::BOLD);
    let desc_style = Style::default().fg(Color::White);
    let dim = Style::default().fg(Color::DarkGray);

    let mut lines: Vec<Line> = Vec::new();
    for (idx, (header, pairs)) in sections.iter().enumerate() {
        if idx > 0 {
            lines.push(Line::raw(""));
        }
        lines.push(Line::styled(header.to_string(), header_style));
        for (key, desc) in *pairs {
            lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(format!("{key:<12}"), key_style),
                Span::raw(" "),
                Span::styled(desc.to_string(), desc_style),
            ]));
        }
    }
    // Configured aliases, if any.
    if !app.config.aliases.is_empty() {
        lines.push(Line::raw(""));
        lines.push(Line::styled("Aliases (from config.toml)", header_style));
        for (k, cmd) in &app.config.aliases {
            lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(format!("{k:<12}"), key_style),
                Span::raw(" "),
                Span::styled(cmd.clone(), desc_style),
            ]));
        }
    }

    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "In Diff view: j/k, arrows, PgUp/PgDn scroll; Esc/q exits.",
        dim,
    ));
    lines.push(Line::styled(
        "Mouse: cmd-click on URLs and native selection work by default.",
        dim,
    ));
    lines.push(Line::styled(
        "Set PENKNIFE_MOUSE=1 to enable click-to-select + wheel-scroll routing.",
        dim,
    ));
    lines.push(Line::styled(
        "Icons: slim unicode by default; PENKNIFE_EMOJI=1 for emoji, PENKNIFE_NO_EMOJI=1 for ASCII.",
        dim,
    ));
    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "Press any key to close.",
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::ITALIC),
    ));

    let modal = modal_for_lines(area, &lines, 60);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} Help", g.help))
        .border_style(Style::default().fg(Color::Cyan))
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render the fzf-style file picker overlay. Top row is the query input;
/// the rest is a ranked list of matching paths with the matched characters
/// highlighted. Selected row is inverted.
pub fn render_file_picker(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let modal = modal_area(area, 75, 70);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let total = app.files.len();
    let shown = app.picker_matches.len();
    let yellow_bold = Style::default()
        .fg(Color::Yellow)
        .add_modifier(Modifier::BOLD);
    let title_line = Line::from(vec![
        Span::styled(format!("{} ", g.search), Style::default().fg(Color::Yellow)),
        Span::styled("Find file", yellow_bold),
        Span::raw("  "),
        Span::styled("(", Style::default().fg(Color::DarkGray)),
        Span::styled(
            shown.to_string(),
            Style::default()
                .fg(if shown == 0 {
                    Color::DarkGray
                } else {
                    Color::Cyan
                })
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("/", Style::default().fg(Color::DarkGray)),
        Span::styled(total.to_string(), Style::default().fg(Color::White)),
        Span::styled(")", Style::default().fg(Color::DarkGray)),
    ]);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title_line)
        .border_style(Style::default().fg(Color::Yellow));
    let inner = block.inner(modal);
    f.render_widget(block, modal);

    let chunks = Layout::vertical([
        Constraint::Length(1), // query line
        Constraint::Length(1), // separator
        Constraint::Min(1),    // results
        Constraint::Length(1), // hints
    ])
    .split(inner);

    // Query line (with a visible cursor)
    let mut query_spans = vec![Span::styled(
        "> ",
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )];
    query_spans.extend(app.picker_editor.spans(Style::default()));
    f.render_widget(Paragraph::new(Line::from(query_spans)), chunks[0]);

    // Visible window: clamp `selected` into a scrolling viewport that keeps
    // the cursor in view without bouncing.
    let view_h = chunks[2].height as usize;
    let start = if view_h == 0 {
        0
    } else if selected >= view_h {
        selected + 1 - view_h
    } else {
        0
    };
    let end = (start + view_h).min(app.picker_matches.len());

    let mut lines: Vec<Line> = Vec::with_capacity(end.saturating_sub(start));
    for (i, m) in app.picker_matches[start..end].iter().enumerate() {
        let row_idx = start + i;
        let is_selected = row_idx == selected;
        let row_style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            Style::default()
        };
        let marker = if is_selected { "" } else { "  " };
        let mut spans: Vec<Span<'static>> = Vec::new();
        spans.push(Span::styled(marker, row_style));
        // Render rel_path char-by-char, highlighting indices that nucleo
        // identified as match positions.
        let mut idx_iter = m.indices.iter().copied().peekable();
        for (pos, ch) in m.rel_path.chars().enumerate() {
            let highlighted = matches!(idx_iter.peek(), Some(&p) if p as usize == pos);
            if highlighted {
                idx_iter.next();
            }
            let style = match (is_selected, highlighted) {
                (true, true) => row_style.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
                (true, false) => row_style,
                (false, true) => Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
                (false, false) => Style::default(),
            };
            spans.push(Span::styled(ch.to_string(), style));
        }
        lines.push(Line::from(spans));
    }
    if lines.is_empty() {
        lines.push(Line::styled(
            "  (no matches)",
            Style::default().fg(Color::DarkGray),
        ));
    }
    f.render_widget(Paragraph::new(lines), chunks[2]);

    // Hint footer
    let hints = Line::styled(
        "↑/↓ or Ctrl-n/p select · Enter open · Esc cancel",
        Style::default().fg(Color::DarkGray),
    );
    f.render_widget(Paragraph::new(hints), chunks[3]);
}

/// Render a text input dialog with a prompt.
pub fn render_input_dialog(
    f: &mut Frame,
    area: Rect,
    title: &str,
    prompt: &str,
    editor: &LineEditor,
) {
    let mut input_spans = vec![Span::styled(
        "> ",
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )];
    input_spans.extend(editor.spans(Style::default().fg(Color::Yellow)));
    let lines = vec![
        Line::styled(
            prompt.to_string(),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Line::raw(""),
        Line::from(input_spans),
    ];

    // min_width 60 keeps the box from resizing on every keystroke; it only
    // grows once the prompt or the typed text actually needs more room.
    let modal = modal_for_lines(area, &lines, 60);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(title.to_string())
        .border_style(Style::default().fg(Color::Cyan))
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render a confirmation dialog.
pub fn render_confirm(f: &mut Frame, area: Rect, message: &str) {
    let bold = Modifier::BOLD;
    let dim = Style::default().fg(Color::DarkGray);
    let lines = vec![
        Line::styled(message.to_string(), Style::default().fg(Color::White)),
        Line::raw(""),
        Line::from(vec![
            Span::styled("[", dim),
            Span::styled("y", Style::default().fg(Color::Green).add_modifier(bold)),
            Span::styled("/Enter] ", dim),
            Span::styled("Yes", Style::default().fg(Color::Green)),
            Span::raw("   "),
            Span::styled("[", dim),
            Span::styled("n", Style::default().fg(Color::Red).add_modifier(bold)),
            Span::styled("/Esc] ", dim),
            Span::styled("No", Style::default().fg(Color::Red)),
        ]),
    ];

    let modal = modal_for_lines(area, &lines, 44);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{}  Confirm", g.warn))
        .border_style(Style::default().fg(Color::Red))
        .title_style(Style::default().fg(Color::Red).add_modifier(bold));
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render a status message overlay.
pub fn render_message(f: &mut Frame, area: Rect, message: &str) {
    let lines: Vec<Line> = message.lines().map(Line::raw).collect();
    let modal = modal_for_lines(area, &lines, 40);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} Info", g.info))
        .border_style(Style::default().fg(Color::Green))
        .title_style(
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(message.to_string())
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render root switcher dialog.
pub fn render_root_switcher(f: &mut Frame, area: Rect, app: &App) {
    let selected = if let crate::app::Mode::RootSwitcher { selected } = &app.mode {
        *selected
    } else {
        0
    };

    let mut lines: Vec<Line> = Vec::new();
    for (i, root) in app.config.roots.iter().enumerate() {
        let marker = if i == app.active_root { "" } else { "   " };
        let style = if i == selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else if i == app.active_root {
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        lines.push(Line::styled(
            format!("{marker}{}", root.path.display()),
            style,
        ));
    }

    if app.config.roots.is_empty() {
        lines.push(Line::styled(
            "  (no roots configured)".to_string(),
            Style::default().fg(Color::DarkGray),
        ));
    }

    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "  Enter=switch  a=add  d=delete  Esc=close".to_string(),
        Style::default().fg(Color::DarkGray),
    ));

    let modal = modal_for_lines(area, &lines, 50);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} Root Directories", g.root))
        .border_style(Style::default().fg(Color::Cyan))
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render the ambiguous-match resolver dialog. Shows the current item with
/// the candidate gists and footer keybindings.
pub fn render_resolve_ambiguous(
    f: &mut Frame,
    area: Rect,
    app: &App,
    item: usize,
    selected: usize,
) {
    let total = app.pending_ambiguous.len();
    let mut lines: Vec<Line> = Vec::new();
    if let Some(am) = app.pending_ambiguous.get(item) {
        lines.push(Line::styled(
            format!("Local file: {}", am.local_path),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ));
        lines.push(Line::raw(""));
        lines.push(Line::styled(
            "Candidate gists:",
            Style::default().fg(Color::White),
        ));
        for (i, c) in am.candidates.iter().enumerate() {
            let marker = if i == selected { "" } else { "   " };
            let style = if i == selected {
                Style::default().fg(Color::Black).bg(Color::Cyan)
            } else {
                Style::default()
            };
            let desc = c.description.as_deref().unwrap_or("(no description)");
            lines.push(Line::styled(
                format!("{marker}{:.10}  {} bytes  {}", c.remote_id, c.size, desc),
                style,
            ));
            lines.push(Line::styled(
                format!("    {}", c.url),
                Style::default().fg(Color::DarkGray),
            ));
        }
    }

    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "j/k=navigate  Enter=pick  s=skip  Esc=abort",
        Style::default().fg(Color::DarkGray),
    ));

    let modal = modal_for_lines(area, &lines, 60);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let title = format!(
        "{} Resolve ambiguous match ({} of {})",
        g.question,
        item + 1,
        total
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::default().fg(Color::Yellow))
        .title_style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render the find-and-replace review dialog. Top line summarizes the
/// substitution and scope; below, a scrollable checklist where each row is
/// one match (rel_path:line + the line text with the matched substring
/// highlighted). Space toggles, a/z select all/none, Enter applies, Esc
/// aborts.
/// Render the find-in-files jump list: path:line rows with the match
/// highlighted in context. Enter jumps to the file; no mutation involved.
pub fn render_search_results(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let modal = modal_area(area, 85, 80);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let total = app.search_matches.len();

    let title_line = Line::from(vec![
        Span::styled(format!("{} ", g.search), Style::default().fg(Color::Yellow)),
        Span::styled(
            "Find",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw("  "),
        Span::styled("(", Style::default().fg(Color::DarkGray)),
        Span::styled(
            format!("{}/{}", (selected + 1).min(total), total),
            Style::default().fg(Color::White),
        ),
        Span::styled(")", Style::default().fg(Color::DarkGray)),
    ]);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title_line)
        .border_style(Style::default().fg(Color::Yellow));
    let inner = block.inner(modal);
    f.render_widget(block, modal);

    let chunks = Layout::vertical([
        Constraint::Length(1), // summary line
        Constraint::Length(1), // spacer
        Constraint::Min(1),    // results
    ])
    .split(inner);

    let dim = Style::default().fg(Color::DarkGray);
    let summary = Line::from(vec![
        Span::styled("'", dim),
        Span::styled(
            app.search_query.clone(),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("' in ", dim),
        Span::styled(app.replace_scope_label(), Style::default().fg(Color::Cyan)),
    ]);
    f.render_widget(Paragraph::new(summary), chunks[0]);

    // Scrolling viewport for the list.
    let view_h = chunks[2].height as usize;
    let start = if view_h == 0 {
        0
    } else if selected >= view_h {
        selected + 1 - view_h
    } else {
        0
    };
    let end = (start + view_h).min(total);

    let mut lines: Vec<Line> = Vec::with_capacity(end.saturating_sub(start));
    for row_idx in start..end {
        let m = &app.search_matches[row_idx];
        let is_selected = row_idx == selected;
        let row_bg = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            Style::default()
        };
        let mut spans: Vec<Span<'static>> = Vec::new();
        spans.push(Span::styled(
            if is_selected { "" } else { "   " },
            row_bg,
        ));
        spans.push(Span::styled(
            format!("{}:{}", m.rel_path, m.line),
            if is_selected {
                row_bg
            } else {
                Style::default().fg(Color::Magenta)
            },
        ));
        spans.push(Span::raw("  "));
        let line = &m.line_text;
        let end_byte = m.col_byte + app.search_query.len();
        let before = line.get(..m.col_byte).unwrap_or("");
        let hit = line.get(m.col_byte..end_byte).unwrap_or("");
        let after = line.get(end_byte..).unwrap_or("");
        let (before, after) = trim_context(before, after, 30);
        spans.push(Span::styled(before, row_bg));
        spans.push(Span::styled(
            hit.to_string(),
            if is_selected {
                row_bg.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
            } else {
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
            },
        ));
        spans.push(Span::styled(after, row_bg));
        lines.push(Line::from(spans));
    }
    if lines.is_empty() {
        lines.push(Line::styled("  (no matches)", dim));
    }
    f.render_widget(Paragraph::new(lines), chunks[2]);
}

pub fn render_replace_review(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let modal = modal_area(area, 85, 80);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let total = app.replace_matches.len();
    let checked = app.replace_checked.iter().filter(|c| **c).count();

    let title_line = Line::from(vec![
        Span::styled(format!("{} ", g.search), Style::default().fg(Color::Yellow)),
        Span::styled(
            "Replace",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw("  "),
        Span::styled("(", Style::default().fg(Color::DarkGray)),
        Span::styled(
            checked.to_string(),
            Style::default()
                .fg(if checked == 0 {
                    Color::DarkGray
                } else {
                    Color::Green
                })
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("/", Style::default().fg(Color::DarkGray)),
        Span::styled(total.to_string(), Style::default().fg(Color::White)),
        Span::styled(" checked)", Style::default().fg(Color::DarkGray)),
    ]);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title_line)
        .border_style(Style::default().fg(Color::Yellow));
    let inner = block.inner(modal);
    f.render_widget(block, modal);

    let chunks = Layout::vertical([
        Constraint::Length(1), // summary line
        Constraint::Length(1), // spacer
        Constraint::Min(1),    // results
        Constraint::Length(1), // hints
    ])
    .split(inner);

    // Summary line: 'foo' → 'bar' in scope/path
    let dim = Style::default().fg(Color::DarkGray);
    let summary = Line::from(vec![
        Span::styled("'", dim),
        Span::styled(
            app.replace_query.clone(),
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::styled("' → '", dim),
        Span::styled(
            if app.replace_target.is_empty() {
                "(empty - delete matches)".to_string()
            } else {
                app.replace_target.clone()
            },
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("' in ", dim),
        Span::styled(app.replace_scope_label(), Style::default().fg(Color::Cyan)),
    ]);
    f.render_widget(Paragraph::new(summary), chunks[0]);

    // Scrolling viewport for the list.
    let view_h = chunks[2].height as usize;
    let start = if view_h == 0 {
        0
    } else if selected >= view_h {
        selected + 1 - view_h
    } else {
        0
    };
    let end = (start + view_h).min(total);

    let mut lines: Vec<Line> = Vec::with_capacity(end.saturating_sub(start));
    for row_idx in start..end {
        let m = &app.replace_matches[row_idx];
        let is_checked = app.replace_checked.get(row_idx).copied().unwrap_or(false);
        let is_selected = row_idx == selected;
        let row_bg = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            Style::default()
        };
        let mark = if is_checked { "" } else { " " };
        let mark_color = if is_checked {
            Color::Green
        } else {
            Color::DarkGray
        };
        let mut spans: Vec<Span<'static>> = Vec::new();
        // Selection caret + checkbox.
        spans.push(Span::styled(
            if is_selected { "" } else { "   " },
            row_bg,
        ));
        spans.push(Span::styled(
            format!("[{mark}] "),
            if is_selected {
                row_bg.add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(mark_color).add_modifier(Modifier::BOLD)
            },
        ));
        // Path:line - magenta path, cyan line number.
        spans.push(Span::styled(
            format!("{}:{}", m.rel_path, m.line),
            if is_selected {
                row_bg
            } else {
                Style::default().fg(Color::Magenta)
            },
        ));
        spans.push(Span::raw("  "));
        // Line context with the match highlighted.
        let line = &m.line_text;
        let end_byte = m.col_byte + app.replace_query.len();
        let before = line.get(..m.col_byte).unwrap_or("");
        let hit = line.get(m.col_byte..end_byte).unwrap_or("");
        let after = line.get(end_byte..).unwrap_or("");
        // Trim long lines to fit. Keep ~30 chars on each side of the match.
        let (before, after) = trim_context(before, after, 30);
        spans.push(Span::styled(before, row_bg));
        spans.push(Span::styled(
            hit.to_string(),
            if is_selected {
                row_bg.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
            } else {
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
            },
        ));
        spans.push(Span::styled(after, row_bg));
        lines.push(Line::from(spans));
    }
    if lines.is_empty() {
        lines.push(Line::styled("  (no matches)", dim));
    }
    f.render_widget(Paragraph::new(lines), chunks[2]);

    let hints = Line::from(vec![
        Span::styled("Space ", Style::default().fg(Color::Yellow)),
        Span::styled("toggle  ", dim),
        Span::styled("a ", Style::default().fg(Color::Yellow)),
        Span::styled("all  ", dim),
        Span::styled("z ", Style::default().fg(Color::Yellow)),
        Span::styled("none  ", dim),
        Span::styled("↑/↓ ", Style::default().fg(Color::Yellow)),
        Span::styled("move  ", dim),
        Span::styled("Enter ", Style::default().fg(Color::Green)),
        Span::styled("apply  ", dim),
        Span::styled("Esc ", Style::default().fg(Color::Red)),
        Span::styled("cancel", dim),
    ]);
    f.render_widget(Paragraph::new(hints), chunks[3]);
}

/// Truncate `before`/`after` context strings around a match so each fits in
/// roughly `pad` display columns. Front-ellipsizes the "before" side and
/// back-ellipsizes the "after" side so the matched substring stays visible.
/// Budgeting by width (not chars) keeps rows with CJK context aligned.
fn trim_context(before: &str, after: &str, pad: usize) -> (String, String) {
    fn take_cols(chars: impl Iterator<Item = char>, budget: usize) -> (Vec<char>, bool) {
        let mut used = 0;
        let mut out = Vec::new();
        let mut truncated = false;
        for ch in chars {
            let w = ch.width().unwrap_or(0);
            if used + w > budget {
                truncated = true;
                break;
            }
            used += w;
            out.push(ch);
        }
        (out, truncated)
    }

    let (mut b_rev, b_trunc) = take_cols(before.chars().rev(), pad);
    b_rev.reverse();
    let b_kept: String = b_rev.into_iter().collect();
    let b_out = if b_trunc {
        format!("{b_kept}")
    } else {
        b_kept
    };

    let (a_fwd, a_trunc) = take_cols(after.chars(), pad);
    let a_kept: String = a_fwd.into_iter().collect();
    let a_out = if a_trunc {
        format!("{a_kept}")
    } else {
        a_kept
    };
    (b_out, a_out)
}

/// Render the bulk-operations picker. Shows the four ops, each with its
/// precomputed file count colored by emptiness (dim if 0, yellow/bold if >0).
/// Render a simple fixed-choice menu: caret + label rows, hint line, titled
/// modal. Shared chassis for the delete and git menus.
fn render_choice_menu(f: &mut Frame, area: Rect, title: &str, labels: &[&str], selected: usize) {
    let mut lines: Vec<Line> = Vec::new();
    for (i, label) in labels.iter().enumerate() {
        let is_selected = i == selected;
        let marker = if is_selected { "" } else { "   " };
        let row_style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            Style::default().fg(Color::White)
        };
        lines.push(Line::from(vec![
            Span::styled(marker.to_string(), row_style),
            Span::styled((*label).to_string(), row_style),
        ]));
    }
    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "  ↑/↓ navigate · Enter choose · Esc cancel",
        Style::default().fg(Color::DarkGray),
    ));

    let modal = modal_for_lines(area, &lines, 48);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(title.to_string())
        .border_style(Style::default().fg(Color::Yellow))
        .title_style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
    let inner = block.inner(modal);
    f.render_widget(block, modal);
    f.render_widget(Paragraph::new(lines), inner);
}

pub fn render_delete_menu(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let g = crate::glyphs::glyphs();
    let opts = app.delete_options();
    let labels: Vec<&str> = opts.iter().map(|o| o.label()).collect();
    let file = app.selected_file().unwrap_or_default();
    render_choice_menu(
        f,
        area,
        &format!("{} Delete: {file}", g.warn),
        &labels,
        selected,
    );
}

pub fn render_git_menu(f: &mut Frame, area: Rect, selected: usize) {
    let g = crate::glyphs::glyphs();
    render_choice_menu(
        f,
        area,
        &format!("{} Git", g.file_pane),
        crate::app::GIT_MENU_LABELS,
        selected,
    );
}

pub fn render_bulk_menu(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let opts = app.bulk_options();
    let mut lines: Vec<Line> = Vec::new();
    for (i, opt) in opts.iter().enumerate() {
        let is_selected = i == selected;
        let count = opt.count();
        let marker = if is_selected { "" } else { "   " };
        let row_style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else {
            Style::default().fg(Color::White)
        };
        let count_style = if is_selected {
            row_style.add_modifier(Modifier::BOLD)
        } else if count == 0 {
            Style::default().fg(Color::DarkGray)
        } else {
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
        };
        lines.push(Line::from(vec![
            Span::styled(marker.to_string(), row_style),
            Span::styled(format!("{:<26}", opt.label()), row_style),
            Span::styled(format!("({count})"), count_style),
        ]));
    }
    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "  ↑/↓ navigate · Enter run (with confirm) · Esc cancel",
        Style::default().fg(Color::DarkGray),
    ));

    let modal = modal_for_lines(area, &lines, 50);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} Bulk operations", g.file_pane))
        .border_style(Style::default().fg(Color::Yellow))
        .title_style(
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render the sort-mode picker. Lists the five sort modes with the active
/// one marked, and the cursor on `selected`.
pub fn render_sort_menu(f: &mut Frame, area: Rect, app: &App, selected: usize) {
    let active = app.config.sort.mode;
    let mut lines: Vec<Line> = Vec::new();
    for (i, mode) in crate::config::SortMode::all().iter().enumerate() {
        let is_selected = i == selected;
        let is_active = *mode == active;
        let marker = if is_active { "" } else { "   " };
        let style = if is_selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else if is_active {
            Style::default()
                .fg(Color::Green)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::White)
        };
        lines.push(Line::styled(format!("{marker}{}", mode.label()), style));
    }
    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "  ↑/↓ navigate · Enter select · Esc cancel",
        Style::default().fg(Color::DarkGray),
    ));

    let modal = modal_for_lines(area, &lines, 44);
    f.render_widget(Clear, modal);

    let g = crate::glyphs::glyphs();
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} Sort by", g.file_pane))
        .border_style(Style::default().fg(Color::Cyan))
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}

/// Render setup/add root dialog.
pub fn render_setup_root(f: &mut Frame, area: Rect, app: &App) {
    let g = crate::glyphs::glyphs();
    let is_setup = matches!(app.mode, crate::app::Mode::SetupRoot);
    let title: String = if is_setup {
        format!("{} Welcome to penknife", g.welcome)
    } else {
        format!("{} Add Root Directory", g.root)
    };
    let prompt = if is_setup {
        "Enter path to your writings folder:"
    } else {
        "Enter path to add:"
    };
    let hint = if is_setup {
        "(Enter to confirm · Ctrl+Q to quit)"
    } else {
        "(Enter to confirm · Esc to cancel)"
    };

    let mut input_spans = vec![Span::styled(
        "> ",
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )];
    input_spans.extend(app.input_editor.spans(Style::default().fg(Color::Yellow)));
    let lines = vec![
        Line::styled(
            prompt.to_string(),
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        ),
        Line::raw(""),
        Line::from(input_spans),
        Line::raw(""),
        Line::styled(
            hint.trim().to_string(),
            Style::default().fg(Color::DarkGray),
        ),
    ];

    let modal = modal_for_lines(area, &lines, 60);
    f.render_widget(Clear, modal);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::default().fg(Color::Cyan))
        .title_style(
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        );
    let para = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(para, modal);
}