clin-rs 0.3.3

Encrypted terminal note-taking app
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
use crate::app::{App, EditFocus, ListFocus, TemplatePopup, ViewMode};
use crate::constants::*;
use crate::events::get_title_text;
use crate::keybinds::*;
use anyhow::{Context, Result};
use ratatui::{prelude::*, widgets::*};
use std::borrow::Cow;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};
use tui_textarea::*;

pub fn draw_ui(frame: &mut Frame, app: &mut App, focus: EditFocus) {
    match app.mode {
        ViewMode::List => draw_list_view(frame, app),
        ViewMode::Edit => draw_edit_view(frame, app, focus),
        ViewMode::Help => draw_help_view(frame, app),
    }
}

pub fn draw_help_view(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(8), Constraint::Length(3)])
        .split(area);

    let help_text = app.get_help_text().clone();
    let help = Paragraph::new(help_text)
        .block(Block::default().borders(Borders::ALL).title("Help"))
        .wrap(Wrap { trim: false })
        .scroll((app.help_scroll, 0));
    frame.render_widget(help, chunks[0]);

    let footer = Paragraph::new(HELP_PAGE_HINTS)
        .block(Block::default().borders(Borders::ALL).title("Navigation"));
    frame.render_widget(footer, chunks[1]);
}

pub fn help_page_text(keybinds: &Keybinds) -> Text<'static> {
    // Get keybind display strings
    let list_move = format!(
        "{}/{}",
        keybinds.list_keys_display(ListAction::MoveUp),
        keybinds.list_keys_display(ListAction::MoveDown)
    );
    let list_expand_collapse = format!(
        "{}/{}",
        keybinds.list_keys_display(ListAction::ExpandFolder),
        keybinds.list_keys_display(ListAction::CollapseFolder)
    );
    let list_open = keybinds.list_keys_display(ListAction::Open);
    let list_delete = keybinds.list_keys_display(ListAction::Delete);
    let list_location = keybinds.list_keys_display(ListAction::OpenLocation);
    let list_focus = keybinds.list_keys_display(ListAction::CycleFocus);
    let list_help = keybinds.list_keys_display(ListAction::Help);
    let list_quit = keybinds.list_keys_display(ListAction::Quit);
    let list_template = keybinds.list_keys_display(ListAction::NewFromTemplate);
    let list_create_folder = keybinds.list_keys_display(ListAction::CreateFolder);
    let list_rename_folder = keybinds.list_keys_display(ListAction::RenameFolder);
    let list_move_note = keybinds.list_keys_display(ListAction::MoveNote);
    let list_manage_tags = keybinds.list_keys_display(ListAction::ManageTags);
    let list_filter_tags = keybinds.list_keys_display(ListAction::FilterTags);

    let edit_quit = keybinds.edit_keys_display(EditAction::Quit);
    let edit_back = keybinds.edit_keys_display(EditAction::Back);
    let edit_focus = keybinds.edit_keys_display(EditAction::CycleFocus);
    let edit_copy = keybinds.edit_keys_display(EditAction::Copy);
    let edit_cut = keybinds.edit_keys_display(EditAction::Cut);
    let edit_paste = keybinds.edit_keys_display(EditAction::Paste);
    let edit_select_all = keybinds.edit_keys_display(EditAction::SelectAll);
    let edit_undo = keybinds.edit_keys_display(EditAction::Undo);
    let edit_redo = keybinds.edit_keys_display(EditAction::Redo);
    let edit_del_word = keybinds.edit_keys_display(EditAction::DeleteWord);
    let edit_del_next_word = keybinds.edit_keys_display(EditAction::DeleteNextWord);

    let help_close = keybinds.help_keys_display(HelpAction::Close);
    let help_scroll = format!(
        "{}/{}",
        keybinds.help_keys_display(HelpAction::ScrollUp),
        keybinds.help_keys_display(HelpAction::ScrollDown)
    );

    let mut lines = Vec::new();
    lines.push(Line::from(vec![
        Span::styled(
            "󰠮 clin",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" Help", Style::default().add_modifier(Modifier::BOLD)),
    ]));
    lines.push(Line::from(""));

    lines.push(help_heading("󰋗", "Core Features"));
    lines.extend(help_item_dyn("Encrypted local note files (.clin)", None));
    lines.extend(help_item_dyn(
        "In-terminal note list, full text editor, and continual auto-save",
        None,
    ));
    lines.extend(help_item_dyn(
        "Open note file location from notes view",
        Some(&list_location),
    ));
    lines.extend(help_item_dyn(
        "Delete selected note or folder",
        Some(&list_delete),
    ));
    lines.push(Line::from(""));

    lines.push(help_heading("󰮋", "Notes View"));
    lines.extend(help_item_dyn("Move selection", Some(&list_move)));
    lines.extend(help_item_dyn(
        "Expand/Collapse folder",
        Some(&list_expand_collapse),
    ));
    lines.extend(help_item_dyn(
        "Open selected folder, note, or create new",
        Some(&list_open),
    ));
    lines.extend(help_item_dyn(
        "Create new folder",
        Some(&list_create_folder),
    ));
    lines.extend(help_item_dyn("Rename folder", Some(&list_rename_folder)));
    lines.extend(help_item_dyn("Move note to folder", Some(&list_move_note)));
    lines.extend(help_item_dyn("Manage note tags", Some(&list_manage_tags)));
    lines.extend(help_item_dyn("Filter tags", Some(&list_filter_tags)));
    lines.extend(help_item_dyn("Delete note or folder", Some(&list_delete)));
    lines.extend(help_item_dyn(
        "Confirm / cancel delete",
        Some("y/Enter / n/Esc"),
    ));
    lines.extend(help_item_dyn(
        "Open selected note file location",
        Some(&list_location),
    ));
    lines.extend(help_item_dyn(
        "Change focus (notes list <-> buttons)",
        Some(&list_focus),
    ));
    lines.extend(help_item_dyn(
        "Toggle Encryption from focused button",
        Some("Enter/Space"),
    ));
    lines.extend(help_item_dyn("Open help", Some(&list_help)));
    lines.extend(help_item_dyn("Quit app", Some(&list_quit)));
    lines.extend(help_item_dyn(
        "New note from template",
        Some(&list_template),
    ));
    lines.push(Line::from(""));

    lines.push(help_heading("󰷈", "Editor"));
    lines.extend(help_item_dyn(
        "Change focus (Title, Content, toggles)",
        Some(&edit_focus),
    ));
    lines.extend(help_item_dyn(
        "Return to notes (continually auto-saved)",
        Some(&edit_back),
    ));
    lines.extend(help_item_dyn("Save and quit", Some(&edit_quit)));
    lines.extend(help_item_dyn(
        "Copy / Cut / Paste",
        Some(&format!("{edit_copy} / {edit_cut} / {edit_paste}")),
    ));
    lines.extend(help_item_dyn(
        "Select all / Undo / Redo",
        Some(&format!("{edit_select_all} / {edit_undo} / {edit_redo}")),
    ));
    lines.extend(help_item_dyn(
        "Delete prev/next word",
        Some(&format!("{edit_del_word} / {edit_del_next_word}")),
    ));
    lines.push(Line::from(""));

    lines.push(help_heading("󰑃", "Templates"));
    lines.extend(help_item_dyn(
        "New note from template (in notes view)",
        Some(&list_template),
    ));
    lines.extend(help_item_dyn("Cancel template selection", Some("Esc")));
    lines.push(Line::from(""));

    lines.push(help_heading("󰞋", "Help Page"));
    lines.extend(help_item_dyn("Close help", Some(&help_close)));
    lines.extend(help_item_dyn("Scroll", Some(&help_scroll)));
    lines.push(Line::from(""));

    lines.push(help_heading("󰒓", "Configuration"));
    lines.extend(help_item_dyn(
        "Keybinds file: ~/.config/clin/keybinds.toml",
        None,
    ));
    lines.extend(help_item_dyn("Templates dir: <storage>/templates/", None));
    lines.extend(help_item_dyn("Run 'clin --help' for CLI commands", None));

    Text::from(lines)
}

