turboreview 0.1.1

A terminal code-review tool for git: review working-tree changes and commits, stage files, leave line comments, and hand off to an AI agent.
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Clear, List, ListItem, ListState, Padding, Paragraph, Wrap,
};
use ratatui::Frame;

use crate::app::{App, CommentRow, InputState, LineKind, Pane, Section, Status, ViewMode};
use crate::comments::CommentStatus;
use crate::highlight::highlight_code;
use crate::theme::Palette;
use crate::tree::RowKind;

fn status_letter(status: Status, pal: &Palette) -> (&'static str, ratatui::style::Color) {
    match status {
        Status::Added => ("A", pal.tick),
        Status::Modified => ("M", pal.yellow),
        Status::Deleted => ("D", pal.red),
        Status::Renamed => ("R", pal.blue),
        Status::Other => (" ", pal.accent_dim),
    }
}

fn gutter(dl: &crate::app::DiffLine) -> String {
    let n = dl.new_lineno.or(dl.old_lineno);
    match n {
        Some(n) => format!("{:>4} ", n),
        None => "     ".to_string(),
    }
}

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

    let main_area = outer[0];
    let comment_pct: u16 = 28;

    if app.show_files && app.show_comments {
        // Three columns: [Files | Diff | Comments]
        // Ensure middle (diff) is at least 20%
        let diff_pct = 100u16
            .saturating_sub(app.file_pane_pct)
            .saturating_sub(comment_pct)
            .max(20);
        let actual_files_pct = 100u16.saturating_sub(diff_pct).saturating_sub(comment_pct);
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(actual_files_pct),
                Constraint::Percentage(diff_pct),
                Constraint::Percentage(comment_pct),
            ])
            .split(main_area);
        match app.view {
            ViewMode::Changes => render_files(frame, app, panes[0]),
            ViewMode::Commits if app.open_commit.is_none() => render_commits(frame, app, panes[0]),
            ViewMode::Commits => render_files(frame, app, panes[0]),
        }
        render_diff(frame, app, panes[1]);
        render_comment_list(frame, app, panes[2]);
    } else if !app.show_files && app.show_comments {
        // Two columns: [Diff | Comments]
        let diff_pct = 100u16.saturating_sub(comment_pct).max(20);
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(diff_pct),
                Constraint::Percentage(comment_pct),
            ])
            .split(main_area);
        render_diff(frame, app, panes[0]);
        render_comment_list(frame, app, panes[1]);
    } else if app.show_files {
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(app.file_pane_pct),
                Constraint::Percentage(100 - app.file_pane_pct),
            ])
            .split(main_area);
        match app.view {
            ViewMode::Changes => render_files(frame, app, panes[0]),
            ViewMode::Commits if app.open_commit.is_none() => render_commits(frame, app, panes[0]),
            ViewMode::Commits => render_files(frame, app, panes[0]),
        }
        render_diff(frame, app, panes[1]);
    } else {
        render_diff(frame, app, main_area);
    }
    render_status(frame, app, outer[1]);
    if let Some(input) = &app.input {
        render_input_modal(frame, app, input);
    }
    if app.show_help {
        render_help_modal(frame, app);
    }
}

fn focused_border(app: &App, pane: Pane) -> Style {
    let pal = app.palette();
    if app.focus == pane {
        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(pal.accent_dim)
    }
}

fn status_color(status: CommentStatus, pal: &Palette) -> ratatui::style::Color {
    match status {
        CommentStatus::Open => pal.accent,
        CommentStatus::NeedsInfo => pal.yellow,
        CommentStatus::Wontfix => pal.red,
        CommentStatus::Resolved => pal.tick,
    }
}

