frame 0.1.5

A markdown task tracker with a terminal UI for humans and a CLI for agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::tui::app::{App, EditTarget, Mode};
use crate::tui::input::{multiline_selection_range, selection_cols_for_line};
use crate::tui::wrap;
use crate::util::unicode;

use super::detail_view::wrap_styled_spans;
use super::push_highlighted_spans;

/// Maximum visible lines for the note editor / view-mode body
const MAX_NOTE_LINES: usize = 8;

/// Render the inbox view
pub fn render_inbox_view(frame: &mut Frame, app: &mut App, area: Rect) {
    let inbox = match &app.project.inbox {
        Some(inbox) => inbox,
        None => {
            let empty = Paragraph::new(" No inbox")
                .style(Style::default().fg(app.theme.dim).bg(app.theme.background));
            frame.render_widget(empty, area);
            return;
        }
    };

    if inbox.items.is_empty() {
        let empty = Paragraph::new(" Inbox is empty")
            .style(Style::default().fg(app.theme.dim).bg(app.theme.background));
        frame.render_widget(empty, area);
        return;
    }

    // Clamp cursor
    let item_count = inbox.items.len();
    let cursor = app.inbox_cursor.min(item_count.saturating_sub(1));
    app.inbox_cursor = cursor;
    let visible_height = area.height as usize;

    let search_re = app.active_search_re();

    // Determine if we're editing a note for the cursor item
    let editing_note_for =
        if app.mode == Mode::Edit && app.edit_target.is_none() && app.inbox_note_index.is_some() {
            app.inbox_note_index
        } else {
            None
        };

    // Snapshot item data to avoid borrow conflict with mutable app borrow in editor
    let items_snapshot: Vec<_> = inbox
        .items
        .iter()
        .map(|item| (item.title.clone(), item.tags.clone(), item.body.clone()))
        .collect();

    // Build all display lines with their item indices
    let mut display_lines: Vec<(Option<usize>, Line)> = Vec::new();

    // Track the editor cursor line (for scroll adjustment)
    let mut editor_active_line: Option<usize> = None;

    for (i, (title, tags, body)) in items_snapshot.iter().enumerate() {
        let is_cursor = i == cursor;
        let bg = if is_cursor {
            app.theme.selection_bg
        } else {
            app.theme.background
        };

        // Blank line before each item (except first)
        if i > 0 {
            display_lines.push((None, Line::from("")));
        }

        // Number + title + tags
        let mut spans: Vec<Span> = Vec::new();

        // Column 0 reservation
        if is_cursor {
            spans.push(Span::styled(
                "\u{258E}",
                Style::default()
                    .fg(app.theme.selection_border)
                    .bg(app.theme.selection_bg),
            ));
        } else {
            spans.push(Span::styled(" ", Style::default().bg(app.theme.background)));
        }

        let num_style = Style::default().fg(app.theme.dim).bg(bg);
        spans.push(Span::styled(format!("{:>2}  ", i + 1), num_style));

        // Check if we're editing this item's title or tags
        let editing_title = is_cursor
            && app.mode == Mode::Edit
            && matches!(
                &app.edit_target,
                Some(EditTarget::NewInboxItem { .. }) | Some(EditTarget::ExistingInboxTitle { .. })
            );
        let editing_tags = is_cursor
            && app.mode == Mode::Edit
            && matches!(&app.edit_target, Some(EditTarget::ExistingInboxTags { .. }));

        if editing_title {
            // Wrap-aware title editing
            let prefix_width: usize = 5; // cursor indicator (1) + number column (4)
            let edit_available = (area.width as usize).saturating_sub(prefix_width);
            let cursor_pos = app.edit_cursor.min(app.edit_buffer.len());

            if edit_available > 0 {
                let edit_text = [app.edit_buffer.as_str()];
                let visual_lines =
                    wrap::wrap_lines_for_edit(&edit_text, edit_available, 0, cursor_pos);
                let total_visual = visual_lines.len();
                let visible_visual = total_visual.clamp(1, MAX_NOTE_LINES);
                let cursor_vrow = wrap::logical_to_visual_row(&visual_lines, 0, cursor_pos);

                // Scroll to keep cursor visible
                let mut title_scroll = 0usize;
                if cursor_vrow >= visible_visual {
                    title_scroll = cursor_vrow.saturating_sub(visible_visual - 1);
                }

                let edit_style = Style::default()
                    .fg(app.theme.text_bright)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD);
                let cursor_block_style = Style::default()
                    .fg(app.theme.background)
                    .bg(app.theme.text_bright);

                for view_row in 0..visible_visual {
                    let vrow_idx = title_scroll + view_row;
                    if vrow_idx >= total_visual {
                        break;
                    }
                    let vl = &visual_lines[vrow_idx];
                    let slice = &app.edit_buffer[vl.byte_start..vl.byte_end];
                    let has_cursor = vrow_idx == cursor_vrow;

                    if has_cursor {
                        editor_active_line = Some(display_lines.len());
                    }

                    let mut line_spans: Vec<Span> = Vec::new();

                    if view_row == 0 {
                        // First visual line: reuse existing prefix spans
                        line_spans.append(&mut spans);
                    } else {
                        // Continuation lines: indent to match prefix
                        line_spans.push(Span::styled(
                            " ".repeat(prefix_width),
                            Style::default().bg(bg),
                        ));
                    }

                    // Render text with cursor
                    let graphemes: Vec<(usize, &str)> =
                        unicode_segmentation::UnicodeSegmentation::grapheme_indices(slice, true)
                            .collect();

                    if has_cursor {
                        let cursor_byte_in_row =
                            cursor_pos.min(vl.byte_end).saturating_sub(vl.byte_start);
                        let mut cursor_rendered = false;
                        for &(gi, g) in &graphemes {
                            if gi == cursor_byte_in_row && !cursor_rendered {
                                line_spans.push(Span::styled(g.to_string(), cursor_block_style));
                                cursor_rendered = true;
                            } else {
                                line_spans.push(Span::styled(g.to_string(), edit_style));
                            }
                        }
                        if !cursor_rendered {
                            line_spans.push(Span::styled(" ", cursor_block_style));
                        }
                    } else if !slice.is_empty() {
                        line_spans.push(Span::styled(slice.to_string(), edit_style));
                    }

                    // Pad to full width
                    let content_width: usize = line_spans
                        .iter()
                        .map(|s| unicode::display_width(&s.content))
                        .sum();
                    let w = area.width as usize;
                    if content_width < w {
                        line_spans.push(Span::styled(
                            " ".repeat(w - content_width),
                            Style::default().bg(bg),
                        ));
                    }

                    display_lines.push((Some(i), Line::from(line_spans)));
                }

                // Scroll indicator
                if total_visual > visible_visual {
                    let dim_style = Style::default().fg(app.theme.dim).bg(app.theme.background);
                    let indicator = format!(
                        "{}[{}/{}]",
                        " ".repeat(prefix_width),
                        title_scroll + visible_visual,
                        total_visual,
                    );
                    display_lines.push((Some(i), Line::from(Span::styled(indicator, dim_style))));
                }
            } else {
                display_lines.push((Some(i), Line::from(spans)));
            }
        } else {
            // View mode: title + tags, wrapped
            let title_style = if is_cursor {
                Style::default()
                    .fg(app.theme.text_bright)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(app.theme.text_bright).bg(bg)
            };
            let hl_style = Style::default()
                .fg(app.theme.search_match_fg)
                .bg(app.theme.search_match_bg)
                .add_modifier(Modifier::BOLD);
            push_highlighted_spans(&mut spans, title, title_style, hl_style, search_re.as_ref());

            // Tags
            if editing_tags {
                spans.push(Span::styled("  ", Style::default().bg(bg)));
                let cursor_pos = app.edit_cursor.min(app.edit_buffer.len());
                let before = &app.edit_buffer[..cursor_pos];
                let after = &app.edit_buffer[cursor_pos..];
                let edit_style = Style::default().fg(app.theme.highlight).bg(bg);
                spans.push(Span::styled(before.to_string(), edit_style));
                spans.push(Span::styled(
                    "\u{258C}",
                    Style::default().fg(app.theme.highlight).bg(bg),
                ));
                if !after.is_empty() {
                    spans.push(Span::styled(after.to_string(), edit_style));
                }
            } else if !tags.is_empty() {
                spans.push(Span::styled("  ", Style::default().bg(bg)));
                let tag_hl_style = Style::default()
                    .fg(app.theme.search_match_fg)
                    .bg(app.theme.search_match_bg)
                    .add_modifier(Modifier::BOLD);
                for (j, tag) in tags.iter().enumerate() {
                    if j > 0 {
                        spans.push(Span::styled(" ", Style::default().bg(bg)));
                    }
                    let tag_color = app.theme.tag_color(tag);
                    let tag_style = Style::default().fg(tag_color).bg(bg);
                    push_highlighted_spans(
                        &mut spans,
                        &format!("#{}", tag),
                        tag_style,
                        tag_hl_style,
                        search_re.as_ref(),
                    );
                }
            }

            // Wrap and push
            let indent: usize = 5; // cursor indicator (1) + number column (4)
            let wrapped = wrap_styled_spans(spans, area.width as usize, indent, bg);
            for mut wrapped_line in wrapped {
                if is_cursor {
                    let content_width: usize = wrapped_line
                        .spans
                        .iter()
                        .map(|s| unicode::display_width(&s.content))
                        .sum();
                    let w = area.width as usize;
                    if content_width < w {
                        wrapped_line.spans.push(Span::styled(
                            " ".repeat(w - content_width),
                            Style::default().bg(bg),
                        ));
                    }
                }
                display_lines.push((Some(i), wrapped_line));
            }
        }

        // Inline note editor or body text
        if editing_note_for == Some(i) {
            // Render the multi-line note editor inline
            render_inline_note_editor(app, &mut display_lines, &mut editor_active_line, i, area);
        } else if let Some(body) = body {
            // View-mode body text
            render_body_view_mode(app, &mut display_lines, body, i, search_re.as_ref(), area);
        }
    }

    // Find the display line index of the cursor item (for autocomplete anchor + scroll)
    let mut cursor_display_line: Option<usize> = None;
    for (dl_idx, (item_idx, _)) in display_lines.iter().enumerate() {
        if *item_idx == Some(cursor) && cursor_display_line.is_none() {
            cursor_display_line = Some(dl_idx);
        }
    }

    // Auto-adjust scroll to keep cursor visible
    let mut scroll = app.inbox_scroll;
    if let Some(cdl) = cursor_display_line {
        if cdl < scroll {
            scroll = cdl;
        } else if cdl >= scroll + visible_height {
            scroll = cdl.saturating_sub(visible_height - 1);
        }
    }

    // When editing a note, ensure the editor's active line (cursor line) is visible
    if let Some(active) = editor_active_line {
        if active >= scroll + visible_height {
            scroll = active.saturating_sub(visible_height - 1);
        }
        // Also ensure the header (cursor item line) stays visible
        if let Some(cdl) = cursor_display_line
            && cdl < scroll
        {
            // Header scrolled off top — pull scroll back so header is row 0
            scroll = cdl;
        }
    }

    app.inbox_scroll = scroll;

    // Set autocomplete anchor if editing tags or in triage mode
    let needs_anchor = (app.mode == Mode::Edit
        && matches!(&app.edit_target, Some(EditTarget::ExistingInboxTags { .. })))
        || app.mode == Mode::Triage;
    if needs_anchor && let Some(dl) = cursor_display_line {
        let screen_line = dl.saturating_sub(scroll);
        let screen_y = area.y + screen_line as u16;
        // Anchor x: after the number prefix (col 5 roughly)
        let screen_x = area.x + 5;
        app.autocomplete_anchor = Some((screen_x, screen_y));
    }

    // Apply scroll and collect visible lines
    let lines: Vec<Line> = display_lines
        .into_iter()
        .skip(scroll)
        .take(visible_height)
        .map(|(_, line)| line)
        .collect();

    let paragraph = Paragraph::new(lines).style(Style::default().bg(app.theme.background));
    frame.render_widget(paragraph, area);
}

