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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::ops::track_ops::task_counts;
use crate::tui::app::{App, EditTarget, Mode};
use crate::util::unicode;

use super::push_highlighted_spans;

/// Width of each stat column (right-aligned numbers)
const COL_W: usize = 5;

/// Column headers (short names) and their markdown checkbox representations
const HEADERS: [&str; 5] = ["todo", "act", "blk", "done", "park"];
const CHECKBOXES: [&str; 5] = ["[ ]", "[>]", "[-]", "[x]", "[~]"];

/// Render the tracks overview as a grid with state columns
pub fn render_tracks_view(frame: &mut Frame, app: &mut App, area: Rect) {
    let mut lines: Vec<Line> = Vec::new();
    let cursor = app.tracks_cursor;

    // Group tracks by state
    let mut active_tracks = Vec::new();
    let mut shelved_tracks = Vec::new();
    let mut archived_tracks = Vec::new();

    for tc in &app.project.config.tracks {
        match tc.state.as_str() {
            "active" => active_tracks.push(tc),
            "shelved" => shelved_tracks.push(tc),
            "archived" => archived_tracks.push(tc),
            _ => {}
        }
    }

    let cc_focus = app.project.config.agent.cc_focus.as_deref();
    let search_re = app.active_search_re();

    // Calculate name column width from longest track name
    let total_tracks = active_tracks.len() + shelved_tracks.len() + archived_tracks.len();
    let num_width = if total_tracks >= 10 { 2 } else { 1 };
    let computed_name_len = app
        .project
        .config
        .tracks
        .iter()
        .map(|tc| unicode::display_width(&tc.name))
        .max()
        .unwrap_or(10);
    // Columns can grow but not shrink within a single Tracks view session
    let max_name_len = computed_name_len.max(app.tracks_name_col_min);
    app.tracks_name_col_min = max_name_len;
    let max_id_len = app
        .project
        .config
        .tracks
        .iter()
        .map(|tc| {
            app.project
                .config
                .ids
                .prefixes
                .get(&tc.id)
                .map(|p| unicode::display_width(p))
                .unwrap_or_else(|| unicode::display_width(&tc.id))
        })
        .max()
        .unwrap_or(2);

    // name_col = total width before stat columns in data rows:
    // border(1) + num + "  " + name + "  " + id
    let name_col = 1 + num_width + 2 + max_name_len + 2 + max_id_len;

    // Project name header
    lines.push(Line::from(Span::styled(
        format!(" Project: {}", app.project.config.project.name),
        Style::default()
            .fg(app.theme.text)
            .bg(app.theme.background)
            .add_modifier(Modifier::BOLD),
    )));

    // Top header: short state names aligned to stat columns
    lines.push(render_col_names(app, name_col, max_id_len));

    let mut flat_idx = 0usize;

    // Detect inline edit state
    let editing_track_id = match (&app.mode, &app.edit_target) {
        (Mode::Edit, Some(EditTarget::ExistingTrackName { track_id, .. })) => {
            Some(track_id.clone())
        }
        _ => None,
    };
    let is_new_track_edit = matches!(
        (&app.mode, &app.edit_target),
        (Mode::Edit, Some(EditTarget::NewTrackName))
    );
    let editing_prefix_track_id = match (&app.mode, &app.edit_target) {
        (Mode::Edit, Some(EditTarget::ExistingPrefix { track_id, .. })) => Some(track_id.clone()),
        _ => None,
    };

    // Active section
    if !active_tracks.is_empty() || is_new_track_edit {
        lines.push(render_section_row(app, "Active", name_col, false));
        for (track_i, tc) in active_tracks.iter().enumerate() {
            // Insert new-track edit row before this track when cursor == track_i
            if is_new_track_edit && flat_idx == cursor && track_i == cursor {
                lines.push(render_new_track_edit_row(
                    app,
                    flat_idx + 1,
                    num_width,
                    area.width,
                ));
                flat_idx += 1;
            }
            let is_cursor = flat_idx == cursor;
            let is_flash = app.is_track_flashing(&tc.id);
            if editing_track_id.as_deref() == Some(&tc.id) && is_cursor {
                lines.push(render_edit_row(
                    app,
                    tc,
                    flat_idx + 1,
                    num_width,
                    max_name_len,
                    max_id_len,
                    cc_focus,
                    area.width,
                ));
            } else {
                lines.push(render_track_row(
                    app,
                    tc,
                    flat_idx + 1,
                    num_width,
                    max_name_len,
                    max_id_len,
                    is_cursor,
                    is_flash,
                    cc_focus,
                    area.width,
                    search_re.as_ref(),
                ));
            }
            // Prefix edit row below the track
            if editing_prefix_track_id.as_deref() == Some(&tc.id) && is_cursor {
                lines.push(render_prefix_edit_row(app, num_width, area.width));
            }
            flat_idx += 1;
        }
        // New track edit row at end of active section (cursor == active_count)
        if is_new_track_edit && flat_idx == cursor {
            lines.push(render_new_track_edit_row(
                app,
                flat_idx + 1,
                num_width,
                area.width,
            ));
            flat_idx += 1;
        }
        lines.push(Line::from(""));
    }

    // Shelved section
    if !shelved_tracks.is_empty() {
        lines.push(render_section_row(app, "Shelved", name_col, false));
        for tc in &shelved_tracks {
            let is_cursor = flat_idx == cursor;
            let is_flash = app.is_track_flashing(&tc.id);
            if editing_track_id.as_deref() == Some(&tc.id) && is_cursor {
                lines.push(render_edit_row(
                    app,
                    tc,
                    flat_idx + 1,
                    num_width,
                    max_name_len,
                    max_id_len,
                    cc_focus,
                    area.width,
                ));
            } else {
                lines.push(render_track_row(
                    app,
                    tc,
                    flat_idx + 1,
                    num_width,
                    max_name_len,
                    max_id_len,
                    is_cursor,
                    is_flash,
                    cc_focus,
                    area.width,
                    search_re.as_ref(),
                ));
            }
            if editing_prefix_track_id.as_deref() == Some(&tc.id) && is_cursor {
                lines.push(render_prefix_edit_row(app, num_width, area.width));
            }
            flat_idx += 1;
        }
        lines.push(Line::from(""));
    }

    // Archived section
    if !archived_tracks.is_empty() {
        lines.push(render_section_row(app, "Archived", name_col, true));
        for tc in &archived_tracks {
            let is_cursor = flat_idx == cursor;
            let is_flash = app.is_track_flashing(&tc.id);
            lines.push(render_track_row(
                app,
                tc,
                flat_idx + 1,
                num_width,
                max_name_len,
                max_id_len,
                is_cursor,
                is_flash,
                cc_focus,
                area.width,
                search_re.as_ref(),
            ));
            flat_idx += 1;
        }
    }

    if flat_idx == 0 {
        lines.clear();
        let bg = app.theme.background;
        lines.push(Line::from(vec![
            Span::styled(
                " No tracks — press ",
                Style::default().fg(app.theme.text).bg(bg),
            ),
            Span::styled("a", Style::default().fg(app.theme.highlight).bg(bg)),
            Span::styled(" to create one", Style::default().fg(app.theme.text).bg(bg)),
        ]));
    }

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

/// Render the top header line with short state names
fn render_col_names<'a>(app: &'a App, name_col: usize, max_id_len: usize) -> Line<'a> {
    let bg = app.theme.background;
    let header_style = Style::default().fg(app.theme.text).bg(bg);
    let dim_style = Style::default().fg(app.theme.dim).bg(bg);

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

    // Pad to align "id" header with ID column in data rows
    let pre_id_col = name_col - max_id_len;
    spans.push(Span::styled(
        " ".repeat(pre_id_col),
        Style::default().bg(bg),
    ));

    // "pfx" header aligned to prefix column
    spans.push(Span::styled(
        format!("{:<width$}", "pfx", width = max_id_len),
        dim_style,
    ));

    for header in &HEADERS {
        spans.push(Span::styled(
            format!("{:>width$}", header, width = COL_W),
            header_style,
        ));
    }

    Line::from(spans)
}