pub fn help_heading(icon: &'static str, title: &'static str) -> Line<'static> {
    Line::from(vec![
        Span::styled(
            format!("{} ", icon),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            title,
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        ),
    ])
}

fn format_keybind(key: &str) -> String {
    let parts: Vec<_> = key
        .split(" / ")
        .map(|group| {
            group
                .split('/')
                .map(|k| format!("<{}>", k))
                .collect::<Vec<_>>()
                .join("/")
        })
        .collect();
    parts.join(" / ")
}

pub fn help_item_dyn(text: &str, key: Option<&str>) -> Vec<Line<'static>> {
    match key {
        Some(key) => {
            let formatted_key = format_keybind(key);
            vec![
                Line::from(vec![
                    Span::raw("  "),
                    Span::styled(
                        formatted_key,
                        Style::default()
                            .fg(Color::Green)
                            .add_modifier(Modifier::BOLD),
                    ),
                ]),
                Line::from(vec![
                    Span::styled("", Style::default().fg(Color::DarkGray)),
                    Span::raw(text.to_owned()),
                ]),
            ]
        }
        None => vec![Line::from(vec![
            Span::styled("", Style::default().fg(Color::DarkGray)),
            Span::raw(text.to_owned()),
        ])],
    }
}

pub fn draw_list_view(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(5),
            Constraint::Length(3),
        ])
        .split(area);

    let header = Paragraph::new(Line::from(vec![
        Span::styled(
            "clin",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw("  encrypted terminal notes"),
    ]))
    .block(Block::default().borders(Borders::ALL).title("Notes"));
    frame.render_widget(header, chunks[0]);

    let mut items: Vec<ListItem> = Vec::with_capacity(app.visual_list.len());

    for item in &app.visual_list {
        match item {
            crate::app::VisualItem::Folder {
                path: _,
                name,
                depth,
                is_expanded,
                note_count,
            } => {
                let indent = "  ".repeat(*depth);
                let icon = if *is_expanded { " " } else { " " };
                let sanitized_name = crate::sanitize::sanitize_for_terminal(name);
                let text = format!("{indent}{icon} {sanitized_name} ({note_count})");
                items.push(ListItem::new(Line::from(vec![Span::styled(
                    text,
                    Style::default()
                        .add_modifier(Modifier::BOLD)
                        .fg(Color::Blue),
                )])));
            }
            crate::app::VisualItem::Note {
                summary_idx,
                depth,
                is_clin,
                ..
            } => {
                let summary = &app.notes[*summary_idx];
                let indent = "  ".repeat(*depth);

                let when = format_relative_time(summary.updated_at);
                let mut text_style = Style::default();

                let mut spans = Vec::new();
                spans.push(Span::raw(indent));
                spans.push(Span::raw(""));

                if !is_clin {
                    spans.push(Span::styled(
                        "[UENC] ",
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    ));
                } else if !app.encryption_enabled {
                    text_style = text_style.fg(Color::Red);
                    spans.push(Span::styled("[ENC] ", text_style));
                }

                let sanitized_title =
                    crate::sanitize::sanitize_for_terminal(summary.title.as_str());
                spans.push(Span::styled(sanitized_title, text_style));

                // Tag badges
                for tag in &summary.tags {
                    spans.push(Span::raw(" "));
                    let sanitized_tag = crate::sanitize::sanitize_for_terminal(tag);
                    spans.push(Span::styled(
                        format!("[{}]", sanitized_tag),
                        Style::default().fg(Color::LightMagenta),
                    ));
                }

                spans.push(Span::raw(format!("  ({when})")));
                items.push(ListItem::new(Line::from(spans)));
            }
            crate::app::VisualItem::CreateNew { depth, .. } => {
                let indent = "  ".repeat(*depth);
                let text = format!("{indent}  Create new note");
                items.push(ListItem::new(Line::from(vec![Span::styled(
                    text,
                    Style::default().fg(Color::Green),
                )])));
            }
        }
    }

    let list = List::new(items)
        .block(Block::default().borders(Borders::ALL).title("Select"))
        .highlight_style(
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("  > ");

    app.list_state.select(Some(app.visual_index));
    frame.render_stateful_widget(list, chunks[1], &mut app.list_state);

    let enc_button_label = if app.encryption_enabled {
        "[ Enc: ON ]"
    } else {
        "[ Enc: OFF ]"
    };
    let enc_button_style = if app.list_focus == ListFocus::EncryptionToggle {
        Style::default()
            .fg(Color::Black)
            .bg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else if app.encryption_enabled {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    };

    let ext_button_label = if app.external_editor_enabled {
        "[ Ext: ON ]"
    } else {
        "[ Ext: OFF ]"
    };
    let ext_button_style = if app.list_focus == ListFocus::ExternalEditorToggle {
        Style::default()
            .fg(Color::Black)
            .bg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else if app.external_editor_enabled {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    };

    let footer_line = Line::from(vec![
        Span::styled(enc_button_label, enc_button_style),
        Span::raw(" "),
        Span::styled(ext_button_label, ext_button_style),
        Span::raw("   "),
        Span::raw(crate::sanitize::sanitize_for_terminal(app.status.as_ref())),
    ]);

    let footer =
        Paragraph::new(footer_line).block(Block::default().borders(Borders::ALL).title("Help"));
    frame.render_widget(footer, chunks[2]);

    // Draw template popup if open
    if let Some(popup) = &app.template_popup {
        draw_template_popup(frame, popup, area);
    }

    if let Some(popup) = &mut app.folder_popup {
        let popup_area = centered_rect(50, 20, area);
        frame.render_widget(Clear, popup_area);
        frame.render_widget(&popup.input, popup_area);
    }

    if let Some(popup) = &mut app.tag_popup {
        let popup_area = centered_rect(50, 20, area);
        frame.render_widget(Clear, popup_area);
        frame.render_widget(&popup.input, popup_area);
    }

    if let Some(popup) = &mut app.filter_popup {
        let popup_area = centered_rect(50, 20, area);
        frame.render_widget(Clear, popup_area);
        frame.render_widget(&*popup, popup_area);
    }

    if let Some(picker) = &app.folder_picker {
        let popup_area = centered_rect(40, 60, area);
        frame.render_widget(Clear, popup_area);

        let items: Vec<ListItem> = picker
            .folders
            .iter()
            .map(|f| {
                let label = if f.is_empty() { "Vault (Root)" } else { f };
                ListItem::new(label)
            })
            .collect();

        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title("Select Folder to Move to"),
            )
            .highlight_style(
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("> ");

        let mut state = ListState::default();
        state.select(Some(picker.selected));

        frame.render_stateful_widget(list, popup_area, &mut state);
    }

    if let Some(palette) = &mut app.command_palette {
        let palette_area = centered_rect(60, 60, area);
        frame.render_widget(Clear, palette_area);

        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(0)])
            .split(palette_area);

        frame.render_widget(&palette.input, chunks[0]);

        let items: Vec<ListItem> = palette
            .items
            .iter()
            .map(|item| {
                ListItem::new(vec![
                    Line::from(Span::styled(
                        &item.name,
                        Style::default().add_modifier(Modifier::BOLD),
                    )),
                    Line::from(Span::styled(
                        &item.description,
                        Style::default().fg(Color::DarkGray),
                    )),
                ])
            })
            .collect();

        let list = ratatui::widgets::List::new(items)
            .block(Block::default().borders(Borders::ALL).title(" Commands "))
            .highlight_style(Style::default().bg(Color::DarkGray).fg(Color::White))
            .highlight_symbol(">> ");

        frame.render_stateful_widget(list, chunks[1], &mut palette.state);
    }
}

pub fn draw_template_popup(frame: &mut Frame, popup: &TemplatePopup, area: Rect) {
    // Create popup area
    let popup_area = centered_rect(60, 60, area);

    // Clear the area
    frame.render_widget(Clear, popup_area);

    // Build list items
    let items: Vec<ListItem> = popup
        .templates
        .iter()
        .map(|t| {
            ListItem::new(Line::from(vec![
                Span::styled(&t.name, Style::default().add_modifier(Modifier::BOLD)),
                Span::styled(
                    format!("  ({})", t.filename),
                    Style::default().fg(Color::DarkGray),
                ),
            ]))
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Select Template (Enter to select, Esc to cancel)")
                .border_style(Style::default().fg(Color::Yellow)),
        )
        .highlight_style(
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("> ");

    let mut state = ListState::default();
    state.select(Some(popup.selected));

    frame.render_stateful_widget(list, popup_area, &mut state);
}

pub fn draw_edit_view(frame: &mut Frame, app: &mut App, focus: EditFocus) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),
            Constraint::Min(8),
            Constraint::Length(3),
        ])
        .split(area);

    // Set block directly on app's editor to avoid clone
    let title_border = if focus == EditFocus::Title {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default()
    };
    app.title_editor.set_block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(title_border)
            .title("Title"),
    );
    frame.render_widget(&app.title_editor, chunks[0]);

    if get_title_text(&app.title_editor).is_empty() {
        let title_inner = chunks[0].inner(Margin {
            vertical: 1,
            horizontal: 1,
        });
        let placeholder = Paragraph::new(Line::from(Span::styled(
            "Untitled note",
            Style::default().fg(Color::DarkGray),
        )));
        frame.render_widget(placeholder, title_inner);
    }

    // Set block directly on app's editor to avoid clone
    let body_border = if focus == EditFocus::Body {
        Style::default().fg(Color::Yellow)
    } else {
        Style::default()
    };
    app.editor.set_block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(body_border)
            .title("Content"),
    );
    frame.render_widget(&app.editor, chunks[1]);

    let enc_button_label = if app.encryption_enabled {
        "[ Enc: ON ]"
    } else {
        "[ Enc: OFF ]"
    };
    let enc_button_style = if focus == EditFocus::EncryptionToggle {
        Style::default()
            .fg(Color::Black)
            .bg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else if app.encryption_enabled {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    };

    let ext_button_label = if app.external_editor_enabled {
        "[ Ext: ON ]"
    } else {
        "[ Ext: OFF ]"
    };
    let ext_button_style = if focus == EditFocus::ExternalEditorToggle {
        Style::default()
            .fg(Color::Black)
            .bg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else if app.external_editor_enabled {
        Style::default()
            .fg(Color::Green)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
    };

    let status_line = Line::from(vec![
        Span::styled(enc_button_label, enc_button_style),
        Span::raw(" "),
        Span::styled(ext_button_label, ext_button_style),
        Span::raw("   "),
        Span::raw(crate::sanitize::sanitize_for_terminal(app.status.as_ref())),
    ]);

    let status =
        Paragraph::new(status_line).block(Block::default().borders(Borders::ALL).title("Help"));
    frame.render_widget(status, chunks[2]);

    if app.status.starts_with("Save failed") || app.status.starts_with("Could not open") {
        let popup = centered_rect(75, 20, area);
        frame.render_widget(Clear, popup);
        let text = Paragraph::new(app.status.as_ref())
            .block(Block::default().borders(Borders::ALL).title("Error"))
            .wrap(Wrap { trim: true });
        frame.render_widget(text, popup);
    }

    if let Some(menu) = &app.context_menu {
        let items = vec![
            ListItem::new(" Copy       "),
            ListItem::new(" Cut        "),
            ListItem::new(" Paste      "),
            ListItem::new(" Select All "),
        ];
        let list = List::new(items)
            .block(Block::default().borders(Borders::ALL))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED));

        let menu_area = Rect::new(menu.x, menu.y, 14, 6);
        let mut state = ListState::default();
        state.select(Some(menu.selected));

        frame.render_widget(Clear, menu_area);
        frame.render_stateful_widget(list, menu_area, &mut state);
    }
}