fn render_comment_list(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let count = app.comments.items.len();
    let title = format!(" Comments ({}) ", count);

    let rows = app.comment_rows();
    let items: Vec<ListItem> = rows
        .iter()
        .map(|row| match row {
            CommentRow::Header(status, cnt) => {
                let label = format!("{} ({})", status.label(), cnt);
                let line = Line::from(Span::styled(
                    label,
                    Style::default()
                        .fg(status_color(*status, &pal))
                        .add_modifier(Modifier::BOLD),
                ));
                ListItem::new(line)
            }
            CommentRow::Item(i) => {
                let c = &app.comments.items[*i];
                let basename = c.file.file_name().and_then(|n| n.to_str()).unwrap_or("");
                let first_line = c.text.lines().next().unwrap_or("");
                let max_text = area.width.saturating_sub(20) as usize;
                let text_display = if first_line.chars().count() > max_text && max_text > 3 {
                    format!(
                        "{}",
                        first_line
                            .chars()
                            .take(max_text.saturating_sub(1))
                            .collect::<String>()
                    )
                } else {
                    first_line.to_string()
                };
                let line = Line::from(vec![
                    Span::styled(
                        format!("  {}:{} ", basename, c.line),
                        Style::default().fg(pal.accent_dim),
                    ),
                    Span::raw(text_display),
                ]);
                ListItem::new(line)
            }
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Comments))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );

    let mut state = ListState::default();
    if !rows.is_empty() {
        state.select(Some(app.comment_selected));
    }
    frame.render_stateful_widget(list, area, &mut state);
}

fn render_files(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let items: Vec<ListItem> = app
        .rows
        .iter()
        .map(|row| {
            let indent = "  ".repeat(row.depth);
            match &row.kind {
                RowKind::Header { section, count } => {
                    let label = match section {
                        Section::Unstaged => format!("{}▌ Unstaged ({})", indent, count),
                        Section::Staged => format!("{}▌ Staged ({})", indent, count),
                        Section::Commit => {
                            let short = app.open_commit_short().unwrap_or("commit");
                            format!("{}▌ Commit {} ({})", indent, short, count)
                        }
                    };
                    let line = Line::from(Span::styled(
                        label,
                        Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
                    ));
                    ListItem::new(line)
                }
                RowKind::Dir { collapsed, .. } => {
                    let glyph = if *collapsed { "" } else { "" };
                    let text = format!("{}{} {}", indent, glyph, row.name);
                    ListItem::new(Line::from(text))
                }
                RowKind::File {
                    section,
                    file_index,
                } => {
                    let files = app.section_files(*section);
                    let fc = &files[*file_index];
                    let file_path = &fc.path;
                    let (mark, mark_style) = if app.is_reviewed_path(file_path) {
                        ("", Style::default().fg(pal.tick))
                    } else {
                        ("", Style::default().fg(pal.accent_dim))
                    };
                    let (letter, letter_color) = status_letter(fc.status, &pal);
                    let icon = crate::icons::icon_for(file_path);
                    let line = Line::from(vec![
                        Span::raw(indent),
                        Span::styled(format!("{} ", letter), Style::default().fg(letter_color)),
                        Span::styled(mark, mark_style),
                        Span::raw(format!("{} {}", icon, row.name)),
                    ]);
                    ListItem::new(line)
                }
            }
        })
        .collect();
    let title = if app.in_commit_detail() {
        let short = app.open_commit_short().unwrap_or("commit");
        format!(" Changes  Commits ▸ {} ", short)
    } else if app.hide_reviewed {
        " [Changes] Commits  (hiding reviewed) ".to_string()
    } else {
        " [Changes] Commits ".to_string()
    };
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Files))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );
    let mut state = ListState::default();
    state.select(Some(app.selected));
    frame.render_stateful_widget(list, area, &mut state);
}

fn render_commits(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let items: Vec<ListItem> = app
        .commits
        .iter()
        .map(|ci| {
            // Truncate summary to avoid overflow
            let max_summary = area.width.saturating_sub(30) as usize;
            let summary = if ci.summary.chars().count() > max_summary && max_summary > 3 {
                format!(
                    "{}",
                    ci.summary.chars().take(max_summary - 1).collect::<String>()
                )
            } else {
                ci.summary.clone()
            };
            let line = Line::from(vec![
                Span::styled(format!("{} ", ci.short), Style::default().fg(pal.yellow)),
                Span::raw(summary),
                Span::styled(
                    format!("{} {}", ci.author, ci.time),
                    Style::default().fg(pal.accent_dim),
                ),
            ]);
            ListItem::new(line)
        })
        .collect();

    let title = " Changes [Commits] ";
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(focused_border(app, Pane::Files))
                .title(title),
        )
        .highlight_style(
            Style::default()
                .bg(pal.selected_bg)
                .add_modifier(Modifier::BOLD),
        );
    let mut state = ListState::default();
    state.select(if app.commits.is_empty() {
        None
    } else {
        Some(app.selected_commit)
    });
    frame.render_stateful_widget(list, area, &mut state);
}