/// Render a section header with name + markdown checkbox sub-headers
fn render_section_row<'a>(
    app: &'a App,
    label: &'static str,
    name_col: usize,
    is_dim: bool,
) -> Line<'a> {
    let bg = app.theme.background;
    let label_color = if is_dim {
        app.theme.dim
    } else {
        app.theme.text
    };
    let label_style = Style::default()
        .fg(label_color)
        .bg(bg)
        .add_modifier(Modifier::BOLD);
    let cb_style = Style::default().fg(app.theme.text).bg(bg);

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

    // " Label" left-aligned, then pad to name_col
    let label_text = format!(" {}", label);
    let label_len = unicode::display_width(&label_text);
    spans.push(Span::styled(label_text, label_style));

    if label_len < name_col {
        spans.push(Span::styled(
            " ".repeat(name_col - label_len),
            Style::default().bg(bg),
        ));
    }

    // Checkbox representations aligned to stat columns
    for cb in &CHECKBOXES {
        spans.push(Span::styled(
            format!("{:>width$}", cb, width = COL_W),
            cb_style,
        ));
    }

    Line::from(spans)
}

/// Render a single track data row with stat counts in columns
#[allow(clippy::too_many_arguments)]
fn render_track_row<'a>(
    app: &'a App,
    tc: &crate::model::TrackConfig,
    number: usize,
    num_width: usize,
    max_name_len: usize,
    max_id_len: usize,
    is_cursor: bool,
    is_flash: bool,
    cc_focus: Option<&str>,
    width: u16,
    search_re: Option<&regex::Regex>,
) -> Line<'a> {
    let bg = if is_flash {
        app.theme.flash_bg
    } else if is_cursor {
        app.theme.selection_bg
    } else {
        app.theme.background
    };

    // Get stats for this track
    let stats = app
        .project
        .tracks
        .iter()
        .find(|(id, _)| id == &tc.id)
        .map(|(_, track)| task_counts(track))
        .unwrap_or_default();

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

    // Column 0: cursor/flash border
    if is_cursor || is_flash {
        let border_color = if is_flash {
            app.theme.yellow
        } else {
            app.theme.selection_border
        };
        spans.push(Span::styled(
            "\u{258E}",
            Style::default().fg(border_color).bg(bg),
        ));
    } else {
        spans.push(Span::styled(" ", Style::default().bg(app.theme.background)));
    }

    // Number (right-aligned in num_width)
    let num_str = format!("{:>width$}", number, width = num_width);
    spans.push(Span::styled(
        num_str,
        Style::default().fg(app.theme.dim).bg(bg),
    ));
    spans.push(Span::styled("  ", Style::default().bg(bg)));

    // Track name (with search highlighting, padded to max_name_len)
    let name_style = 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, &tc.name, name_style, hl_style, search_re);

    // Pad name to max_name_len
    let name_len = unicode::display_width(&tc.name);
    if name_len < max_name_len {
        spans.push(Span::styled(
            " ".repeat(max_name_len - name_len),
            Style::default().bg(bg),
        ));
    }

    // ID prefix column (gap + uppercase prefix padded to max_id_len)
    spans.push(Span::styled("  ", Style::default().bg(bg)));
    let id_style = Style::default().fg(app.theme.text).bg(bg);
    let prefix = app
        .project
        .config
        .ids
        .prefixes
        .get(&tc.id)
        .map(|p| p.to_uppercase())
        .unwrap_or_else(|| tc.id.to_uppercase());
    let id_text = format!("{:<width$}", prefix, width = max_id_len);
    push_highlighted_spans(&mut spans, &id_text, id_style, hl_style, search_re);

    // Stat columns: todo, active, blocked, done, parked
    let counts = [
        stats.todo,
        stats.active,
        stats.blocked,
        stats.done,
        stats.parked,
    ];
    let colors = [
        app.theme.text,      // todo
        app.theme.highlight, // active
        app.theme.red,       // blocked
        app.theme.text,      // done
        app.theme.yellow,    // parked
    ];

    for (count, color) in counts.iter().zip(colors.iter()) {
        let style = Style::default().fg(*color).bg(bg);
        spans.push(Span::styled(
            format!("{:>width$}", count, width = COL_W),
            style,
        ));
    }

    // cc-focus indicator
    if cc_focus == Some(tc.id.as_str()) {
        spans.push(Span::styled("  ", Style::default().bg(bg)));
        spans.push(Span::styled(
            "\u{2605} cc",
            Style::default().fg(app.theme.purple).bg(bg),
        ));
    }

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

    Line::from(spans)
}