pub fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);
    let horizontal = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(vertical[1]);
    horizontal[1].inner(Margin {
        vertical: 0,
        horizontal: 0,
    })
}

pub fn text_area_from_content(content: &str) -> TextArea<'static> {
    if content.is_empty() {
        TextArea::default()
    } else {
        let lines: Vec<String> = content.lines().map(ToString::to_string).collect();
        TextArea::from(lines)
    }
}

pub fn now_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| Duration::from_secs(0))
        .as_secs()
}

pub fn format_relative_time(unix_ts: u64) -> Cow<'static, str> {
    let now = now_unix_secs();
    let diff = now.saturating_sub(unix_ts);

    if diff < 60 {
        return Cow::Borrowed("just now");
    }
    if diff < 3600 {
        return Cow::Owned(format!("{}m ago", diff / 60));
    }
    if diff < 86_400 {
        return Cow::Owned(format!("{}h ago", diff / 3600));
    }

    let secs = UNIX_EPOCH + Duration::from_secs(unix_ts);
    let dt: chrono::DateTime<chrono::Local> = secs.into();
    Cow::Owned(dt.format("%Y-%m-%d %H:%M").to_string())
}

pub fn open_in_file_manager(path: &Path) -> Result<()> {
    use std::process::Stdio;

    let command = if cfg!(target_os = "linux") {
        "xdg-open"
    } else if cfg!(target_os = "macos") {
        "open"
    } else if cfg!(target_os = "windows") {
        "explorer"
    } else {
        anyhow::bail!("opening file manager is not supported on this platform")
    };

    // Suppress stdio to prevent corrupting the TUI terminal state
    Command::new(command)
        .arg(path)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .with_context(|| format!("failed to launch {command}"))?;
    Ok(())
}