fn render_diff(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    let ext = app
        .selected_path()
        .and_then(|p| p.extension())
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_string();

    let ctx_label = if app.full_file {
        "full file".to_string()
    } else {
        format!("ctx {}", app.context_lines)
    };
    let title = app
        .selected_path()
        .map(|p| format!(" Diff: {} ({}) ", p.display(), ctx_label))
        .unwrap_or_else(|| " Diff ".to_string());

    let lines: Vec<Line> = if app.view == ViewMode::Commits && app.open_commit.is_none() {
        vec![Line::from(Span::styled(
            "Press Enter to open commit  ·  [/] switch view",
            Style::default().fg(pal.placeholder),
        ))]
    } else if app.diff.is_empty() {
        vec![Line::from(Span::styled(
            "No changes",
            Style::default().fg(pal.placeholder),
        ))]
    } else {
        let page = area.height.saturating_sub(2) as usize;

        // Compute the rendered height (diff line + its inline comment box lines) for a
        // given diff index, so we can scroll in rendered-line space and guarantee the
        // cursor line AND its comment are always visible.
        // comment box: 1 (top) + text_lines + (if response: 1 blank + response_lines) + 1 (bottom)
        let rendered_height = |i: usize| -> usize {
            let dl = &app.diff[i];
            let comment_lines = app
                .comment_for(dl)
                .map(|c| {
                    let text_lines = c.text.lines().count().max(1);
                    let response_lines = match c.response.as_deref() {
                        Some(r) if !r.trim().is_empty() => 1 + r.lines().count(), // 1 blank separator + response text lines
                        _ => 0,
                    };
                    1 + text_lines + response_lines + 1 // top + text + [blank+response] + bottom
                })
                .unwrap_or(0);
            1 + comment_lines
        };

        // Walk backward from diff_cursor to find the first visible diff index such
        // that the total rendered height from start..=cursor fits within `page`.
        let mut start = app.diff_cursor;
        let mut used = rendered_height(app.diff_cursor);
        while start > 0 {
            let h = rendered_height(start - 1);
            if used + h > page {
                break;
            }
            used += h;
            start -= 1;
        }

        let mut result: Vec<Line> = Vec::new();
        let mut rendered_rows: usize = 0;
        for (idx, dl) in app.diff.iter().enumerate().skip(start) {
            if rendered_rows >= page {
                break;
            }
            let is_cursor = idx == app.diff_cursor;
            let bg = match dl.kind {
                LineKind::Add => Some(pal.add_bg),
                LineKind::Del => Some(pal.del_bg),
                _ => None,
            };
            if dl.kind == LineKind::Hunk {
                let shifted: String = dl.text.chars().skip(app.diff_hscroll).collect();
                let mut span = Span::styled(shifted, Style::default().fg(pal.hunk));
                if is_cursor {
                    span.style = span.style.bg(pal.selected_bg);
                }
                result.push(Line::from(span));
                rendered_rows += 1;
                continue;
            }
            // Gutter: YELLOW for stale-commented lines, ACCENT for normal commented, ACCENT_DIM otherwise.
            let comment = app.comment_for(dl);
            let gutter_fg = match comment {
                Some(c) if c.stale => pal.yellow,
                Some(_) => pal.accent,
                None => pal.accent_dim,
            };
            let gutter_style = if is_cursor {
                Style::default().fg(gutter_fg).bg(pal.selected_bg)
            } else {
                Style::default().fg(gutter_fg)
            };
            let gutter_span = Span::styled(gutter(dl), gutter_style);
            let shifted: String = dl.text.chars().skip(app.diff_hscroll).collect();
            let mut spans: Vec<Span> = highlight_code(&shifted, &ext, app.theme);
            if is_cursor {
                for s in spans.iter_mut() {
                    s.style = s.style.bg(pal.selected_bg);
                }
            } else {
                if let Some(bg) = bg {
                    for s in spans.iter_mut() {
                        s.style = s.style.bg(bg);
                    }
                }
                if dl.kind == LineKind::Context {
                    for s in spans.iter_mut() {
                        s.style = s.style.add_modifier(Modifier::DIM);
                    }
                }
            }
            let mut all_spans = Vec::with_capacity(1 + spans.len());
            all_spans.push(gutter_span);
            all_spans.extend(spans);
            result.push(Line::from(all_spans));
            rendered_rows += 1;

            // Enhancement 5a: Inline comment box with box-drawing chars.
            // Normal:  ╭─ comment  /  │ <line>...  /  ╰─
            // Stale:   ╭─ ⚠ outdated · <status> (yellow) / │ <line>... / ╰─
            // Status badge colors: resolved=TICK, wontfix=RED, needs_info=YELLOW, open=ACCENT_DIM
            // Response: blank line + ↳ response: <text> lines, shown below body
            // The top + body lines + optional response + bottom are all counted toward budget.
            if let Some(c) = comment {
                // Determine border color based on stale flag and status
                let border_color = if c.stale {
                    pal.yellow
                } else {
                    match c.status {
                        CommentStatus::Open => pal.accent_dim,
                        CommentStatus::Resolved => pal.tick,
                        CommentStatus::Wontfix => pal.red,
                        CommentStatus::NeedsInfo => pal.yellow,
                    }
                };
                let border_style = Style::default()
                    .fg(border_color)
                    .add_modifier(Modifier::ITALIC | Modifier::DIM);
                let body_style = Style::default()
                    .fg(pal.accent_dim)
                    .add_modifier(Modifier::ITALIC);

                // Top border line with status badge
                if rendered_rows < page {
                    let top_label = if c.stale {
                        format!("    ╭─ ⚠ outdated · {}", c.status.label())
                    } else {
                        match c.status {
                            CommentStatus::Open => "    ╭─ comment".to_string(),
                            CommentStatus::Resolved => "    ╭─ ✓ resolved".to_string(),
                            CommentStatus::Wontfix => "    ╭─ ✗ wontfix".to_string(),
                            CommentStatus::NeedsInfo => "    ╭─ ? needs-info".to_string(),
                        }
                    };
                    result.push(Line::from(Span::styled(top_label, border_style)));
                    rendered_rows += 1;
                }
                // Body lines (reviewer's comment text)
                for comment_line in c.text.lines() {
                    if rendered_rows >= page {
                        break;
                    }
                    let prefix = Span::styled("", body_style);
                    let body = Span::styled(comment_line.to_string(), body_style);
                    result.push(Line::from(vec![prefix, body]));
                    rendered_rows += 1;
                }
                // Response block (only when response is present AND non-empty after trim)
                if c.response
                    .as_deref()
                    .map_or(false, |r| !r.trim().is_empty())
                {
                    let resp = c.response.as_deref().unwrap();
                    let response_label_style = Style::default()
                        .fg(border_color)
                        .add_modifier(Modifier::ITALIC | Modifier::DIM);
                    // Blank separator line
                    if rendered_rows < page {
                        result.push(Line::from(Span::styled("", body_style)));
                        rendered_rows += 1;
                    }
                    // Response lines
                    let mut first = true;
                    for resp_line in resp.lines() {
                        if rendered_rows >= page {
                            break;
                        }
                        let line_content = if first {
                            first = false;
                            format!("    │ ↳ response: {}", resp_line)
                        } else {
                            format!("{}", resp_line)
                        };
                        result.push(Line::from(Span::styled(line_content, response_label_style)));
                        rendered_rows += 1;
                    }
                }
                // Bottom border line
                if rendered_rows < page {
                    result.push(Line::from(Span::styled("    ╰─", border_style)));
                    rendered_rows += 1;
                }
            }
        }
        result
    };

    let para = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(focused_border(app, Pane::Diff))
            .title(title),
    );
    frame.render_widget(para, area);
}