/// Render an inline edit row for existing track name editing (preserves column layout)
#[allow(clippy::too_many_arguments)]
fn render_edit_row<'a>(
    app: &'a App,
    tc: &crate::model::TrackConfig,
    number: usize,
    num_width: usize,
    max_name_len: usize,
    max_id_len: usize,
    cc_focus: Option<&str>,
    width: u16,
) -> Line<'a> {
    let bg = app.theme.selection_bg;
    let mut spans: Vec<Span> = Vec::new();

    // Selection border
    spans.push(Span::styled(
        "\u{258E}",
        Style::default().fg(app.theme.selection_border).bg(bg),
    ));

    // Number
    let num_str = format!("{:>width$}", number, width = num_width);
    spans.push(Span::styled(
        num_str,
        Style::default().fg(app.theme.dim).bg(bg),
    ));
    spans.push(Span::styled("  ", Style::default().bg(bg)));

    // Edit buffer with cursor (occupies the name column)
    let cursor_pos = app.edit_cursor;
    let buffer = &app.edit_buffer;
    let text_style = Style::default().fg(app.theme.text_bright).bg(bg);
    let cursor_style = Style::default().fg(app.theme.highlight).bg(bg);
    let buf_char_len;

    if cursor_pos < buffer.len() {
        let before = &buffer[..cursor_pos];
        let grapheme = unicode::grapheme_at(buffer, cursor_pos);
        let after = &buffer[cursor_pos + grapheme.len()..];
        buf_char_len = unicode::display_width(buffer);

        spans.push(Span::styled(before.to_string(), text_style));
        spans.push(Span::styled(
            grapheme.to_string(),
            Style::default()
                .fg(app.theme.background)
                .bg(app.theme.highlight)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(after.to_string(), text_style));
    } else {
        buf_char_len = unicode::display_width(buffer) + 1; // +1 for cursor block
        spans.push(Span::styled(buffer.to_string(), text_style));
        spans.push(Span::styled("\u{258C}", cursor_style));
    }

    // Pad name area to max_name_len so ID + stat columns stay aligned
    if buf_char_len < max_name_len {
        spans.push(Span::styled(
            " ".repeat(max_name_len - buf_char_len),
            Style::default().bg(bg),
        ));
    }

    // ID prefix column
    spans.push(Span::styled("  ", Style::default().bg(bg)));
    let id_style = Style::default().fg(app.theme.text).bg(bg);
    let prefix = app
        .project
        .config
        .ids
        .prefixes
        .get(&tc.id)
        .map(|p| p.to_uppercase())
        .unwrap_or_else(|| tc.id.to_uppercase());
    spans.push(Span::styled(
        format!("{:<width$}", prefix, width = max_id_len),
        id_style,
    ));

    // Stat columns
    let stats = app
        .project
        .tracks
        .iter()
        .find(|(id, _)| id == &tc.id)
        .map(|(_, track)| task_counts(track))
        .unwrap_or_default();

    let counts = [
        stats.todo,
        stats.active,
        stats.blocked,
        stats.done,
        stats.parked,
    ];
    let colors = [
        app.theme.text,
        app.theme.highlight,
        app.theme.red,
        app.theme.text,
        app.theme.yellow,
    ];

    for (count, color) in counts.iter().zip(colors.iter()) {
        let style = Style::default().fg(*color).bg(bg);
        spans.push(Span::styled(
            format!("{:>width$}", count, width = COL_W),
            style,
        ));
    }

    // cc-focus indicator
    if cc_focus == Some(tc.id.as_str()) {
        spans.push(Span::styled("  ", Style::default().bg(bg)));
        spans.push(Span::styled(
            "\u{2605} cc",
            Style::default().fg(app.theme.purple).bg(bg),
        ));
    }

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

    Line::from(spans)
}