/// Render body text in view mode with optional line numbers (>= 4 lines)
/// and capped at MAX_NOTE_LINES with a "N more lines" indicator.
fn render_body_view_mode(
    app: &App,
    display_lines: &mut Vec<(Option<usize>, Line)>,
    body: &str,
    item_index: usize,
    search_re: Option<&regex::Regex>,
    area: Rect,
) {
    let body_lines: Vec<&str> = body.lines().collect();
    let line_count = body_lines.len();
    let truncated = line_count > MAX_NOTE_LINES;
    let visible_count = if truncated {
        MAX_NOTE_LINES
    } else {
        line_count
    };

    let body_style = Style::default().fg(app.theme.text).bg(app.theme.background);
    let body_hl_style = Style::default()
        .fg(app.theme.search_match_fg)
        .bg(app.theme.search_match_bg)
        .add_modifier(Modifier::BOLD);
    let dim_style = Style::default().fg(app.theme.dim).bg(app.theme.background);
    let indent = "      ";
    let indent_len = indent.len();
    let content_width = (area.width as usize).saturating_sub(indent_len);

    let mut visual_lines_rendered = 0;
    for body_line in body_lines.iter().take(visible_count) {
        let mut content_spans: Vec<Span> = Vec::new();
        push_highlighted_spans(
            &mut content_spans,
            body_line,
            body_style,
            body_hl_style,
            search_re,
        );

        let wrapped = wrap_styled_spans(content_spans, content_width, 0, app.theme.background);
        for wrapped_line in wrapped {
            let indent_span = Span::styled(
                indent.to_string(),
                Style::default().bg(app.theme.background),
            );
            let mut line_spans = vec![indent_span];
            line_spans.extend(wrapped_line.spans);
            display_lines.push((Some(item_index), Line::from(line_spans)));
            visual_lines_rendered += 1;
        }
    }
    let _ = visual_lines_rendered;

    if truncated {
        let remaining = line_count - MAX_NOTE_LINES;
        let indicator = format!(
            "{}{} more line{}",
            indent,
            remaining,
            if remaining == 1 { "" } else { "s" }
        );
        display_lines.push((
            Some(item_index),
            Line::from(Span::styled(indicator, dim_style)),
        ));
    }
}