fn render_status(frame: &mut Frame, app: &App, area: Rect) {
    let pal = app.palette();
    // Footer is just a help reminder plus any transient status message.
    let base = "? for help";
    let text = match &app.status_msg {
        Some(msg) => format!("{}   |   {}", base, msg),
        None => base.to_string(),
    };
    let para = Paragraph::new(text).style(Style::default().fg(pal.accent_dim));
    frame.render_widget(para, area);
}

/// Compute a centered Rect using percentages of the given area.
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let margin_v = (100u16.saturating_sub(percent_y)) / 2;
    let margin_h = (100u16.saturating_sub(percent_x)) / 2;
    let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(margin_v),
            Constraint::Percentage(percent_y),
            Constraint::Percentage(margin_v),
        ])
        .split(area);
    let horizontal = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(margin_h),
            Constraint::Percentage(percent_x),
            Constraint::Percentage(margin_h),
        ])
        .split(vertical[1]);
    horizontal[1]
}

fn render_input_modal(frame: &mut Frame, app: &App, input: &InputState) {
    let pal = app.palette();
    let area = centered_rect(60, 40, frame.area());
    frame.render_widget(Clear, area);
    let title = format!(
        " Comment line {} (Ctrl-S save · Esc cancel) ",
        input.target_line
    );
    // Append a cursor block indicator to the buffer text.
    let display_text = format!("{}", input.buffer);
    // Enhancement 5b: rounded border, accent color, horizontal padding for clearer text field.
    let para = Paragraph::new(display_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(pal.accent))
                .padding(Padding::horizontal(1))
                .title(title),
        )
        .wrap(Wrap { trim: false });
    frame.render_widget(para, area);
}

