travelagent 1.10.3

Agent-first TUI code review tool
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
//! Unified diff view rendering (H9 part 4).
//!
//! Extracted from `ui/app_layout.rs`. Owns the unified-diff rendering
//! path: the primary `render_unified_diff` entry, plus the
//! `unified_line_bg_style` classifier and `paint_unified_diff_row_backgrounds`
//! painter that colour the per-row backgrounds for visual selection,
//! reviewed highlighting, and orphan markers.
//!
//! Shared helpers (`expand_tabs`, `cursor_indicator*`, `truncate_or_pad*`,
//! `render_expanded_context_line`, `render_expander_line`,
//! `render_hidden_lines`, `render_collapsed_placeholder`,
//! `comment_type_presentation`, `render_orphans_section`,
//! `render_session_orphans`, `scroll_comment_input_into_view`,
//! `diff_stat_title`, `apply_horizontal_scroll`) stay in `app_layout.rs`
//! under `pub(crate)` visibility.

use ratatui::{
    Frame,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};
use unicode_width::UnicodeWidthStr;

use crate::app::{App, ExpandDirection, FocusedPanel, GAP_EXPAND_BATCH, GapId, InputMode};
use crate::theme::Theme;
use crate::ui::app_layout::{
    apply_horizontal_scroll, comment_type_presentation, cursor_indicator, cursor_indicator_spaced,
    diff_stat_title, expand_tabs, render_collapsed_placeholder, render_expanded_context_line,
    render_expander_line, render_hidden_lines, render_orphans_section, render_session_orphans,
    scroll_comment_input_into_view,
};
use crate::ui::{comment_panel, styles};
use travelagent_core::model::{LineOrigin, LineRange, LineSide};
use travelagent_core::vcs::git::calculate_gap;