/// Render the inline multi-line note editor below the selected inbox item.
fn render_inline_note_editor(
    app: &mut App,
    display_lines: &mut Vec<(Option<usize>, Line)>,
    editor_active_line: &mut Option<usize>,
    item_index: usize,
    area: Rect,
) {
    let ds = match &app.detail_state {
        Some(ds) => ds,
        None => return,
    };

    let edit_lines: Vec<&str> = ds.edit_buffer.split('\n').collect();
    let total_lines = edit_lines.len();
    let visible_lines = total_lines.clamp(1, MAX_NOTE_LINES);

    // Auto-adjust editor scroll to keep cursor line visible
    let cursor_line = ds.edit_cursor_line;
    let mut editor_scroll = app.inbox_note_editor_scroll;
    // Clamp scroll so the editor always fills its visible_lines window
    let max_scroll = total_lines.saturating_sub(visible_lines);
    editor_scroll = editor_scroll.min(max_scroll);
    if cursor_line < editor_scroll {
        editor_scroll = cursor_line;
    } else if cursor_line >= editor_scroll + visible_lines {
        editor_scroll = cursor_line.saturating_sub(visible_lines - 1);
    }
    app.inbox_note_editor_scroll = editor_scroll;

    // Compute gutter width from total line count
    let gutter_width = wrap::gutter_width(total_lines);
    let num_display_width = gutter_width - 1;

    // Available width for note content (gutter eats into base indent)
    const BASE_INDENT: usize = 6;
    let indent_width = BASE_INDENT.saturating_sub(gutter_width);
    let note_available = (area.width as usize).saturating_sub(BASE_INDENT);

    app.last_edit_available_width = note_available as u16;
    let cursor_col = ds.edit_cursor_col;
    let bright_style = Style::default()
        .fg(app.theme.text_bright)
        .bg(app.theme.background);
    let text_style = Style::default().fg(app.theme.text).bg(app.theme.background);
    let cursor_style = Style::default()
        .fg(app.theme.background)
        .bg(app.theme.text_bright);
    let selection_style = Style::default()
        .fg(app.theme.text_bright)
        .bg(app.theme.blue);
    let dim_arrow_style = Style::default().fg(app.theme.dim).bg(app.theme.background);

    // Compute selection range
    let sel_range = multiline_selection_range(ds);

    let mut h_scroll = ds.note_h_scroll;

    if app.note_wrap && note_available > 0 {
        // --- Wrap-aware rendering ---
        let visual_lines =
            wrap::wrap_lines_for_edit(&edit_lines, note_available, cursor_line, cursor_col);
        let total_visual = visual_lines.len();
        let visible_visual = total_visual.clamp(1, MAX_NOTE_LINES);

        let cursor_vrow = wrap::logical_to_visual_row(&visual_lines, cursor_line, cursor_col);

        // Scroll to keep cursor visual row visible
        let max_vscroll = total_visual.saturating_sub(visible_visual);
        editor_scroll = editor_scroll.min(max_vscroll);
        if cursor_vrow < editor_scroll {
            editor_scroll = cursor_vrow;
        } else if cursor_vrow >= editor_scroll + visible_visual {
            editor_scroll = cursor_vrow.saturating_sub(visible_visual - 1);
        }
        app.inbox_note_editor_scroll = editor_scroll;

        for view_row in 0..visible_visual {
            let vrow_idx = editor_scroll + view_row;
            if vrow_idx >= total_visual {
                break;
            }
            let vl = &visual_lines[vrow_idx];
            let line_text = edit_lines.get(vl.logical_line).copied().unwrap_or("");
            let slice = &line_text[vl.byte_start..vl.byte_end];
            let graphemes: Vec<(usize, &str)> =
                unicode_segmentation::UnicodeSegmentation::grapheme_indices(slice, true).collect();

            let has_cursor = vrow_idx == cursor_vrow;
            if has_cursor {
                *editor_active_line = Some(display_lines.len());
            }

            let mut spans: Vec<Span> = Vec::new();
            if indent_width > 0 {
                spans.push(Span::styled(
                    " ".repeat(indent_width),
                    Style::default().bg(app.theme.background),
                ));
            }

            // Gutter
            if vl.is_first {
                let num_str = format!(
                    "{:>width$} ",
                    vl.logical_line + 1,
                    width = num_display_width,
                );
                spans.push(Span::styled(num_str, text_style));
            } else {
                spans.push(Span::styled(
                    " ".repeat(gutter_width),
                    Style::default().bg(app.theme.background),
                ));
            }

            let vl_sel = sel_range
                .and_then(|(s, e)| selection_cols_for_line(&ds.edit_buffer, s, e, vl.logical_line));

            let cursor_byte_in_row = if has_cursor {
                Some(cursor_col.saturating_sub(vl.char_start))
            } else {
                None
            };

            if let Some((sc, ec)) = vl_sel {
                for &(gi, g) in &graphemes {
                    let abs_byte = vl.byte_start + gi;
                    let s = if abs_byte >= sc && abs_byte < ec {
                        selection_style
                    } else {
                        bright_style
                    };
                    if cursor_byte_in_row == Some(gi) {
                        spans.push(Span::styled(g.to_string(), cursor_style));
                    } else {
                        spans.push(Span::styled(g.to_string(), s));
                    }
                }
                if sc == ec && graphemes.is_empty() && !has_cursor {
                    spans.push(Span::styled(" ", selection_style));
                }
                if has_cursor && cursor_col >= vl.char_end {
                    spans.push(Span::styled(" ", cursor_style));
                }
            } else if has_cursor {
                let byte_in_row = cursor_col.min(vl.char_end).saturating_sub(vl.char_start);
                for &(gi, g) in &graphemes {
                    if gi == byte_in_row {
                        spans.push(Span::styled(g.to_string(), cursor_style));
                    } else {
                        spans.push(Span::styled(g.to_string(), bright_style));
                    }
                }
                if byte_in_row >= slice.len() {
                    spans.push(Span::styled(" ", cursor_style));
                }
            } else if !slice.is_empty() {
                spans.push(Span::styled(slice.to_string(), bright_style));
            }

            display_lines.push((Some(item_index), Line::from(spans)));
        }

        // Scroll indicator
        if total_visual > visible_visual {
            let dim_style = Style::default().fg(app.theme.dim).bg(app.theme.background);
            let indicator = format!(
                "{}[{}/{}]",
                " ".repeat(BASE_INDENT),
                editor_scroll + visible_visual,
                total_visual
            );
            display_lines.push((
                Some(item_index),
                Line::from(Span::styled(indicator, dim_style)),
            ));
        }
    } else {
        // --- Original horizontal-scroll rendering ---
        if note_available > 0 {
            let margin = 10.min(note_available / 3);
            let cursor_line_len = edit_lines.get(cursor_line).map_or(0, |l| l.len());
            let content_end = if cursor_col >= cursor_line_len {
                cursor_line_len + 1
            } else {
                cursor_line_len
            };
            if cursor_col >= h_scroll + note_available.saturating_sub(margin) {
                h_scroll = cursor_col.saturating_sub(note_available.saturating_sub(margin + 1));
            }
            h_scroll = h_scroll.min(content_end.saturating_sub(note_available.saturating_sub(1)));
            if cursor_col < h_scroll + margin {
                h_scroll = cursor_col.saturating_sub(margin);
            }
        }

        for view_row in 0..visible_lines {
            let line_idx = editor_scroll + view_row;
            if line_idx >= total_lines {
                break;
            }
            let edit_line = edit_lines[line_idx];
            let has_cursor = line_idx == cursor_line;

            if has_cursor {
                *editor_active_line = Some(display_lines.len());
            }

            let mut spans: Vec<Span> = Vec::new();
            if indent_width > 0 {
                spans.push(Span::styled(
                    " ".repeat(indent_width),
                    Style::default().bg(app.theme.background),
                ));
            }

            let graphemes: Vec<(usize, &str)> =
                unicode_segmentation::UnicodeSegmentation::grapheme_indices(edit_line, true)
                    .collect();
            let total_graphemes = graphemes.len();
            let clipped_left = h_scroll > 0 && total_graphemes > 0;
            let left_indicator = if clipped_left { 1 } else { 0 };
            let avail_after_left = note_available.saturating_sub(left_indicator);
            let clipped_right = h_scroll + avail_after_left < total_graphemes;
            let right_indicator = if clipped_right { 1 } else { 0 };
            let view_count = avail_after_left.saturating_sub(right_indicator);
            let view_start = h_scroll.min(total_graphemes);
            let view_end = (view_start + view_count).min(total_graphemes);

            let line_num_str = format!("{:>width$}", line_idx + 1, width = num_display_width);
            if clipped_left {
                spans.push(Span::styled(line_num_str, text_style));
                spans.push(Span::styled("\u{25C2}", dim_arrow_style)); //            } else {
                spans.push(Span::styled(format!("{} ", line_num_str), text_style));
            }

            let line_sel = sel_range
                .and_then(|(s, e)| selection_cols_for_line(&ds.edit_buffer, s, e, line_idx));

            // Convert cursor byte offset to grapheme index
            let cursor_gi = graphemes
                .iter()
                .position(|&(bo, _)| bo >= cursor_col)
                .unwrap_or(total_graphemes);

            if let Some((sc, ec)) = line_sel {
                for (gi, &(bo, g)) in graphemes
                    .iter()
                    .enumerate()
                    .skip(view_start)
                    .take(view_end - view_start)
                {
                    let s = if bo >= sc && bo < ec {
                        selection_style
                    } else {
                        bright_style
                    };
                    if has_cursor && gi == cursor_gi {
                        spans.push(Span::styled(g.to_string(), cursor_style));
                    } else {
                        spans.push(Span::styled(g.to_string(), s));
                    }
                }
                if sc == ec && total_graphemes == 0 && !has_cursor {
                    spans.push(Span::styled(" ", selection_style));
                }
                if has_cursor && cursor_gi >= total_graphemes && cursor_gi >= view_start {
                    spans.push(Span::styled(" ", cursor_style));
                }
            } else if has_cursor {
                let col_gi = cursor_gi.min(total_graphemes);
                for (gi, &(_bo, g)) in graphemes
                    .iter()
                    .enumerate()
                    .skip(view_start)
                    .take(view_end - view_start)
                {
                    if gi == col_gi {
                        spans.push(Span::styled(g.to_string(), cursor_style));
                    } else {
                        spans.push(Span::styled(g.to_string(), bright_style));
                    }
                }
                if col_gi >= total_graphemes && col_gi >= view_start {
                    spans.push(Span::styled(" ", cursor_style));
                }
            } else if view_start < view_end {
                let slice: String = graphemes[view_start..view_end]
                    .iter()
                    .map(|g| g.1)
                    .collect();
                spans.push(Span::styled(slice, bright_style));
            }

            if clipped_right {
                spans.push(Span::styled("\u{25B8}", dim_arrow_style)); //            }

            display_lines.push((Some(item_index), Line::from(spans)));
        }

        // Scroll indicator
        if total_lines > visible_lines {
            let dim_style = Style::default().fg(app.theme.dim).bg(app.theme.background);
            let indicator = format!(
                "{}[{}/{}]",
                " ".repeat(BASE_INDENT),
                editor_scroll + visible_lines,
                total_lines
            );
            display_lines.push((
                Some(item_index),
                Line::from(Span::styled(indicator, dim_style)),
            ));
        }
    }

    // Write back adjusted h_scroll
    if let Some(ds_mut) = app.detail_state.as_mut() {
        ds_mut.note_h_scroll = h_scroll;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::render::test_helpers::*;
    use insta::assert_snapshot;

    #[test]
    fn inbox_with_items() {
        let mut app = app_with_inbox(INBOX_MD);
        app.view = crate::tui::app::View::Inbox;
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_inbox_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn inbox_empty() {
        let mut app = app_with_inbox(EMPTY_INBOX_MD);
        app.view = crate::tui::app::View::Inbox;
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_inbox_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn inbox_in_edit_mode() {
        let mut app = app_with_inbox(INBOX_MD);
        app.view = crate::tui::app::View::Inbox;
        app.mode = Mode::Edit;
        app.edit_target = Some(EditTarget::NewInboxItem { index: 0 });
        app.edit_buffer = "New item text".into();
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_inbox_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }
}