const HELP_LINES: &[(&str, &str)] = &[
    ("Tab", "switch focus (Files/Diff/Comments)"),
    ("j/k, ↑/↓", "move selection / cursor"),
    ("gg / G", "top / bottom"),
    (
        "Enter",
        "open file diff / open commit / fold dir / jump to comment",
    ),
    ("Esc", "back / focus files"),
    ("h/l, ←/→", "scroll diff horizontally"),
    ("+/-", "context lines (±5)"),
    ("F", "full-file diff toggle"),
    ("z", "hide/show file pane"),
    ("C", "toggle comment-list pane"),
    ("< / >", "resize file pane"),
    ("[ / ]", "switch Changes/Commits view"),
    ("c", "comment on line"),
    ("s", "stage / unstage file"),
    ("Space", "toggle reviewed"),
    ("R", "hide reviewed files"),
    ("r", "refresh"),
    ("T", "toggle light / dark theme"),
    ("?", "this help"),
    ("q / Ctrl-C", "quit"),
];

fn render_help_modal(frame: &mut Frame, app: &App) {
    let pal = app.palette();
    let area = centered_rect(60, 70, frame.area());
    frame.render_widget(Clear, area);
    let lines: Vec<Line> = HELP_LINES
        .iter()
        .map(|(key, desc)| {
            Line::from(vec![
                Span::styled(
                    format!("  {:14}", key),
                    Style::default().fg(pal.accent).add_modifier(Modifier::BOLD),
                ),
                Span::styled(desc.to_string(), Style::default().fg(pal.accent_dim)),
            ])
        })
        .collect();
    let para = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(pal.accent))
            .title(" Keybindings (? or Esc to close) "),
    );
    frame.render_widget(para, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{App, DiffLine, FileChange, Status};
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;
    use std::path::PathBuf;

    fn app_with_diff() -> App {
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            },
            DiffLine {
                kind: LineKind::Add,
                text: "let x = 1;".into(),
                old_lineno: None,
                new_lineno: Some(1),
            },
        ]);
        app
    }

    #[test]
    fn render_does_not_panic_and_shows_file() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let app = app_with_diff();
        terminal.draw(|f| render(f, &app)).unwrap();
        let buf = terminal.backend().buffer().clone();
        let dump: String = buf.content().iter().map(|c| c.symbol()).collect();
        assert!(dump.contains("a.rs"));
        assert!(dump.contains(""));
    }

    #[test]
    fn scroll_offset_hides_earlier_lines() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        // With the cursor near the end, the viewport scrolls so earlier lines are not rendered.
        app.set_diff({
            let mut lines = vec![crate::app::DiffLine {
                kind: LineKind::Hunk,
                text: "@@ -1 +1 @@".into(),
                old_lineno: None,
                new_lineno: None,
            }];
            // Add 18 context lines after hunk so page=18 and cursor=18 scrolls past the hunk.
            for i in 1..=18u32 {
                lines.push(crate::app::DiffLine {
                    kind: LineKind::Add,
                    text: "let x = 1;".into(),
                    old_lineno: None,
                    new_lineno: Some(i),
                });
            }
            lines
        });
        // With page=18, cursor=18 -> scroll = 18+1-18 = 1, so hunk at index 0 is hidden.
        app.diff_cursor = 18;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!dump.contains("@@ -1 +1 @@"));
        assert!(dump.contains("let x = 1;"));
    }

    #[test]
    fn empty_diff_shows_placeholder() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("No changes"));
    }

    #[test]
    fn hscroll_offsets_diff_text() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![DiffLine {
            kind: LineKind::Context,
            text: "ABCDEFGHIJ".into(),
            old_lineno: Some(1),
            new_lineno: Some(1),
        }]);
        // no scroll: "ABCDEF..." visible
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump0: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump0.contains("ABCDEFGHIJ"));
        // scroll right 4: leading "ABCD" gone, "EFGHIJ" remains
        app.diff_hscroll = 4;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump1: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump1.contains("EFGHIJ"));
        assert!(!dump1.contains("ABCDEFGHIJ"));
    }

    #[test]
    fn diff_shows_line_numbers() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![
            DiffLine {
                kind: LineKind::Context,
                text: "ctx".into(),
                old_lineno: Some(7),
                new_lineno: Some(7),
            },
            DiffLine {
                kind: LineKind::Add,
                text: "added".into(),
                old_lineno: None,
                new_lineno: Some(8),
            },
            DiffLine {
                kind: LineKind::Del,
                text: "removed".into(),
                old_lineno: Some(5),
                new_lineno: None,
            },
        ]);
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains('7'), "context line number 7 missing");
        assert!(dump.contains('8'), "add line number 8 missing");
        assert!(dump.contains('5'), "del line number 5 missing");
        assert!(dump.contains("ctx"), "context text missing");
        assert!(dump.contains("added"), "add text missing");
        assert!(dump.contains("removed"), "del text missing");
    }

    #[test]
    fn tree_view_shows_dir_and_basenames() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![
            FileChange {
                path: PathBuf::from("src/main.rs"),
                status: Status::Modified,
            },
            FileChange {
                path: PathBuf::from("top.rs"),
                status: Status::Modified,
            },
        ];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("src"),
            "directory name 'src' missing from tree view"
        );
        assert!(
            dump.contains("main.rs"),
            "file basename 'main.rs' missing from tree view"
        );
        assert!(
            dump.contains("top.rs"),
            "file basename 'top.rs' missing from tree view"
        );
        assert!(
            !dump.contains("src/main.rs"),
            "full path 'src/main.rs' should not appear; tree view shows basenames"
        );
    }

    #[test]
    fn reviewed_file_shows_tick() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // select a.rs row (row 1) and review it
        app.selected = 1;
        app.toggle_reviewed(); // review a.rs
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains(""));
    }

    #[test]
    fn both_sections_headers_render_when_both_non_empty() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let unstaged = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let staged = vec![FileChange {
            path: PathBuf::from("b.rs"),
            status: Status::Added,
        }];
        let app = App::new(unstaged, staged, PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("Unstaged"), "Unstaged header missing");
        assert!(dump.contains("Staged"), "Staged header missing");
        assert!(dump.contains("a.rs"), "a.rs missing");
        assert!(dump.contains("b.rs"), "b.rs missing");
    }

    #[test]
    fn files_title_has_no_mode_label() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The block title shows the tab bar with Changes and Commits tabs.
        // In Changes mode, Changes tab is active (in brackets).
        assert!(dump.contains("Changes"), "Changes tab missing from title");
        assert!(dump.contains("Commits"), "Commits tab missing from title");
        assert!(
            !dump.contains("STAGED"),
            "[STAGED] mode label should be gone"
        );
        assert!(
            !dump.contains("UNSTAGED"),
            "[UNSTAGED] mode label should be gone"
        );
    }

    #[test]
    fn hidden_file_pane_shows_only_diff() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("zzz.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_files = false;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(!dump.contains("zzz.rs")); // file pane hidden
        assert!(dump.contains("No changes") || dump.contains("Diff")); // diff pane present
    }

    #[test]
    fn modified_file_shows_m_status_letter() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains('M'),
            "Modified file should show 'M' status letter"
        );
        assert!(dump.contains("a.rs"), "filename should still appear");
    }

    #[test]
    fn input_modal_shows_buffer_and_title() {
        use crate::app::InputState;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = app_with_diff();
        app.focus = Pane::Diff;
        app.input = Some(InputState {
            buffer: "hello world".to_string(),
            target_file: PathBuf::from("a.rs"),
            target_line: 1,
            target_hunk: "@@ -1 +1 @@".to_string(),
            anchor_line_text: String::new(),
            anchor_before: vec![],
            anchor_after: vec![],
        });
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("hello world"),
            "modal buffer text must appear"
        );
        assert!(
            dump.contains("Comment"),
            "modal title must contain 'Comment'"
        );
    }

    #[test]
    fn commented_line_shows_comment_text_inline() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs row
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(5),
        }]);
        // attach a comment for a.rs line 5
        app.comments.set(
            PathBuf::from("a.rs"),
            5,
            "@@ -3,4 @@".to_string(),
            "review note here".to_string(),
            "let x = 1;".to_string(),
            vec![],
            vec![],
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("review note here"),
            "inline comment text must appear below commented line"
        );
    }

    /// FIX 2: comment on a line near the bottom of a small viewport must not be clipped.
    /// Build a diff of 30 context lines + one Add line with a comment. Set the cursor
    /// on the Add line. Use an 80x10 backend (page = 8 visible rows). With the old
    /// scroll formula (diff-index space), the comment would be pushed off screen.
    /// With rendered-height scroll the comment must appear in the buffer.
    #[test]
    fn comment_not_clipped_when_cursor_near_bottom() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 10);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs
        app.focus = Pane::Diff;

        // 30 context lines, then one Add line at new_lineno 31
        let mut diff_lines = Vec::new();
        for i in 1u32..=30 {
            diff_lines.push(DiffLine {
                kind: LineKind::Context,
                text: format!("ctx {}", i),
                old_lineno: Some(i),
                new_lineno: Some(i),
            });
        }
        diff_lines.push(DiffLine {
            kind: LineKind::Add,
            text: "added_line".into(),
            old_lineno: None,
            new_lineno: Some(31),
        });
        app.set_diff(diff_lines);

        // cursor on the Add line (index 30)
        app.diff_cursor = 30;

        // attach a comment to that Add line
        app.comments.set(
            PathBuf::from("a.rs"),
            31,
            "".to_string(),
            "clipping_test_comment".to_string(),
            "added_line".to_string(),
            vec![],
            vec![],
        );

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("clipping_test_comment"),
            "comment on cursor line must not be clipped even near the viewport bottom"
        );
    }

    /// FIX 1: saving a comment with leading/trailing whitespace must store only the
    /// trimmed text. Verify by setting a padded comment and checking that the rendered
    /// inline comment shows the trimmed text (no surrounding spaces).
    #[test]
    fn trimmed_comment_stored_without_whitespace_padding() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "fn main() {}".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        // Simulate what main.rs does after Fix 1: store the trimmed text.
        let raw = "   trimmed_note   ";
        let trimmed = raw.trim().to_string();
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "".to_string(),
            trimmed,
            "fn main() {}".to_string(),
            vec![],
            vec![],
        );

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("trimmed_note"),
            "trimmed comment text must appear"
        );
        // The raw padded string (with surrounding spaces) must not be stored/rendered.
        assert!(
            !dump.contains("   trimmed_note   "),
            "padded comment text must not appear"
        );
    }

    #[test]
    fn added_file_shows_a_deleted_shows_d() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![
            FileChange {
                path: PathBuf::from("new.rs"),
                status: Status::Added,
            },
            FileChange {
                path: PathBuf::from("old.rs"),
                status: Status::Deleted,
            },
        ];
        let app = App::new(files, vec![], PathBuf::from("/repo"));
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains('A'),
            "Added file should show 'A' status letter"
        );
        assert!(
            dump.contains('D'),
            "Deleted file should show 'D' status letter"
        );
    }

    #[test]
    fn resolved_comment_shows_status_and_response() {
        use crate::app::LineKind;
        use crate::comments::CommentStatus;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "fn foo() {}".into(),
            old_lineno: None,
            new_lineno: Some(3),
        }]);
        app.comments.set(
            PathBuf::from("a.rs"),
            3,
            "@@".to_string(),
            "please fix this".to_string(),
            "fn foo() {}".to_string(),
            vec![],
            vec![],
        );
        app.comments.items[0].status = CommentStatus::Resolved;
        app.comments.items[0].response = Some("Fixed it".to_string());

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("resolved"),
            "resolved status must appear in comment box"
        );
        assert!(
            dump.contains("Fixed it"),
            "agent response must appear in comment box"
        );
    }

    #[test]
    fn stale_comment_shows_outdated_prefix() {
        use crate::app::LineKind;
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1;
        app.focus = Pane::Diff;
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let y = 2;".into(),
            old_lineno: None,
            new_lineno: Some(7),
        }]);
        // Insert a stale comment directly
        app.comments.set(
            PathBuf::from("a.rs"),
            7,
            "@@".to_string(),
            "stale note".to_string(),
            "let y = 2;".to_string(),
            vec![],
            vec![],
        );
        // Mark it stale manually (simulating relocation failure)
        app.comments.items[0].stale = true;

        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("outdated"),
            "stale comment must show '(outdated)' prefix"
        );
        assert!(
            dump.contains("stale note"),
            "stale comment text must still appear"
        );
    }

    #[test]
    fn comment_pane_shows_status_header_and_item() {
        let backend = TestBackend::new(160, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // Enable comment pane
        app.show_comments = true;
        // Add an Open comment
        app.comments.set(
            PathBuf::from("a.rs"),
            5,
            "@@ -3,4 @@".to_string(),
            "look at this".to_string(),
            "fn foo()".to_string(),
            vec![],
            vec![],
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // The comment pane title must appear
        assert!(dump.contains("Comments"), "comment pane title must appear");
        // The Open status header must appear
        assert!(
            dump.contains("Open") || dump.contains("open"),
            "Open status header must appear"
        );
        // The file basename must appear
        assert!(
            dump.contains("a.rs"),
            "file basename must appear in comment list"
        );
    }

    #[test]
    fn comment_pane_hidden_by_default() {
        let backend = TestBackend::new(120, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        // show_comments is false by default
        app.comments.set(
            PathBuf::from("a.rs"),
            1,
            "@@".to_string(),
            "hidden comment".to_string(),
            "fn x()".to_string(),
            vec![],
            vec![],
        );
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // Comment pane title must NOT appear when show_comments is false
        assert!(
            !dump.contains("hidden comment"),
            "comment text must not appear when pane hidden"
        );
    }

    #[test]
    fn help_overlay_shows_keybindings_title() {
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_help = true;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("Keybindings"),
            "help overlay must show 'Keybindings' title"
        );
    }

    #[test]
    fn help_overlay_shows_theme_toggle_key() {
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.show_help = true;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(
            dump.contains("theme"),
            "help overlay must mention theme toggle"
        );
    }

    #[test]
    fn empty_response_does_not_break_layout() {
        // A comment with an empty-string response must render without a phantom line
        // (regression: rendered-height overcounted, clipping the box bottom).
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.selected = 1; // select a.rs row (row 0=Unstaged header, row 1=File a.rs)
        app.focus = Pane::Diff;
        // place a comment with empty response on a line in the diff
        app.comments.items.push(crate::comments::Comment {
            file: PathBuf::from("a.rs"),
            line: 1,
            hunk: String::new(),
            text: "please fix".into(),
            line_text: "let x = 1;".into(),
            context_before: vec![],
            context_after: vec![],
            orig_line: 1,
            stale: false,
            status: crate::comments::CommentStatus::Open,
            response: Some(String::new()),
        });
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        // the comment text renders; no panic; "response:" label NOT shown for empty response
        assert!(dump.contains("please fix"));
        assert!(!dump.contains("response:"));
    }

    #[test]
    fn light_theme_renders_without_panic() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let files = vec![FileChange {
            path: PathBuf::from("a.rs"),
            status: Status::Modified,
        }];
        let mut app = App::new(files, vec![], PathBuf::from("/repo"));
        app.set_diff(vec![DiffLine {
            kind: LineKind::Add,
            text: "let x = 1;".into(),
            old_lineno: None,
            new_lineno: Some(1),
        }]);
        app.theme = crate::theme::Theme::Light;
        terminal.draw(|f| render(f, &app)).unwrap();
        let dump: String = terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|c| c.symbol())
            .collect();
        assert!(dump.contains("a.rs"), "file must appear in light theme");
    }
}