pub(super) fn render_unified_diff(frame: &mut Frame, app: &mut App, area: Rect) {
    let focused = app.nav.focused_panel == FocusedPanel::Diff;

    let title = if app.is_cursor_in_overview() || app.current_file_path().is_none() {
        " Diff (Unified) \u{2014} Overview ".to_string()
    } else {
        format!(
            " Diff (Unified) \u{2014} {} ",
            app.current_file_path().unwrap().display()
        )
    };

    let block = Block::default()
        .title(title)
        .title_top(diff_stat_title(app).right_aligned())
        .borders(Borders::ALL)
        .style(styles::panel_style(&app.theme))
        .border_style(styles::border_style(&app.theme, focused));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Update viewport height for scroll calculations
    app.diff_state.viewport_height = inner.height as usize;

    // Build all diff lines for infinite scroll
    // Track line index to mark the current line (cursor position)
    let mut lines: Vec<Line> = Vec::new();
    let mut line_idx: usize = 0;
    let current_line_idx = app.diff_state.cursor_line;

    // Track cursor position for IME when in Comment mode
    // Store the logical line index and column where the cursor should be
    let mut comment_cursor_logical_line: Option<usize> = None;
    let mut comment_cursor_column: u16 = 0;
    // Track the full extent of the comment input box so we can auto-scroll
    // the viewport to keep it visible while the user types.
    let mut comment_input_box_range: Option<(usize, usize)> = None;

    let is_review_comment_mode =
        app.nav.input_mode == InputMode::Comment && app.comment.is_review_level;

    let general_indicator = cursor_indicator_spaced(line_idx, current_line_idx);
    lines.push(Line::from(vec![
        Span::styled(
            general_indicator,
            styles::current_line_indicator_style(&app.theme),
        ),
        Span::styled(
            "═══ Review Comments ",
            styles::file_header_style(&app.theme),
        ),
        Span::styled("".repeat(40), styles::file_header_style(&app.theme)),
    ]));
    line_idx += 1;

    for comment in &app.engine.session().review_comments {
        let is_being_edited =
            app.comment.editing_id.as_ref() == Some(&comment.id) && is_review_comment_mode;

        if is_being_edited {
            let (input_lines, cursor_info) = comment_panel::format_comment_input_lines(
                &app.theme,
                comment_type_presentation(app, &app.comment.comment_type),
                &app.comment.buffer,
                app.comment.cursor,
                None,
                true,
                app.supports_keyboard_enhancement,
            );
            comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
            comment_cursor_column = 1 + cursor_info.column;
            comment_input_box_range =
                Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

            for mut input_line in input_lines {
                let indicator = cursor_indicator(line_idx, current_line_idx);
                input_line.spans.insert(
                    0,
                    Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                );
                lines.push(input_line);
                line_idx += 1;
            }
        } else {
            let comment_lines = comment_panel::format_comment_lines(
                &app.theme,
                comment_type_presentation(app, &comment.comment_type),
                &comment.content,
                None,
            );
            for mut comment_line in comment_lines {
                let indicator = cursor_indicator(line_idx, current_line_idx);
                comment_line.spans.insert(
                    0,
                    Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                );
                lines.push(comment_line);
                line_idx += 1;
            }
        }
    }

    if is_review_comment_mode && app.comment.editing_id.is_none() {
        let (input_lines, cursor_info) = comment_panel::format_comment_input_lines(
            &app.theme,
            comment_type_presentation(app, &app.comment.comment_type),
            &app.comment.buffer,
            app.comment.cursor,
            None,
            false,
            app.supports_keyboard_enhancement,
        );
        comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
        comment_cursor_column = 1 + cursor_info.column;
        comment_input_box_range = Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

        for mut input_line in input_lines {
            let indicator = cursor_indicator(line_idx, current_line_idx);
            input_line.spans.insert(
                0,
                Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
            );
            lines.push(input_line);
            line_idx += 1;
        }
    }

    // L3: session-level orphaned comments (files that disappeared entirely
    // from the working tree after a rescan). Rendered once above the file
    // list so the user can see + re-anchor orphans even if the owning file
    // is gone.
    render_session_orphans(&mut lines, &mut line_idx, current_line_idx, app);

    for (file_idx, file) in app.diff_files.iter().enumerate() {
        let path = file.display_path_lossy();
        let status = file.status.as_char();
        let is_reviewed = app.engine.session().is_file_reviewed(path);
        let file_risk_band = if app.risk_border_colors {
            Some(travelagent_core::risk::RiskBand::for_score(
                travelagent_core::risk::score_file(path.as_path(), &file.hunks, &app.risk_config),
            ))
        } else {
            None
        };

        // L3: per-file orphaned section renders *before* the file header.
        if let Some(review) = app.engine.session().files.get(path.as_path())
            && !review.orphaned_comments.is_empty()
        {
            let label = format!(
                "── Orphaned comments ({}) — {} ──",
                review.orphaned_comments.len(),
                path.display()
            );
            let orphans = review.orphaned_comments.clone();
            render_orphans_section(
                &mut lines,
                &mut line_idx,
                current_line_idx,
                app,
                label,
                &orphans,
            );
        }

        // File header
        let indicator = cursor_indicator_spaced(line_idx, current_line_idx);

        // Add checkmark if reviewed (using same character as file list)
        let review_mark = if is_reviewed { "" } else { "" };

        let header_text = if file.is_commit_message {
            format!("═══ {review_mark}Commit Message ")
        } else {
            format!("═══ {}{} [{}] ", review_mark, path.display(), status)
        };
        let file_header_style = styles::file_header_style_with_risk(&app.theme, file_risk_band);
        lines.push(Line::from(vec![
            Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
            Span::styled(header_text, file_header_style),
            Span::styled("".repeat(40), file_header_style),
        ]));
        line_idx += 1;

        // If file is reviewed, skip rendering the body (fold it away)
        if is_reviewed {
            continue;
        }

        // If file is collapsed, render a single centered placeholder instead
        // of the diff body.
        if app.is_file_collapsed(file_idx) {
            render_collapsed_placeholder(&mut lines, &mut line_idx, current_line_idx, app, file);
            // Spacing line after the placeholder to match the normal file
            // layout height assumed by `file_render_height`.
            let indicator = cursor_indicator(line_idx, current_line_idx);
            lines.push(Line::from(Span::styled(
                indicator,
                styles::current_line_indicator_style(&app.theme),
            )));
            line_idx += 1;
            continue;
        }

        // Check if we're editing/adding a file-level comment for this file
        let is_file_comment_mode = app.nav.input_mode == InputMode::Comment
            && app.comment.is_file_level
            && file_idx == app.diff_state.current_file_idx;

        // Show file-level comments right after the header
        if let Some(review) = app.engine.session().files.get(path) {
            for comment in &review.file_comments {
                // Skip rendering this comment if it's being edited
                let is_being_edited =
                    app.comment.editing_id.as_ref() == Some(&comment.id) && is_file_comment_mode;

                if is_being_edited {
                    // Render the inline input instead
                    let (input_lines, cursor_info) = comment_panel::format_comment_input_lines(
                        &app.theme,
                        comment_type_presentation(app, &app.comment.comment_type),
                        &app.comment.buffer,
                        app.comment.cursor,
                        None,
                        true,
                        app.supports_keyboard_enhancement,
                    );
                    // Track cursor position: logical line = current line_idx + cursor offset within input
                    comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
                    // Column = indicator (1) + cursor_info.column
                    comment_cursor_column = 1 + cursor_info.column;
                    comment_input_box_range =
                        Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

                    for mut input_line in input_lines {
                        let indicator = cursor_indicator(line_idx, current_line_idx);
                        input_line.spans.insert(
                            0,
                            Span::styled(
                                indicator,
                                styles::current_line_indicator_style(&app.theme),
                            ),
                        );
                        lines.push(input_line);
                        line_idx += 1;
                    }
                } else {
                    let comment_lines = comment_panel::format_comment_lines(
                        &app.theme,
                        comment_type_presentation(app, &comment.comment_type),
                        &comment.content,
                        None,
                    );
                    for mut comment_line in comment_lines {
                        let indicator = cursor_indicator(line_idx, current_line_idx);
                        comment_line.spans.insert(
                            0,
                            Span::styled(
                                indicator,
                                styles::current_line_indicator_style(&app.theme),
                            ),
                        );
                        lines.push(comment_line);
                        line_idx += 1;
                    }
                }
            }
        }

        // Render inline input for new file-level comment
        if is_file_comment_mode && app.comment.editing_id.is_none() {
            let (input_lines, cursor_info) = comment_panel::format_comment_input_lines(
                &app.theme,
                comment_type_presentation(app, &app.comment.comment_type),
                &app.comment.buffer,
                app.comment.cursor,
                None,
                false,
                app.supports_keyboard_enhancement,
            );
            // Track cursor position
            comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
            comment_cursor_column = 1 + cursor_info.column;
            comment_input_box_range =
                Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

            for mut input_line in input_lines {
                let indicator = cursor_indicator(line_idx, current_line_idx);
                input_line.spans.insert(
                    0,
                    Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                );
                lines.push(input_line);
                line_idx += 1;
            }
        }

        if file.is_too_large {
            let indicator = cursor_indicator_spaced(line_idx, current_line_idx);
            lines.push(Line::from(vec![
                Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                Span::styled("(file too large to display)", styles::dim_style(&app.theme)),
            ]));
            line_idx += 1;
        } else if file.is_binary {
            let indicator = cursor_indicator_spaced(line_idx, current_line_idx);
            lines.push(Line::from(vec![
                Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                Span::styled("(binary file)", styles::dim_style(&app.theme)),
            ]));
            line_idx += 1;
        } else if file.hunks.is_empty() {
            let indicator = cursor_indicator_spaced(line_idx, current_line_idx);
            lines.push(Line::from(vec![
                Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                Span::styled("(no changes)", styles::dim_style(&app.theme)),
            ]));
            line_idx += 1;
        } else {
            // Get line comments for this file
            let line_comments = app.engine.line_comments_for(path);

            for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
                // Calculate and render gap before this hunk
                let prev_hunk = if hunk_idx > 0 {
                    file.hunks.get(hunk_idx - 1)
                } else {
                    None
                };
                let gap = calculate_gap(
                    prev_hunk.map(|h| (&h.new_start, &h.new_count)),
                    hunk.new_start,
                );

                let gap_id = GapId { file_idx, hunk_idx };

                if gap > 0 {
                    let top_lines = app.gaps.expanded_top.get(&gap_id);
                    let bot_lines = app.gaps.expanded_bottom.get(&gap_id);
                    let top_len = top_lines.map_or(0, std::vec::Vec::len);
                    let bot_len = bot_lines.map_or(0, std::vec::Vec::len);
                    let remaining = (gap as usize).saturating_sub(top_len + bot_len);
                    let is_top_of_file = hunk_idx == 0;

                    // Render top expanded lines
                    if let Some(top) = top_lines {
                        for expanded_line in top {
                            render_expanded_context_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                expanded_line,
                                &app.theme,
                            );
                        }
                    }

                    // Render expanders / hidden lines
                    if remaining > 0 {
                        if is_top_of_file {
                            if remaining > GAP_EXPAND_BATCH {
                                render_hidden_lines(
                                    &mut lines,
                                    &mut line_idx,
                                    current_line_idx,
                                    remaining,
                                    &app.theme,
                                );
                            }
                            render_expander_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                ExpandDirection::Up,
                                remaining,
                                &app.theme,
                            );
                        } else if remaining >= GAP_EXPAND_BATCH {
                            render_expander_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                ExpandDirection::Down,
                                remaining,
                                &app.theme,
                            );
                            render_hidden_lines(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                remaining,
                                &app.theme,
                            );
                            render_expander_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                ExpandDirection::Up,
                                remaining,
                                &app.theme,
                            );
                        } else {
                            render_expander_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                ExpandDirection::Both,
                                remaining,
                                &app.theme,
                            );
                        }
                    }

                    // Render bottom expanded lines
                    if let Some(bot) = bot_lines {
                        for expanded_line in bot {
                            render_expanded_context_line(
                                &mut lines,
                                &mut line_idx,
                                current_line_idx,
                                expanded_line,
                                &app.theme,
                            );
                        }
                    }
                }

                // Hunk header
                let hunk_risk_band = if app.risk_border_colors {
                    Some(travelagent_core::risk::RiskBand::for_score(
                        travelagent_core::risk::score_hunk(path.as_path(), hunk, &app.risk_config),
                    ))
                } else {
                    None
                };
                let indicator = cursor_indicator_spaced(line_idx, current_line_idx);
                lines.push(Line::from(vec![
                    Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                    Span::styled(
                        hunk.header.clone(),
                        styles::diff_hunk_header_style_with_risk(&app.theme, hunk_risk_band),
                    ),
                ]));
                line_idx += 1;

                // Build a per-hunk pairing map so paired (deletion, addition)
                // rows can be word-highlighted. `paired_partner[idx]` holds
                // the partner's hunk-local index when the line was paired by
                // `pair_deletions_with_additions`.
                let paired_partner: Vec<Option<usize>> = if app.word_diff_enabled {
                    let mut map = vec![None; hunk.lines.len()];
                    for (left, right) in travelagent_core::diff::pair_deletions_with_additions(hunk)
                    {
                        if let (Some(del_idx), Some(add_idx)) = (left, right) {
                            map[del_idx] = Some(add_idx);
                            map[add_idx] = Some(del_idx);
                        }
                    }
                    map
                } else {
                    Vec::new()
                };

                // Diff lines
                for (line_idx_in_hunk, diff_line) in hunk.lines.iter().enumerate() {
                    let (prefix, base_style) = match diff_line.origin {
                        LineOrigin::Addition => ("+", styles::diff_add_style(&app.theme)),
                        LineOrigin::Deletion => ("-", styles::diff_del_style(&app.theme)),
                        LineOrigin::Context => (" ", styles::diff_context_style(&app.theme)),
                    };

                    // Check if this line is in visual selection
                    let is_in_visual_selection = {
                        let line_num = match diff_line.origin {
                            LineOrigin::Addition | LineOrigin::Context => diff_line.new_lineno,
                            LineOrigin::Deletion => diff_line.old_lineno,
                        };
                        let side = match diff_line.origin {
                            LineOrigin::Addition | LineOrigin::Context => LineSide::New,
                            LineOrigin::Deletion => LineSide::Old,
                        };
                        line_num.is_some_and(|ln| app.is_line_in_visual_selection(ln, side))
                    };

                    // Apply visual selection highlighting if applicable
                    let style = if is_in_visual_selection {
                        base_style.patch(styles::visual_selection_style(&app.theme))
                    } else {
                        base_style
                    };

                    let line_num_str = match diff_line.origin {
                        LineOrigin::Addition => diff_line
                            .new_lineno
                            .map_or_else(|| "     ".to_string(), |n| format!("{n:>4} ")),
                        LineOrigin::Deletion => diff_line
                            .old_lineno
                            .map_or_else(|| "     ".to_string(), |n| format!("{n:>4} ")),
                        _ => diff_line
                            .new_lineno
                            .or(diff_line.old_lineno)
                            .map_or_else(|| "     ".to_string(), |n| format!("{n:>4} ")),
                    };

                    let indicator = cursor_indicator(line_idx, current_line_idx);

                    // Build line spans - use syntax highlighting if available
                    let line_num_style = if is_in_visual_selection {
                        styles::gutter_style(&app.theme)
                            .patch(styles::visual_selection_style(&app.theme))
                    } else {
                        styles::gutter_style(&app.theme)
                    };

                    let mut line_spans = vec![
                        Span::styled(indicator, styles::current_line_indicator_style(&app.theme)),
                        Span::styled(line_num_str, line_num_style),
                        Span::styled(format!("{prefix} "), style),
                    ];

                    // Add content spans.
                    //
                    // Word-diff is applied when all of the following hold:
                    //  * `word_diff_enabled` is true
                    //  * this line is paired with a partner from the opposite side
                    //  * the line is an addition or deletion
                    //
                    // When syntax-highlighted spans are also present, we
                    // overlay word-diff emphasis (background + BOLD) on top
                    // of the syntax foreground colors — GitHub-style.
                    let partner_idx = paired_partner
                        .get(line_idx_in_hunk)
                        .copied()
                        .unwrap_or(None);
                    let should_word_diff = app.word_diff_enabled
                        && partner_idx.is_some()
                        && matches!(
                            diff_line.origin,
                            LineOrigin::Addition | LineOrigin::Deletion
                        );

                    if let Some(ref highlighted) = diff_line.highlighted_spans {
                        // Syntax-highlighted line. If word-diff also applies,
                        // overlay the emphasis background + BOLD on the byte
                        // ranges the LCS flagged as changed — preserving the
                        // syntax foreground colors.
                        let overlay_chunks = if should_word_diff {
                            let partner = partner_idx.expect("checked above");
                            let partner_line = &hunk.lines[partner];
                            let (old_content, new_content) =
                                if diff_line.origin == LineOrigin::Deletion {
                                    (diff_line.content.as_str(), partner_line.content.as_str())
                                } else {
                                    (partner_line.content.as_str(), diff_line.content.as_str())
                                };
                            let (old_tokens, new_tokens) =
                                travelagent_core::diff::highlight_line_pair(
                                    old_content,
                                    new_content,
                                );
                            let tokens = if diff_line.origin == LineOrigin::Deletion {
                                old_tokens
                            } else {
                                new_tokens
                            };
                            Some(super::word_diff_overlay::overlay_word_diff_on_syntax(
                                highlighted,
                                &tokens,
                            ))
                        } else {
                            None
                        };

                        if let Some(chunks) = overlay_chunks {
                            let emphasis_bg = match diff_line.origin {
                                LineOrigin::Addition => app.theme.syntax_add_bg,
                                LineOrigin::Deletion => app.theme.syntax_del_bg,
                                LineOrigin::Context => app.theme.panel_bg,
                            };
                            for chunk in chunks {
                                let mut chunk_style = styles::style_hint_to_ratatui(chunk.hint);
                                if chunk.is_changed {
                                    chunk_style =
                                        chunk_style.bg(emphasis_bg).add_modifier(Modifier::BOLD);
                                }
                                if is_in_visual_selection {
                                    chunk_style = chunk_style
                                        .patch(styles::visual_selection_style(&app.theme));
                                }
                                line_spans.push(Span::styled(chunk.text, chunk_style));
                            }
                        } else {
                            // No word-diff overlay: keep the syntax colors verbatim.
                            for (span_hint, span_text) in highlighted {
                                let base = styles::style_hint_to_ratatui(*span_hint);
                                let final_style = if is_in_visual_selection {
                                    base.patch(styles::visual_selection_style(&app.theme))
                                } else {
                                    base
                                };
                                line_spans.push(Span::styled(span_text.clone(), final_style));
                            }
                        }
                    } else if should_word_diff {
                        // Paired line without syntax spans: emit per-token spans
                        // with a stronger background on the changed tokens.
                        let partner = partner_idx.expect("checked above");
                        let partner_line = &hunk.lines[partner];
                        let (old_content, new_content) = if diff_line.origin == LineOrigin::Deletion
                        {
                            (diff_line.content.as_str(), partner_line.content.as_str())
                        } else {
                            (partner_line.content.as_str(), diff_line.content.as_str())
                        };
                        let (old_tokens, new_tokens) =
                            travelagent_core::diff::highlight_line_pair(old_content, new_content);
                        let tokens = if diff_line.origin == LineOrigin::Deletion {
                            old_tokens
                        } else {
                            new_tokens
                        };
                        let emphasis_bg = match diff_line.origin {
                            LineOrigin::Addition => app.theme.syntax_add_bg,
                            LineOrigin::Deletion => app.theme.syntax_del_bg,
                            LineOrigin::Context => app.theme.panel_bg,
                        };
                        for token in tokens {
                            let mut tok_style = style;
                            if token.highlight {
                                tok_style = tok_style.bg(emphasis_bg).add_modifier(Modifier::BOLD);
                            }
                            if is_in_visual_selection {
                                tok_style =
                                    tok_style.patch(styles::visual_selection_style(&app.theme));
                            }
                            line_spans.push(Span::styled(token.text, tok_style));
                        }
                    } else {
                        // Fall back to default diff styling.
                        line_spans.push(Span::styled(
                            expand_tabs(&diff_line.content, app.tab_width),
                            style,
                        ));
                    }

                    // Mark add/del lines with their effective EOL style so we can paint full
                    // row backgrounds later (including wrapped visual rows).
                    if matches!(
                        diff_line.origin,
                        LineOrigin::Addition | LineOrigin::Deletion
                    ) {
                        let eol_style = match diff_line.highlighted_spans.as_ref() {
                            // For syntax-highlighted lines (including empty highlighted lines),
                            // use syntax diff background so row fill matches code spans.
                            Some(_) => {
                                let syntax_bg = match diff_line.origin {
                                    LineOrigin::Addition => app.theme.syntax_add_bg,
                                    LineOrigin::Deletion => app.theme.syntax_del_bg,
                                    LineOrigin::Context => app.theme.panel_bg,
                                };
                                let base = line_spans.last().map_or(style, |s| s.style);
                                base.bg(syntax_bg)
                            }
                            // Non-highlighted lines keep classic diff background.
                            None => line_spans.last().map_or(style, |s| s.style),
                        };
                        // Zero-width marker span carrying the background style.
                        line_spans.push(Span::styled(String::new(), eol_style));
                    }

                    lines.push(Line::from(line_spans));
                    line_idx += 1;

                    // Show line comments for both old side (deleted lines) and new side (added/context)
                    // Old side comments (for deleted lines)
                    if let Some(old_ln) = diff_line.old_lineno {
                        // Check if we're adding/editing a comment on this line (old side)
                        let is_line_comment_mode = app.nav.input_mode == InputMode::Comment
                            && !app.comment.is_file_level
                            && file_idx == app.diff_state.current_file_idx
                            && app.comment.line == Some((old_ln, LineSide::Old));

                        if let Some(comments) = line_comments.get(&old_ln) {
                            for comment in comments {
                                if comment.side == Some(LineSide::Old) {
                                    // Skip if this comment is being edited
                                    let is_being_edited = is_line_comment_mode
                                        && app.comment.editing_id.as_ref() == Some(&comment.id);

                                    if is_being_edited {
                                        let line_range = app
                                            .comment
                                            .line_range
                                            .map(|(r, _)| r)
                                            .or_else(|| Some(LineRange::single(old_ln)));
                                        let (input_lines, cursor_info) =
                                            comment_panel::format_comment_input_lines(
                                                &app.theme,
                                                comment_type_presentation(
                                                    app,
                                                    &app.comment.comment_type,
                                                ),
                                                &app.comment.buffer,
                                                app.comment.cursor,
                                                line_range,
                                                true,
                                                app.supports_keyboard_enhancement,
                                            );
                                        comment_cursor_logical_line =
                                            Some(line_idx + cursor_info.line_offset);
                                        comment_cursor_column = 1 + cursor_info.column;
                                        comment_input_box_range = Some((
                                            line_idx,
                                            line_idx + input_lines.len().saturating_sub(1),
                                        ));

                                        for mut input_line in input_lines {
                                            let indicator =
                                                cursor_indicator(line_idx, current_line_idx);
                                            input_line.spans.insert(
                                                0,
                                                Span::styled(
                                                    indicator,
                                                    styles::current_line_indicator_style(
                                                        &app.theme,
                                                    ),
                                                ),
                                            );
                                            lines.push(input_line);
                                            line_idx += 1;
                                        }
                                    } else {
                                        let line_range = comment
                                            .line_range
                                            .or_else(|| Some(LineRange::single(old_ln)));
                                        let comment_lines = comment_panel::format_comment_lines(
                                            &app.theme,
                                            comment_type_presentation(app, &comment.comment_type),
                                            &comment.content,
                                            line_range,
                                        );
                                        for mut comment_line in comment_lines {
                                            let is_current = line_idx == current_line_idx;
                                            let indicator = if is_current { "" } else { " " };
                                            comment_line.spans.insert(
                                                0,
                                                Span::styled(
                                                    indicator,
                                                    styles::current_line_indicator_style(
                                                        &app.theme,
                                                    ),
                                                ),
                                            );
                                            lines.push(comment_line);
                                            line_idx += 1;
                                        }
                                    }
                                }
                            }
                        }

                        // Render inline input for new line comment (old side)
                        if is_line_comment_mode && app.comment.editing_id.is_none() {
                            let line_range = app
                                .comment
                                .line_range
                                .map(|(r, _)| r)
                                .or_else(|| Some(LineRange::single(old_ln)));
                            let (input_lines, cursor_info) =
                                comment_panel::format_comment_input_lines(
                                    &app.theme,
                                    comment_type_presentation(app, &app.comment.comment_type),
                                    &app.comment.buffer,
                                    app.comment.cursor,
                                    line_range,
                                    false,
                                    app.supports_keyboard_enhancement,
                                );
                            comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
                            comment_cursor_column = 1 + cursor_info.column;
                            comment_input_box_range =
                                Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

                            for mut input_line in input_lines {
                                let indicator = cursor_indicator(line_idx, current_line_idx);
                                input_line.spans.insert(
                                    0,
                                    Span::styled(
                                        indicator,
                                        styles::current_line_indicator_style(&app.theme),
                                    ),
                                );
                                lines.push(input_line);
                                line_idx += 1;
                            }
                        }
                    }

                    // New side comments (for added/context lines)
                    if let Some(new_ln) = diff_line.new_lineno {
                        // Check if we're adding/editing a comment on this line (new side)
                        let is_line_comment_mode = app.nav.input_mode == InputMode::Comment
                            && !app.comment.is_file_level
                            && file_idx == app.diff_state.current_file_idx
                            && app.comment.line == Some((new_ln, LineSide::New));

                        if let Some(comments) = line_comments.get(&new_ln) {
                            for comment in comments {
                                if comment.side != Some(LineSide::Old) {
                                    // Skip if this comment is being edited
                                    let is_being_edited = is_line_comment_mode
                                        && app.comment.editing_id.as_ref() == Some(&comment.id);

                                    if is_being_edited {
                                        let line_range = app
                                            .comment
                                            .line_range
                                            .map(|(r, _)| r)
                                            .or_else(|| Some(LineRange::single(new_ln)));
                                        let (input_lines, cursor_info) =
                                            comment_panel::format_comment_input_lines(
                                                &app.theme,
                                                comment_type_presentation(
                                                    app,
                                                    &app.comment.comment_type,
                                                ),
                                                &app.comment.buffer,
                                                app.comment.cursor,
                                                line_range,
                                                true,
                                                app.supports_keyboard_enhancement,
                                            );
                                        comment_cursor_logical_line =
                                            Some(line_idx + cursor_info.line_offset);
                                        comment_cursor_column = 1 + cursor_info.column;
                                        comment_input_box_range = Some((
                                            line_idx,
                                            line_idx + input_lines.len().saturating_sub(1),
                                        ));

                                        for mut input_line in input_lines {
                                            let indicator =
                                                cursor_indicator(line_idx, current_line_idx);
                                            input_line.spans.insert(
                                                0,
                                                Span::styled(
                                                    indicator,
                                                    styles::current_line_indicator_style(
                                                        &app.theme,
                                                    ),
                                                ),
                                            );
                                            lines.push(input_line);
                                            line_idx += 1;
                                        }
                                    } else {
                                        let line_range = comment
                                            .line_range
                                            .or_else(|| Some(LineRange::single(new_ln)));
                                        let comment_lines = comment_panel::format_comment_lines(
                                            &app.theme,
                                            comment_type_presentation(app, &comment.comment_type),
                                            &comment.content,
                                            line_range,
                                        );
                                        for mut comment_line in comment_lines {
                                            let indicator =
                                                cursor_indicator(line_idx, current_line_idx);
                                            comment_line.spans.insert(
                                                0,
                                                Span::styled(
                                                    indicator,
                                                    styles::current_line_indicator_style(
                                                        &app.theme,
                                                    ),
                                                ),
                                            );
                                            lines.push(comment_line);
                                            line_idx += 1;
                                        }
                                    }
                                }
                            }
                        }

                        // Render inline input for new line comment (new side)
                        if is_line_comment_mode && app.comment.editing_id.is_none() {
                            let line_range = app
                                .comment
                                .line_range
                                .map(|(r, _)| r)
                                .or_else(|| Some(LineRange::single(new_ln)));
                            let (input_lines, cursor_info) =
                                comment_panel::format_comment_input_lines(
                                    &app.theme,
                                    comment_type_presentation(app, &app.comment.comment_type),
                                    &app.comment.buffer,
                                    app.comment.cursor,
                                    line_range,
                                    false,
                                    app.supports_keyboard_enhancement,
                                );
                            comment_cursor_logical_line = Some(line_idx + cursor_info.line_offset);
                            comment_cursor_column = 1 + cursor_info.column;
                            comment_input_box_range =
                                Some((line_idx, line_idx + input_lines.len().saturating_sub(1)));

                            for mut input_line in input_lines {
                                let indicator = cursor_indicator(line_idx, current_line_idx);
                                input_line.spans.insert(
                                    0,
                                    Span::styled(
                                        indicator,
                                        styles::current_line_indicator_style(&app.theme),
                                    ),
                                );
                                lines.push(input_line);
                                line_idx += 1;
                            }
                        }
                    }
                }
            }
        }

        // Spacing between files
        let indicator = cursor_indicator(line_idx, current_line_idx);
        lines.push(Line::from(Span::styled(
            indicator,
            styles::current_line_indicator_style(&app.theme),
        )));
        line_idx += 1;
    }

    // Auto-scroll so the comment input box stays visible while the user types.
    // Without this, adding a comment near the bottom/top of the viewport would
    // place the input box off-screen and the user couldn't see what they type.
    scroll_comment_input_into_view(
        &mut app.diff_state.scroll_offset,
        comment_input_box_range,
        comment_cursor_logical_line,
        inner.height as usize,
        lines.len(),
    );

    let visible_lines_unscrolled: Vec<Line> = lines
        .into_iter()
        .skip(app.diff_state.scroll_offset)
        .take(inner.height as usize)
        .collect();

    // Calculate the width of each line for max_content_width and visible line count
    let line_widths: Vec<usize> = visible_lines_unscrolled
        .iter()
        .map(|line| {
            line.spans
                .iter()
                .map(|span| span.content.width())
                .sum::<usize>()
        })
        .collect();

    let max_content_width = line_widths.iter().copied().max().unwrap_or(0);

    app.diff_state.viewport_width = inner.width as usize;
    app.diff_state.max_content_width = max_content_width;

    // Calculate how many logical lines actually fit in the viewport when wrapped
    let viewport_width = inner.width as usize;
    let viewport_height = inner.height as usize;
    app.diff_state.visible_line_count = if app.diff_state.wrap_lines && viewport_width > 0 {
        let mut visual_rows_used = 0;
        let mut logical_lines_visible = 0;
        for &width in &line_widths {
            // Each line takes at least 1 row, plus extra rows if it wraps
            let rows_for_line = if width == 0 {
                1
            } else {
                width.div_ceil(viewport_width)
            };
            if visual_rows_used + rows_for_line > viewport_height {
                break;
            }
            visual_rows_used += rows_for_line;
            logical_lines_visible += 1;
        }
        logical_lines_visible.max(1)
    } else {
        viewport_height
    };

    let max_scroll_x = max_content_width.saturating_sub(inner.width as usize);
    if app.diff_state.scroll_x > max_scroll_x {
        app.diff_state.scroll_x = max_scroll_x;
    }
    if app.diff_state.wrap_lines {
        app.diff_state.scroll_x = 0;
    }

    let scroll_x = app.diff_state.scroll_x;
    let visible_lines_unscrolled_for_bg = visible_lines_unscrolled.clone();
    let visible_lines: Vec<Line> = if app.diff_state.wrap_lines {
        visible_lines_unscrolled
    } else {
        visible_lines_unscrolled
            .into_iter()
            .map(|line| apply_horizontal_scroll(line, scroll_x))
            .collect()
    };

    // Paint per-visual-row add/del backgrounds across full row width.
    paint_unified_diff_row_backgrounds(
        frame,
        inner,
        &visible_lines_unscrolled_for_bg,
        &line_widths,
        app.diff_state.wrap_lines,
        inner.width as usize,
        &app.theme,
    );

    // Keep paragraph bg unset so pre-painted per-row diff backgrounds remain visible.
    let mut diff = Paragraph::new(visible_lines).style(Style::default().fg(app.theme.fg_primary));
    if app.diff_state.wrap_lines {
        diff = diff.wrap(Wrap { trim: false });
    }
    frame.render_widget(diff, inner);

    // Calculate screen position for comment cursor if in Comment mode
    if let Some(cursor_logical_line) = comment_cursor_logical_line {
        let scroll_offset = app.diff_state.scroll_offset;
        // Use visible_line_count which accounts for line wrapping
        let visible_lines_count = app.diff_state.visible_line_count.max(1);

        // Check if the cursor line is visible (after scrolling)
        if cursor_logical_line >= scroll_offset
            && cursor_logical_line < scroll_offset + visible_lines_count
        {
            // Calculate screen row - need to account for wrapping
            let logical_offset = cursor_logical_line - scroll_offset;

            // Calculate visual row by summing wrapped line heights
            let mut visual_row: u16 = 0;
            let viewport_width = inner.width as usize;

            if app.diff_state.wrap_lines && viewport_width > 0 {
                // Calculate how many visual rows the lines before cursor take
                // Note: line_widths is indexed from 0 and corresponds to visible lines
                // (i.e., line_widths[0] is the first visible line after scroll)
                for i in 0..logical_offset {
                    if i < line_widths.len() {
                        let width = line_widths[i];
                        let rows = if width == 0 {
                            1
                        } else {
                            width.div_ceil(viewport_width)
                        };
                        visual_row += rows as u16;
                    } else {
                        visual_row += 1;
                    }
                }
            } else {
                visual_row = logical_offset as u16;
            }

            // Account for diff area position (inner starts at diff block's inner area)
            let screen_col = inner.x + comment_cursor_column;
            let screen_row_abs = inner.y + visual_row;

            app.comment.cursor_screen_pos = Some((screen_col, screen_row_abs));
        }
    }
}
fn unified_line_bg_style(line: &Line, theme: &Theme) -> Option<Style> {
    let prefix = line.spans.get(2)?.content.as_ref();
    let default_bg = match prefix {
        "+ " => theme.diff_add_bg,
        "- " => theme.diff_del_bg,
        _ => return None,
    };

    let bg = line
        .spans
        .last()
        .and_then(|span| span.style.bg)
        .unwrap_or(default_bg);

    Some(Style::default().bg(bg))
}

fn paint_unified_diff_row_backgrounds(
    frame: &mut Frame,
    inner: Rect,
    visible_lines_unscrolled: &[Line],
    line_widths: &[usize],
    wrap_lines: bool,
    viewport_width: usize,
    theme: &Theme,
) {
    let mut visual_row: usize = 0;

    for (idx, line) in visible_lines_unscrolled.iter().enumerate() {
        if visual_row >= inner.height as usize {
            break;
        }

        let rows_for_line = if wrap_lines && viewport_width > 0 {
            let width = line_widths.get(idx).copied().unwrap_or(0);
            if width == 0 {
                1
            } else {
                width.div_ceil(viewport_width)
            }
        } else {
            1
        };

        if let Some(row_style) = unified_line_bg_style(line, theme) {
            for _ in 0..rows_for_line {
                if visual_row >= inner.height as usize {
                    break;
                }

                let row_rect = Rect {
                    x: inner.x,
                    y: inner.y + visual_row as u16,
                    width: inner.width,
                    height: 1,
                };
                frame.buffer_mut().set_style(row_rect, row_style);
                visual_row += 1;
            }
        } else {
            visual_row += rows_for_line;
        }
    }
}