/// Render an inline edit row for new track name entry
fn render_new_track_edit_row<'a>(
    app: &'a App,
    number: usize,
    num_width: usize,
    width: u16,
) -> Line<'a> {
    let bg = app.theme.selection_bg;
    let mut spans: Vec<Span> = Vec::new();

    // Selection border
    spans.push(Span::styled(
        "\u{258E}",
        Style::default().fg(app.theme.selection_border).bg(bg),
    ));

    // Number
    let num_str = format!("{:>width$}", number, width = num_width);
    spans.push(Span::styled(
        num_str,
        Style::default().fg(app.theme.dim).bg(bg),
    ));
    spans.push(Span::styled("  ", Style::default().bg(bg)));

    // Edit buffer with cursor
    let cursor_pos = app.edit_cursor;
    let buffer = &app.edit_buffer;
    let text_style = Style::default().fg(app.theme.text_bright).bg(bg);
    let cursor_style = Style::default().fg(app.theme.highlight).bg(bg);

    if cursor_pos < buffer.len() {
        let before = &buffer[..cursor_pos];
        let grapheme = unicode::grapheme_at(buffer, cursor_pos);
        let after = &buffer[cursor_pos + grapheme.len()..];

        spans.push(Span::styled(before.to_string(), text_style));
        spans.push(Span::styled(
            grapheme.to_string(),
            Style::default()
                .fg(app.theme.background)
                .bg(app.theme.highlight)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(after.to_string(), text_style));
    } else {
        spans.push(Span::styled(buffer.to_string(), text_style));
        spans.push(Span::styled("\u{258C}", cursor_style));
    }

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

    Line::from(spans)
}

/// Render the inline prefix edit row below a track (shown when P is pressed)
fn render_prefix_edit_row<'a>(app: &'a App, num_width: usize, width: u16) -> Line<'a> {
    let bg = app.theme.selection_bg;
    let mut spans: Vec<Span> = Vec::new();

    // Indent to align with name column: border(1) + num + "  " + "Prefix: "
    let indent = 1 + num_width + 2;
    spans.push(Span::styled(" ".repeat(indent), Style::default().bg(bg)));
    spans.push(Span::styled(
        "Prefix: ",
        Style::default().fg(app.theme.dim).bg(bg),
    ));

    // Edit buffer with cursor and selection
    let cursor_pos = app.edit_cursor;
    let buffer = &app.edit_buffer;
    let text_style = Style::default()
        .fg(app.theme.text_bright)
        .bg(bg)
        .add_modifier(Modifier::BOLD);
    let cursor_style = Style::default()
        .fg(app.theme.background)
        .bg(app.theme.highlight)
        .add_modifier(Modifier::BOLD);

    let sel_range = app.edit_selection_range();

    if let Some((sel_start, sel_end)) = sel_range {
        // Render with selection highlight
        let selection_style = Style::default()
            .fg(app.theme.text_bright)
            .bg(app.theme.highlight);
        let before_sel = &buffer[..sel_start];
        let selected = &buffer[sel_start..sel_end];
        let after_sel = &buffer[sel_end..];

        if !before_sel.is_empty() {
            spans.push(Span::styled(before_sel.to_string(), text_style));
        }
        spans.push(Span::styled(selected.to_string(), selection_style));
        if !after_sel.is_empty() {
            spans.push(Span::styled(after_sel.to_string(), text_style));
        }
        // Cursor at end
        if cursor_pos >= buffer.len() {
            spans.push(Span::styled(
                "\u{258C}",
                Style::default().fg(app.theme.highlight).bg(bg),
            ));
        }
    } else if cursor_pos < buffer.len() {
        let before = &buffer[..cursor_pos];
        let grapheme = unicode::grapheme_at(buffer, cursor_pos);
        let after = &buffer[cursor_pos + grapheme.len()..];

        spans.push(Span::styled(before.to_string(), text_style));
        spans.push(Span::styled(grapheme.to_string(), cursor_style));
        spans.push(Span::styled(after.to_string(), text_style));
    } else {
        spans.push(Span::styled(buffer.to_string(), text_style));
        spans.push(Span::styled(
            "\u{258C}",
            Style::default().fg(app.theme.highlight).bg(bg),
        ));
    }

    // Validation error (dim red text after the editor)
    if let Some(ref pr) = app.prefix_rename
        && !pr.validation_error.is_empty()
    {
        spans.push(Span::styled("  ", Style::default().bg(bg)));
        spans.push(Span::styled(
            pr.validation_error.clone(),
            Style::default().fg(app.theme.red).bg(bg),
        ));
    }

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

    Line::from(spans)
}

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

    #[test]
    fn overview_multiple_tracks() {
        let mut project = project_with_track(
            "alpha",
            "Alpha",
            "# Alpha\n\n## Backlog\n\n- [ ] `A-1` Task one\n- [>] `A-2` Task two\n\n## Done\n\n- [x] `A-3` Done task\n",
        );
        let track2 = crate::parse::parse_track(
            "# Beta\n\n## Backlog\n\n- [-] `B-1` Blocked task\n\n## Done\n",
        );
        project.config.tracks.push(crate::model::TrackConfig {
            id: "beta".into(),
            name: "Beta".into(),
            state: "active".into(),
            file: "tracks/beta.md".into(),
        });
        project.tracks.push(("beta".into(), track2));
        let mut app = App::new(project);
        app.view = crate::tui::app::View::Tracks;
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_tracks_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn overview_single_track() {
        let mut app = app_with_track(SIMPLE_TRACK_MD);
        app.view = crate::tui::app::View::Tracks;
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_tracks_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn overview_edit_mode() {
        let mut app = app_with_track(SIMPLE_TRACK_MD);
        app.view = crate::tui::app::View::Tracks;
        app.mode = Mode::Edit;
        app.edit_target = Some(EditTarget::NewTrackName);
        app.edit_buffer = "New Track".into();
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_tracks_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }
}