mutiny-diff 0.1.22

TUI git diff viewer with worktree management
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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
    Frame,
};

use crate::display_map::{
    build_display_map, filter_hunk_lines, DisplayRowInfo, ExpandDirection, FilteredItem,
};
use crate::git::types::{DiffLineOrigin, FileDelta};
use crate::highlight::HighlightSpan;
use crate::state::{app_state::FocusPanel, AppState, DiffViewMode};
use crate::theme::Theme;

use super::Component;

pub struct DiffView;

impl Component for DiffView {
    fn render(&self, frame: &mut Frame, area: Rect, state: &AppState) {
        let is_focused = state.focus == FocusPanel::DiffView;
        let theme = &state.theme;

        let border_style = if is_focused {
            Style::default().fg(theme.accent)
        } else {
            Style::default().fg(theme.text_muted)
        };

        let view_label = match state.diff.options.view_mode {
            DiffViewMode::Split => "Split",
            DiffViewMode::Unified => "Unified",
        };

        let Some(delta) = state.diff.selected_delta() else {
            let block = Block::default()
                .title(format!(" Diff [{view_label}] "))
                .borders(Borders::ALL)
                .border_style(border_style);

            let content = if state.diff.loading {
                " Loading..."
            } else if state.diff.deltas.is_empty() {
                " No changes detected"
            } else {
                " Select a file to view diff"
            };

            let paragraph = Paragraph::new(content)
                .style(Style::default().fg(theme.text_muted))
                .block(block);
            frame.render_widget(paragraph, area);
            return;
        };

        match state.diff.options.view_mode {
            DiffViewMode::Split => {
                render_split(frame, area, delta, state, border_style, view_label, theme)
            }
            DiffViewMode::Unified => {
                render_unified(frame, area, delta, state, border_style, view_label, theme)
            }
        }
    }
}

fn format_title(delta: &FileDelta, view_label: &str, state: &AppState) -> String {
    let path_display = delta.path.to_string_lossy();
    let base = if let Some(ref old_path) = delta.old_path {
        if *old_path != delta.path {
            let old_display = old_path.to_string_lossy();
            format!(" {old_display} \u{2192} {path_display} [{view_label}]")
        } else {
            format!(" {path_display} [{view_label}]")
        }
    } else {
        format!(" {path_display} [{view_label}]")
    };

    if state.diff.search_active || !state.diff.search_query.is_empty() {
        let match_info = if state.diff.search_matches.is_empty() {
            if state.diff.search_query.is_empty() {
                String::new()
            } else {
                " (no matches)".to_string()
            }
        } else {
            let idx = state.diff.search_match_index.map(|i| i + 1).unwrap_or(0);
            format!(" ({}/{})", idx, state.diff.search_matches.len())
        };
        {
            let q = state.diff.search_query.text();
            let ci = state.diff.search_query.cursor_char_index();
            let before: String = q.chars().take(ci).collect();
            let after: String = q.chars().skip(ci).collect();
            format!("{base} /{}\u{2588}{}{match_info} ", before, after)
        }
    } else {
        format!("{base} ")
    }
}

/// Check if a display row index is within the current visual selection range.
fn is_row_selected(state: &AppState, display_row: usize) -> bool {
    if !state.selection.active {
        return false;
    }
    let (start, end) = state.selection.range();
    display_row >= start && display_row <= end
}

/// Check if a display row is the cursor row (when not in visual selection mode).
fn is_cursor_row(state: &AppState, display_row: usize) -> bool {
    !state.selection.active
        && state.focus == FocusPanel::DiffView
        && display_row == state.diff.cursor_row
}

/// Per-row highlight: separates gutter indicator from content background.
#[derive(Clone, Copy, Default)]
struct RowHighlight {
    /// Background for the gutter/line-number area.
    gutter_bg: Option<Color>,
    /// Foreground for the gutter (overrides text_muted when set).
    gutter_fg: Option<Color>,
    /// Background override for content area. When set, replaces diff_bg.
    content_bg: Option<Color>,
}

struct WrapConfig<'a> {
    width: u16,
    gutter_width: usize,
    wrap_enabled: bool,
    theme: &'a Theme,
}

pub(crate) struct VisualRowMetrics {
    pub row_offsets: Vec<usize>,
    pub row_heights: Vec<usize>,
    pub total_rows: usize,
}

/// Check if a display row is a search match.
fn is_search_match(state: &AppState, display_row: usize) -> bool {
    !state.diff.search_query.is_empty()
        && state
            .diff
            .search_matches
            .binary_search(&display_row)
            .is_ok()
}

/// Compute row highlight for cursor or visual selection.
fn row_highlight(state: &AppState, display_row: usize) -> RowHighlight {
    let theme = &state.theme;
    if is_row_selected(state, display_row) {
        let bg = Some(theme.visual_select_bg);
        RowHighlight {
            gutter_bg: bg,
            gutter_fg: None,
            content_bg: bg,
        }
    } else if is_cursor_row(state, display_row) {
        RowHighlight {
            gutter_bg: Some(theme.accent),
            gutter_fg: Some(Color::Black),
            content_bg: None,
        }
    } else if is_search_match(state, display_row) {
        RowHighlight {
            gutter_bg: None,
            gutter_fg: None,
            content_bg: Some(theme.search_match_bg),
        }
    } else {
        RowHighlight::default()
    }
}

/// Check if a line has an annotation marker in the gutter.
fn has_annotation(state: &AppState, delta: &FileDelta, row_info: &DisplayRowInfo) -> bool {
    let file_path = delta.path.to_string_lossy();
    state
        .annotations
        .has_annotation_at(&file_path, row_info.old_lineno, row_info.new_lineno)
}

/// Check if a line has a bookmark marker in the gutter, returning the optional label.
fn bookmark_label(
    state: &AppState,
    delta: &FileDelta,
    row_info: &DisplayRowInfo,
) -> Option<Option<char>> {
    let file_path = delta.path.to_string_lossy();
    state
        .bookmarks
        .label_at(&file_path, row_info.old_lineno, row_info.new_lineno)
}

/// Get the score at a line position, if any.
fn get_score(state: &AppState, delta: &FileDelta, row_info: &DisplayRowInfo) -> Option<u8> {
    let file_path = delta.path.to_string_lossy();
    state
        .annotations
        .score_at(&file_path, row_info.old_lineno, row_info.new_lineno)
}

/// Get the color for a score value.
fn score_color(score: u8) -> Color {
    match score {
        1 => Color::Red,
        2 => Color::Rgb(255, 165, 0), // Orange
        3 => Color::Yellow,
        4 => Color::Rgb(144, 238, 144), // Light green
        5 => Color::Green,
        _ => Color::Gray,
    }
}

fn render_split(
    frame: &mut Frame,
    area: Rect,
    delta: &FileDelta,
    state: &AppState,
    border_style: Style,
    view_label: &str,
    theme: &Theme,
) {
    let title = format_title(delta, view_label, state);

    if delta.binary {
        let block = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_style(border_style);
        let msg = Paragraph::new(" Binary file differs")
            .style(Style::default().fg(theme.text_muted))
            .block(block);
        frame.render_widget(msg, area);
        return;
    }

    let outer_block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(border_style);
    let inner = outer_block.inner(area);
    frame.render_widget(outer_block, area);

    // 3-column layout: left content | center gutter | right content
    // Center gutter: "NNNNN NNNNN " = 5 + 1 + 5 + 1 = 12 chars
    let gutter_width_chars: u16 = 12;
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Min(10),
            Constraint::Length(gutter_width_chars),
            Constraint::Min(10),
        ])
        .split(inner);

    let old_hl = &state.diff.old_highlights;
    let new_hl = &state.diff.new_highlights;

    // Build display map for selection/annotation checking
    let display_map = build_display_map(
        delta,
        DiffViewMode::Split,
        state.diff.display_context,
        &state.diff.gap_expansions,
    );

    let (left_lines, center_lines, right_lines) = build_split_lines(
        delta,
        state.diff.scroll_offset,
        inner.height as usize,
        old_hl,
        new_hl,
        state,
        &display_map,
        cols[0].width,
        true,
        theme,
    );

    let left_para = Paragraph::new(left_lines);
    let center_para = Paragraph::new(center_lines);
    let right_para = Paragraph::new(right_lines);

    frame.render_widget(left_para, cols[0]);
    frame.render_widget(center_para, cols[1]);
    frame.render_widget(right_para, cols[2]);
}

#[allow(clippy::too_many_arguments)]
fn build_split_lines<'a>(
    delta: &'a FileDelta,
    scroll: usize,
    height: usize,
    old_hl: &[Vec<HighlightSpan>],
    new_hl: &[Vec<HighlightSpan>],
    state: &AppState,
    display_map: &[DisplayRowInfo],
    width: u16,
    wrap_enabled: bool,
    theme: &Theme,
) -> (Vec<Line<'a>>, Vec<Line<'a>>, Vec<Line<'a>>) {
    let (left_lines, center_lines, right_lines) =
        build_split_lines_core(delta, old_hl, new_hl, state, display_map, theme);

    let config = WrapConfig {
        width,
        gutter_width: 0,
        wrap_enabled,
        theme,
    };
    wrap_split_lines_synchronized_with_scroll(
        left_lines,
        center_lines,
        right_lines,
        &config,
        scroll,
        height,
    )
}

fn render_unified(
    frame: &mut Frame,
    area: Rect,
    delta: &FileDelta,
    state: &AppState,
    border_style: Style,
    view_label: &str,
    theme: &Theme,
) {
    let title = format_title(delta, view_label, state);

    if delta.binary {
        let block = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_style(border_style);
        let msg = Paragraph::new(" Binary file differs")
            .style(Style::default().fg(theme.text_muted))
            .block(block);
        frame.render_widget(msg, area);
        return;
    }

    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .border_style(border_style);
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let old_hl = &state.diff.old_highlights;
    let new_hl = &state.diff.new_highlights;

    // Build display map for selection/annotation checking
    let display_map = build_display_map(
        delta,
        DiffViewMode::Unified,
        state.diff.display_context,
        &state.diff.gap_expansions,
    );

    let lines = build_unified_lines_core(delta, old_hl, new_hl, state, &display_map, theme);
    // Unified gutter: old_lineno(5) + space(1) + new_lineno(5) + marker(1) + prefix(1) = 13
    let config = WrapConfig {
        width: inner.width,
        gutter_width: 5 + 1 + 5 + 1 + 1,
        wrap_enabled: true,
        theme,
    };
    let wrapped = wrap_lines_for_display_with_scroll(
        lines,
        &config,
        state.diff.scroll_offset,
        inner.height as usize,
    );
    let paragraph = Paragraph::new(wrapped);
    frame.render_widget(paragraph, inner);
}

fn build_split_lines_core<'a>(
    delta: &'a FileDelta,
    old_hl: &[Vec<HighlightSpan>],
    new_hl: &[Vec<HighlightSpan>],
    state: &AppState,
    display_map: &[DisplayRowInfo],
    theme: &Theme,
) -> (Vec<Line<'a>>, Vec<Line<'a>>, Vec<Line<'a>>) {
    let mut left: Vec<Line> = Vec::new();
    let mut center: Vec<Line> = Vec::new();
    let mut right: Vec<Line> = Vec::new();
    let mut display_row: usize = 0;

    let gutter_width = 5;
    let mut gap_id_offset = 0;

    for hunk in &delta.hunks {
        let hl = row_highlight(state, display_row);
        let ann_marker = display_map
            .get(display_row)
            .is_some_and(|info| has_annotation(state, delta, info));

        let marker = if ann_marker { "\u{2502}" } else { " " };
        let hunk_gutter = format!("{:>gutter_width$} {:>gutter_width$}{marker}", "...", "...");
        let mut gutter_style = Style::default().fg(theme.text_muted);
        if let Some(fg) = hl.gutter_fg {
            gutter_style = gutter_style.fg(fg);
        }
        if let Some(bg) = hl.gutter_bg {
            gutter_style = gutter_style.bg(bg);
        }

        let score = display_map
            .get(display_row)
            .and_then(|info| get_score(state, delta, info));
        let mut hunk_spans = Vec::new();
        if let Some(s) = score {
            hunk_spans.push(Span::styled("", Style::default().fg(score_color(s))));
        }
        hunk_spans.push(Span::styled(hunk_gutter, gutter_style));
        center.push(Line::from(hunk_spans));

        let mut content_style = Style::default().fg(theme.text_muted);
        if let Some(bg) = hl.content_bg {
            content_style = content_style.bg(bg);
        }
        left.push(Line::from(Span::styled(hunk.header.clone(), content_style)));
        right.push(Line::from(Span::styled("", content_style)));
        display_row += 1;

        let (items, next_offset) = filter_hunk_lines(
            &hunk.lines,
            state.diff.display_context,
            &state.diff.gap_expansions,
            gap_id_offset,
        );
        gap_id_offset = next_offset;

        let mut i = 0;
        while i < items.len() {
            match &items[i] {
                FilteredItem::CollapsedIndicator {
                    hidden_count,
                    direction,
                    ..
                } => {
                    let hl = row_highlight(state, display_row);

                    // Center gutter: ellipsis
                    let collapsed_gutter = format!(
                        "{:>gutter_width$} {:>gutter_width$} ",
                        "\u{22ef}", "\u{22ef}"
                    );
                    let mut gutter_style = Style::default().fg(theme.text_muted);
                    if let Some(fg) = hl.gutter_fg {
                        gutter_style = gutter_style.fg(fg);
                    }
                    if let Some(bg) = hl.gutter_bg {
                        gutter_style = gutter_style.bg(bg);
                    }

                    let score = display_map
                        .get(display_row)
                        .and_then(|info| get_score(state, delta, info));
                    let mut collapsed_spans = Vec::new();
                    if let Some(s) = score {
                        collapsed_spans
                            .push(Span::styled("", Style::default().fg(score_color(s))));
                    }
                    collapsed_spans.push(Span::styled(collapsed_gutter, gutter_style));
                    center.push(Line::from(collapsed_spans));

                    let mut content_style = Style::default().fg(theme.text_muted);
                    if let Some(bg) = hl.content_bg {
                        content_style = content_style.bg(bg);
                    }
                    let caret = match direction {
                        ExpandDirection::Down => "\u{25bc}",
                        ExpandDirection::Up => "\u{25b2}",
                    };
                    let label = format!("{caret} {hidden_count} lines hidden {caret}");
                    left.push(Line::from(Span::styled(label, content_style)));
                    right.push(Line::from(Span::styled("", content_style)));

                    display_row += 1;
                    i += 1;
                }
                FilteredItem::Line { line, .. } => match line.origin {
                    DiffLineOrigin::Context => {
                        let hl = row_highlight(state, display_row);
                        let ann_marker = display_map
                            .get(display_row)
                            .is_some_and(|info| has_annotation(state, delta, info));

                        let gutter_l = format_lineno(line.old_lineno, gutter_width);
                        let gutter_r = format_lineno(line.new_lineno, gutter_width);
                        let marker = if ann_marker { "\u{2502}" } else { " " };
                        let score = display_map
                            .get(display_row)
                            .and_then(|info| get_score(state, delta, info));
                        let bm_label = display_map
                            .get(display_row)
                            .and_then(|info| bookmark_label(state, delta, info));
                        center.push(make_center_gutter_line(
                            &gutter_l, &gutter_r, marker, hl, theme, score, bm_label,
                        ));

                        let old_spans = line.old_lineno.and_then(|n| old_hl.get(n as usize));
                        let new_spans = line.new_lineno.and_then(|n| new_hl.get(n as usize));
                        left.push(make_content_only_line(
                            &line.content,
                            old_spans,
                            None,
                            hl,
                            theme,
                        ));
                        right.push(make_content_only_line(
                            &line.content,
                            new_spans,
                            None,
                            hl,
                            theme,
                        ));
                        display_row += 1;
                        i += 1;
                    }
                    DiffLineOrigin::Deletion => {
                        // Collect consecutive deletions from filtered items
                        let del_start = i;
                        while i < items.len() {
                            if let FilteredItem::Line { line: l, .. } = &items[i] {
                                if l.origin == DiffLineOrigin::Deletion {
                                    i += 1;
                                    continue;
                                }
                            }
                            break;
                        }
                        // Collect consecutive additions
                        let add_start = i;
                        while i < items.len() {
                            if let FilteredItem::Line { line: l, .. } = &items[i] {
                                if l.origin == DiffLineOrigin::Addition {
                                    i += 1;
                                    continue;
                                }
                            }
                            break;
                        }

                        let dels: Vec<_> = items[del_start..add_start]
                            .iter()
                            .filter_map(|item| {
                                if let FilteredItem::Line { line, .. } = item {
                                    Some(*line)
                                } else {
                                    None
                                }
                            })
                            .collect();
                        let adds: Vec<_> = items[add_start..i]
                            .iter()
                            .filter_map(|item| {
                                if let FilteredItem::Line { line, .. } = item {
                                    Some(*line)
                                } else {
                                    None
                                }
                            })
                            .collect();
                        let max = dels.len().max(adds.len());

                        for j in 0..max {
                            let hl = row_highlight(state, display_row);
                            let ann_marker = display_map
                                .get(display_row)
                                .is_some_and(|info| has_annotation(state, delta, info));
                            let marker = if ann_marker { "\u{2502}" } else { " " };

                            let old_lineno = if j < dels.len() {
                                dels[j].old_lineno
                            } else {
                                None
                            };
                            let new_lineno = if j < adds.len() {
                                adds[j].new_lineno
                            } else {
                                None
                            };
                            let gutter_l = format_lineno(old_lineno, gutter_width);
                            let gutter_r = format_lineno(new_lineno, gutter_width);
                            let score = display_map
                                .get(display_row)
                                .and_then(|info| get_score(state, delta, info));
                            let bm_label = display_map
                                .get(display_row)
                                .and_then(|info| bookmark_label(state, delta, info));
                            center.push(make_center_gutter_line(
                                &gutter_l, &gutter_r, marker, hl, theme, score, bm_label,
                            ));

                            if j < dels.len() {
                                let line = dels[j];
                                let spans = line.old_lineno.and_then(|n| old_hl.get(n as usize));
                                left.push(make_content_only_line(
                                    &line.content,
                                    spans,
                                    Some(theme.diff_del_bg),
                                    hl,
                                    theme,
                                ));
                            } else {
                                left.push(make_empty_content_line(hl, theme));
                            }

                            if j < adds.len() {
                                let line = adds[j];
                                let spans = line.new_lineno.and_then(|n| new_hl.get(n as usize));
                                right.push(make_content_only_line(
                                    &line.content,
                                    spans,
                                    Some(theme.diff_add_bg),
                                    hl,
                                    theme,
                                ));
                            } else {
                                right.push(make_empty_content_line(hl, theme));
                            }

                            display_row += 1;
                        }
                    }
                    DiffLineOrigin::Addition => {
                        let hl = row_highlight(state, display_row);
                        let ann_marker = display_map
                            .get(display_row)
                            .is_some_and(|info| has_annotation(state, delta, info));
                        let marker = if ann_marker { "\u{2502}" } else { " " };

                        let gutter_l = " ".repeat(gutter_width);
                        let gutter_r = format_lineno(line.new_lineno, gutter_width);
                        let score = display_map
                            .get(display_row)
                            .and_then(|info| get_score(state, delta, info));
                        let bm_label = display_map
                            .get(display_row)
                            .and_then(|info| bookmark_label(state, delta, info));
                        center.push(make_center_gutter_line(
                            &gutter_l, &gutter_r, marker, hl, theme, score, bm_label,
                        ));

                        left.push(make_empty_content_line(hl, theme));
                        let spans = line.new_lineno.and_then(|n| new_hl.get(n as usize));
                        right.push(make_content_only_line(
                            &line.content,
                            spans,
                            Some(theme.diff_add_bg),
                            hl,
                            theme,
                        ));
                        display_row += 1;
                        i += 1;
                    }
                },
            }
        }
    }

    (left, center, right)
}

fn build_unified_lines_core<'a>(
    delta: &'a FileDelta,
    old_hl: &[Vec<HighlightSpan>],
    new_hl: &[Vec<HighlightSpan>],
    state: &AppState,
    display_map: &[DisplayRowInfo],
    theme: &Theme,
) -> Vec<Line<'a>> {
    let gutter_width = 5;
    let mut lines: Vec<Line> = Vec::new();
    let mut display_row: usize = 0;
    let mut gap_id_offset = 0;

    for hunk in &delta.hunks {
        let hl = row_highlight(state, display_row);
        let ann_marker = display_map
            .get(display_row)
            .is_some_and(|info| has_annotation(state, delta, info));
        let score = display_map
            .get(display_row)
            .and_then(|info| get_score(state, delta, info));

        lines.push(make_hunk_header_line_unified(
            gutter_width,
            &hunk.header,
            hl,
            ann_marker,
            score,
            theme,
        ));
        display_row += 1;

        let (items, next_offset) = filter_hunk_lines(
            &hunk.lines,
            state.diff.display_context,
            &state.diff.gap_expansions,
            gap_id_offset,
        );
        gap_id_offset = next_offset;

        for item in &items {
            match item {
                FilteredItem::CollapsedIndicator {
                    hidden_count,
                    direction,
                    ..
                } => {
                    let hl = row_highlight(state, display_row);
                    let score = display_map
                        .get(display_row)
                        .and_then(|info| get_score(state, delta, info));
                    lines.push(make_collapsed_indicator_line_unified(
                        gutter_width,
                        *hidden_count,
                        *direction,
                        hl,
                        score,
                        theme,
                    ));
                    display_row += 1;
                }
                FilteredItem::Line { line, .. } => {
                    let hl = row_highlight(state, display_row);
                    let ann_marker = display_map
                        .get(display_row)
                        .is_some_and(|info| has_annotation(state, delta, info));
                    let score = display_map
                        .get(display_row)
                        .and_then(|info| get_score(state, delta, info));
                    let bm_label = display_map
                        .get(display_row)
                        .and_then(|info| bookmark_label(state, delta, info));

                    let (old_g, new_g) = (
                        format_lineno(line.old_lineno, gutter_width),
                        format_lineno(line.new_lineno, gutter_width),
                    );

                    match line.origin {
                        DiffLineOrigin::Context => {
                            let spans = line.new_lineno.and_then(|n| new_hl.get(n as usize));
                            lines.push(make_unified_highlighted(
                                &old_g,
                                &new_g,
                                " ",
                                &line.content,
                                spans,
                                None,
                                hl,
                                ann_marker,
                                score,
                                bm_label,
                                theme,
                            ));
                        }
                        DiffLineOrigin::Addition => {
                            let spans = line.new_lineno.and_then(|n| new_hl.get(n as usize));
                            let blank = " ".repeat(gutter_width);
                            lines.push(make_unified_highlighted(
                                &blank,
                                &new_g,
                                "+",
                                &line.content,
                                spans,
                                Some(theme.diff_add_bg),
                                hl,
                                ann_marker,
                                score,
                                bm_label,
                                theme,
                            ));
                        }
                        DiffLineOrigin::Deletion => {
                            let spans = line.old_lineno.and_then(|n| old_hl.get(n as usize));
                            let blank = " ".repeat(gutter_width);
                            lines.push(make_unified_highlighted(
                                &old_g,
                                &blank,
                                "-",
                                &line.content,
                                spans,
                                Some(theme.diff_del_bg),
                                hl,
                                ann_marker,
                                score,
                                bm_label,
                                theme,
                            ));
                        }
                    }
                    display_row += 1;
                }
            }
        }
    }

    lines
}

// Helper functions

fn format_lineno(lineno: Option<u32>, width: usize) -> String {
    match lineno {
        Some(n) => format!("{n:>width$}"),
        None => " ".repeat(width),
    }
}

/// Build a hunk header line for unified view.
fn make_hunk_header_line_unified<'a>(
    gutter_width: usize,
    header: &str,
    hl: RowHighlight,
    ann_marker: bool,
    score: Option<u8>,
    theme: &Theme,
) -> Line<'a> {
    let marker = if ann_marker { "\u{2502}" } else { " " };
    let gutter_text = format!("{:>gutter_width$}{marker}", "...");
    let mut gutter_style = Style::default().fg(theme.text_muted);
    if let Some(fg) = hl.gutter_fg {
        gutter_style = gutter_style.fg(fg);
    }
    if let Some(bg) = hl.gutter_bg {
        gutter_style = gutter_style.bg(bg);
    }
    let mut content_style = Style::default()
        .fg(theme.diff_hunk_header_fg)
        .add_modifier(Modifier::BOLD);
    if let Some(bg) = hl.content_bg {
        content_style = content_style.bg(bg);
    }

    let mut spans = Vec::new();
    if let Some(s) = score {
        spans.push(Span::styled("", Style::default().fg(score_color(s))));
    }
    spans.push(Span::styled(gutter_text, gutter_style));
    spans.push(Span::styled(header.to_string(), content_style));
    Line::from(spans)
}

/// Apply highlight spans to a string, blending with diff background.
fn apply_highlights<'a>(
    text: &str,
    hl_spans: &[HighlightSpan],
    bg: Option<Color>,
    theme: &Theme,
) -> Vec<Span<'a>> {
    if hl_spans.is_empty() || text.is_empty() {
        let mut style = Style::default().fg(theme.text);
        if let Some(bg_color) = bg {
            style = style.bg(bg_color);
        }
        return vec![Span::styled(text.to_string(), style)];
    }

    let mut result = Vec::new();
    let mut pos = 0;
    let text_len = text.len();

    for span in hl_spans {
        let start = span.start.min(text_len);
        let end = span.end.min(text_len);

        if start > pos {
            // Gap before this span — use default style
            let mut style = Style::default().fg(theme.diff_context_fg);
            if let Some(bg_color) = bg {
                style = style.bg(bg_color);
            }
            result.push(Span::styled(text[pos..start].to_string(), style));
        }

        if start < end {
            let mut style = span.style;
            if let Some(bg_color) = bg {
                style = style.bg(bg_color);
            }
            result.push(Span::styled(text[start..end].to_string(), style));
        }

        pos = end;
    }

    // Remaining text after last span
    if pos < text_len {
        let mut style = Style::default().fg(theme.diff_context_fg);
        if let Some(bg_color) = bg {
            style = style.bg(bg_color);
        }
        result.push(Span::styled(text[pos..].to_string(), style));
    }

    result
}

/// Build a center gutter line for split view: "{old:>5} {new:>5}{marker}"
#[allow(clippy::too_many_arguments)]
fn make_center_gutter_line<'a>(
    gutter_l: &str,
    gutter_r: &str,
    marker: &str,
    hl: RowHighlight,
    theme: &Theme,
    score: Option<u8>,
    bm_label: Option<Option<char>>,
) -> Line<'a> {
    let mut spans = Vec::new();

    // Add score dot if present
    if let Some(s) = score {
        let dot_style = Style::default().fg(score_color(s));
        spans.push(Span::styled("", dot_style));
    }

    // Add bookmark diamond if present
    if let Some(label) = bm_label {
        let diamond = if let Some(c) = label {
            format!("\u{25c6}{c}")
        } else {
            "\u{25c6}".to_string()
        };
        let mut bm_style = Style::default().fg(theme.accent);
        if let Some(bg) = hl.gutter_bg {
            bm_style = bm_style.bg(bg);
        }
        spans.push(Span::styled(diamond, bm_style));
    }

    let text = format!("{gutter_l} {gutter_r}{marker}");
    let mut style = Style::default().fg(theme.text_muted);
    if marker == "\u{2502}" {
        style = style.fg(theme.cursor_line_fg);
    }
    if let Some(fg) = hl.gutter_fg {
        style = style.fg(fg);
    }
    if let Some(bg) = hl.gutter_bg {
        style = style.bg(bg);
    }
    spans.push(Span::styled(text, style));

    Line::from(spans)
}

/// Build a content-only line (no gutter) with syntax highlighting and diff background.
fn make_content_only_line<'a>(
    content: &str,
    hl_spans: Option<&Vec<HighlightSpan>>,
    diff_bg: Option<Color>,
    hl: RowHighlight,
    theme: &Theme,
) -> Line<'a> {
    let trimmed = content.trim_end_matches('\n');
    let content_bg = hl.content_bg.or(diff_bg);

    let content_spans = if let Some(spans) = hl_spans {
        apply_highlights(trimmed, spans, content_bg, theme)
    } else {
        let mut style = Style::default();
        if let Some(bg_color) = content_bg {
            style = style.bg(bg_color);
            if hl.content_bg.is_none() {
                if bg_color == theme.diff_del_bg {
                    style = style.fg(theme.diff_del_fg);
                } else if bg_color == theme.diff_add_bg {
                    style = style.fg(theme.diff_add_fg);
                } else {
                    style = style.fg(theme.text);
                }
            } else {
                style = style.fg(theme.text);
            }
        } else {
            style = style.fg(theme.text);
        }
        vec![Span::styled(trimmed.to_string(), style)]
    };

    Line::from(content_spans)
}

/// Build an empty content-only line (no gutter) for split view filler.
fn make_empty_content_line<'a>(hl: RowHighlight, theme: &Theme) -> Line<'a> {
    let mut style = Style::default().fg(theme.text_muted).bg(theme.collapsed_bg);
    if let Some(bg) = hl.content_bg {
        style = style.bg(bg);
    }
    Line::from(Span::styled(" ", style))
}

#[allow(clippy::too_many_arguments)]
fn make_unified_highlighted<'a>(
    old_g: &str,
    new_g: &str,
    prefix: &str,
    content: &str,
    hl_spans: Option<&Vec<HighlightSpan>>,
    diff_bg: Option<Color>,
    hl: RowHighlight,
    ann_marker: bool,
    score: Option<u8>,
    bm_label: Option<Option<char>>,
    theme: &Theme,
) -> Line<'a> {
    let trimmed = content.trim_end_matches('\n');
    let content_bg = hl.content_bg.or(diff_bg);

    let marker = if ann_marker { "\u{2502}" } else { " " };
    let mut gutter_style = Style::default().fg(theme.text_muted);
    if ann_marker {
        gutter_style = gutter_style.fg(theme.cursor_line_fg);
    }
    if let Some(fg) = hl.gutter_fg {
        gutter_style = gutter_style.fg(fg);
    }
    if let Some(bg) = hl.gutter_bg {
        gutter_style = gutter_style.bg(bg);
    }

    let mut all_spans = Vec::new();
    if let Some(s) = score {
        all_spans.push(Span::styled("", Style::default().fg(score_color(s))));
    }
    if let Some(label) = bm_label {
        let diamond = if let Some(c) = label {
            format!("\u{25c6}{c}")
        } else {
            "\u{25c6}".to_string()
        };
        let mut bm_style = Style::default().fg(theme.accent);
        if let Some(bg) = hl.gutter_bg {
            bm_style = bm_style.bg(bg);
        }
        all_spans.push(Span::styled(diamond, bm_style));
    }
    let gutter_span = Span::styled(format!("{old_g} {new_g}{marker}"), gutter_style);
    all_spans.push(gutter_span);

    let prefix_style = match prefix {
        "+" => Style::default()
            .fg(theme.diff_add_fg)
            .bg(content_bg.unwrap_or_default()),
        "-" => Style::default()
            .fg(theme.diff_del_fg)
            .bg(content_bg.unwrap_or_default()),
        _ => {
            let mut s = Style::default().fg(theme.text_muted);
            if let Some(bg_color) = content_bg {
                s = s.bg(bg_color);
            }
            s
        }
    };
    let prefix_span = Span::styled(prefix.to_string(), prefix_style);

    let content_spans = if let Some(spans) = hl_spans {
        apply_highlights(trimmed, spans, content_bg, theme)
    } else {
        let mut style = Style::default().fg(theme.text);
        if let Some(bg_color) = content_bg {
            style = style.bg(bg_color);
        }
        vec![Span::styled(trimmed.to_string(), style)]
    };

    all_spans.push(prefix_span);
    all_spans.extend(content_spans);
    Line::from(all_spans)
}

/// Build a collapsed indicator line for unified view.
fn make_collapsed_indicator_line_unified<'a>(
    gutter_width: usize,
    hidden_count: usize,
    direction: ExpandDirection,
    hl: RowHighlight,
    score: Option<u8>,
    theme: &Theme,
) -> Line<'a> {
    let gutter_text = format!(
        "{:>gutter_width$} {:>gutter_width$} ",
        "\u{22ef}", "\u{22ef}"
    );
    let mut gutter_style = Style::default().fg(theme.text_muted);
    if let Some(fg) = hl.gutter_fg {
        gutter_style = gutter_style.fg(fg);
    }
    if let Some(bg) = hl.gutter_bg {
        gutter_style = gutter_style.bg(bg);
    }
    let mut content_style = Style::default().fg(theme.text_muted);
    if let Some(bg) = hl.content_bg {
        content_style = content_style.bg(bg);
    }
    let caret = match direction {
        ExpandDirection::Down => "\u{25bc}", //        ExpandDirection::Up => "\u{25b2}",   //    };
    let label = format!("{caret} {hidden_count} lines hidden {caret}");

    let mut spans = Vec::new();
    if let Some(s) = score {
        spans.push(Span::styled("", Style::default().fg(score_color(s))));
    }
    spans.push(Span::styled(gutter_text, gutter_style));
    spans.push(Span::styled(label, content_style));
    Line::from(spans)
}

/// Wrap left and right split-view lines in lockstep so each logical row occupies the same
/// number of visual rows on both sides. Without this, independent wrapping desynchronises the
/// two panels — a long line on one side pushes subsequent rows down, causing the cursor row
/// to appear at different vertical positions (or be clipped on one side but visible on the other).
fn wrap_split_lines_synchronized_with_scroll<'a>(
    left_lines: Vec<Line<'a>>,
    center_lines: Vec<Line<'a>>,
    right_lines: Vec<Line<'a>>,
    config: &WrapConfig<'_>,
    start_visual: usize,
    height: usize,
) -> (Vec<Line<'a>>, Vec<Line<'a>>, Vec<Line<'a>>) {
    if height == 0 {
        return (Vec::new(), Vec::new(), Vec::new());
    }
    if !config.wrap_enabled || config.width == 0 {
        let left_visible: Vec<Line> = left_lines
            .into_iter()
            .skip(start_visual)
            .take(height)
            .collect();
        let center_visible: Vec<Line> = center_lines
            .into_iter()
            .skip(start_visual)
            .take(height)
            .collect();
        let right_visible: Vec<Line> = right_lines
            .into_iter()
            .skip(start_visual)
            .take(height)
            .collect();
        return (left_visible, center_visible, right_visible);
    }

    let mut remaining_skip = start_visual;
    let mut remaining_height = height;
    let mut left_result: Vec<Line<'a>> = Vec::new();
    let mut center_result: Vec<Line<'a>> = Vec::new();
    let mut right_result: Vec<Line<'a>> = Vec::new();

    let iter = left_lines
        .into_iter()
        .zip(center_lines)
        .zip(right_lines)
        .map(|((l, c), r)| (l, c, r));

    for (left_line, center_line, right_line) in iter {
        let left_wrapped = wrap_single_line_for_display(left_line, config);
        let right_wrapped = wrap_single_line_for_display(right_line, config);
        // Center gutter is never wrapped (fixed width)

        let max_height = left_wrapped.len().max(right_wrapped.len());

        if remaining_skip >= max_height {
            remaining_skip -= max_height;
            continue;
        }

        let start = remaining_skip;
        remaining_skip = 0;

        for i in start..max_height {
            if remaining_height == 0 {
                return (left_result, center_result, right_result);
            }

            let left_line = left_wrapped.get(i).cloned().unwrap_or_else(Line::default);
            let right_line = right_wrapped.get(i).cloned().unwrap_or_else(Line::default);
            // Center: show the gutter on first visual row, blank on continuation rows
            let center_line = if i == 0 {
                center_line.clone()
            } else {
                Line::default()
            };

            left_result.push(left_line);
            center_result.push(center_line);
            right_result.push(right_line);
            remaining_height -= 1;
        }

        if remaining_height == 0 {
            return (left_result, center_result, right_result);
        }
    }

    (left_result, center_result, right_result)
}

fn wrap_lines_for_display_with_scroll<'a>(
    lines: Vec<Line<'a>>,
    config: &WrapConfig<'_>,
    start_visual: usize,
    height: usize,
) -> Vec<Line<'a>> {
    if height == 0 {
        return Vec::new();
    }

    let mut remaining_skip = start_visual;
    let mut remaining_height = height;
    let mut result: Vec<Line<'a>> = Vec::new();

    for line in lines {
        let wrapped = wrap_single_line_for_display(line, config);
        if remaining_skip >= wrapped.len() {
            remaining_skip -= wrapped.len();
            continue;
        }

        let start = remaining_skip;
        remaining_skip = 0;
        for (idx, line) in wrapped.into_iter().enumerate() {
            if idx < start {
                continue;
            }
            if remaining_height == 0 {
                return result;
            }
            result.push(line);
            remaining_height -= 1;
        }

        if remaining_height == 0 {
            return result;
        }
    }

    result
}

fn wrap_single_line_for_display<'a>(line: Line<'a>, config: &WrapConfig<'_>) -> Vec<Line<'a>> {
    if !config.wrap_enabled || config.width == 0 {
        return vec![line];
    }
    let max_width = config.width as usize;
    let content_width = max_width.saturating_sub(config.gutter_width);
    if content_width == 0 {
        return vec![line];
    }

    let line_width: usize = line.spans.iter().map(|s| s.width()).sum();
    if line_width <= max_width {
        return vec![line];
    }

    if config.gutter_width == 0 {
        // No gutter — all spans are content, no continuation prefix
        let mut chars: Vec<(char, Style)> = Vec::new();
        for span in &line.spans {
            let style = span.style;
            for ch in span.content.chars() {
                chars.push((ch, style));
            }
        }

        let mut result: Vec<Line<'a>> = Vec::new();
        let mut offset = 0;
        while offset < chars.len() {
            let end = (offset + content_width).min(chars.len());
            let chunk = &chars[offset..end];

            let mut chunk_spans: Vec<Span<'a>> = Vec::new();
            let mut current_text = String::new();
            let mut current_style = chunk[0].1;

            for &(ch, style) in chunk {
                if style == current_style {
                    current_text.push(ch);
                } else {
                    if !current_text.is_empty() {
                        chunk_spans.push(Span::styled(current_text, current_style));
                        current_text = String::new();
                    }
                    current_style = style;
                    current_text.push(ch);
                }
            }
            if !current_text.is_empty() {
                chunk_spans.push(Span::styled(current_text, current_style));
            }

            result.push(Line::from(chunk_spans));
            offset = end;
        }

        if result.is_empty() {
            result.push(line);
        }

        return result;
    }

    // Separate gutter (first span) from content (remaining spans)
    let mut spans_iter = line.spans.into_iter();
    let gutter_span = match spans_iter.next() {
        Some(s) => s,
        None => {
            return vec![Line::default()];
        }
    };
    let content_spans: Vec<Span<'a>> = spans_iter.collect();

    // Flatten content spans into (char, Style) pairs for splitting
    let mut chars: Vec<(char, Style)> = Vec::new();
    for span in &content_spans {
        let style = span.style;
        for ch in span.content.chars() {
            chars.push((ch, style));
        }
    }

    // Build the continuation gutter
    let cont_gutter = format!(
        "{}\u{21aa}",
        " ".repeat(config.gutter_width.saturating_sub(1))
    );
    let cont_gutter_style = gutter_span.style.fg(config.theme.text_muted);

    // Split chars into chunks of content_width
    let mut result: Vec<Line<'a>> = Vec::new();
    let mut offset = 0;
    let mut is_first = true;
    while offset < chars.len() {
        let end = (offset + content_width).min(chars.len());
        let chunk = &chars[offset..end];

        // Build spans from the chunk, coalescing adjacent chars with the same style
        let mut chunk_spans: Vec<Span<'a>> = Vec::new();
        let mut current_text = String::new();
        let mut current_style = chunk[0].1;

        for &(ch, style) in chunk {
            if style == current_style {
                current_text.push(ch);
            } else {
                if !current_text.is_empty() {
                    chunk_spans.push(Span::styled(current_text, current_style));
                    current_text = String::new();
                }
                current_style = style;
                current_text.push(ch);
            }
        }
        if !current_text.is_empty() {
            chunk_spans.push(Span::styled(current_text, current_style));
        }

        let mut line_spans = Vec::new();
        if is_first {
            line_spans.push(gutter_span.clone());
            is_first = false;
        } else {
            line_spans.push(Span::styled(cont_gutter.clone(), cont_gutter_style));
        }
        line_spans.extend(chunk_spans);
        result.push(Line::from(line_spans));

        offset = end;
    }

    // Edge case: if content was empty but gutter was wide
    if is_first {
        result.push(Line::from(vec![gutter_span]));
    }

    result
}

pub(crate) fn compute_split_visual_row_metrics(
    delta: &FileDelta,
    state: &AppState,
    left_width: u16,
    right_width: u16,
) -> VisualRowMetrics {
    let display_map = build_display_map(
        delta,
        DiffViewMode::Split,
        state.diff.display_context,
        &state.diff.gap_expansions,
    );
    let (left_lines, _center_lines, right_lines) = build_split_lines_core(
        delta,
        &state.diff.old_highlights,
        &state.diff.new_highlights,
        state,
        &display_map,
        &state.theme,
    );
    let left_config = WrapConfig {
        width: left_width,
        gutter_width: 0,
        wrap_enabled: true,
        theme: &state.theme,
    };
    let right_config = WrapConfig {
        width: right_width,
        gutter_width: 0,
        wrap_enabled: true,
        theme: &state.theme,
    };
    let mut row_offsets = Vec::with_capacity(left_lines.len());
    let mut row_heights = Vec::with_capacity(left_lines.len());
    let mut total_rows = 0;

    for (left, right) in left_lines.into_iter().zip(right_lines.into_iter()) {
        let left_height = wrap_single_line_for_display(left, &left_config).len();
        let right_height = wrap_single_line_for_display(right, &right_config).len();
        let row_height = left_height.max(right_height).max(1);
        row_offsets.push(total_rows);
        row_heights.push(row_height);
        total_rows += row_height;
    }

    VisualRowMetrics {
        row_offsets,
        row_heights,
        total_rows,
    }
}

pub(crate) fn compute_unified_visual_row_metrics(
    delta: &FileDelta,
    state: &AppState,
    width: u16,
) -> VisualRowMetrics {
    let display_map = build_display_map(
        delta,
        DiffViewMode::Unified,
        state.diff.display_context,
        &state.diff.gap_expansions,
    );
    let lines = build_unified_lines_core(
        delta,
        &state.diff.old_highlights,
        &state.diff.new_highlights,
        state,
        &display_map,
        &state.theme,
    );
    let config = WrapConfig {
        width,
        gutter_width: 5 + 1 + 5 + 1 + 1,
        wrap_enabled: true,
        theme: &state.theme,
    };
    let mut row_offsets = Vec::with_capacity(lines.len());
    let mut row_heights = Vec::with_capacity(lines.len());
    let mut total_rows = 0;

    for line in lines {
        let row_height = wrap_single_line_for_display(line, &config).len().max(1);
        row_offsets.push(total_rows);
        row_heights.push(row_height);
        total_rows += row_height;
    }

    VisualRowMetrics {
        row_offsets,
        row_heights,
        total_rows,
    }
}

#[cfg(test)]
mod tests {
    use super::{compute_split_visual_row_metrics, compute_unified_visual_row_metrics};
    use crate::git::types::{DiffLine, DiffLineOrigin, FileDelta, FileStatus, Hunk};
    use crate::state::{AppState, DiffOptions};
    use crate::theme::Theme;
    use std::path::PathBuf;

    fn make_delta(lines: Vec<DiffLine>) -> FileDelta {
        FileDelta {
            path: PathBuf::from("src/lib.rs"),
            old_path: None,
            status: FileStatus::Modified,
            hunks: vec![Hunk {
                header: "@@ -1,1 +1,1 @@".to_string(),
                lines,
            }],
            additions: 0,
            deletions: 0,
            binary: false,
        }
    }

    #[test]
    fn split_metrics_use_max_wrap_height() {
        let mut state = AppState::new(DiffOptions::new(false, false), Theme::from_name("one-dark"));
        state.diff.old_highlights = vec![Vec::new(); 2];
        state.diff.new_highlights = vec![Vec::new(); 2];

        let long_line = "x".repeat(200);
        let delta = make_delta(vec![
            DiffLine {
                origin: DiffLineOrigin::Deletion,
                old_lineno: Some(1),
                new_lineno: None,
                content: long_line.clone(),
            },
            DiffLine {
                origin: DiffLineOrigin::Addition,
                old_lineno: None,
                new_lineno: Some(1),
                content: "ok".to_string(),
            },
        ]);

        let metrics = compute_split_visual_row_metrics(&delta, &state, 12, 12);

        assert_eq!(metrics.row_offsets.len(), 2);
        assert_eq!(metrics.row_heights.len(), 2);
        assert!(metrics.row_heights[1] > 1, "paired row should wrap");
        assert_eq!(
            metrics.total_rows,
            metrics.row_heights.iter().sum::<usize>()
        );
    }

    #[test]
    fn unified_metrics_account_for_wrapping() {
        let mut state = AppState::new(DiffOptions::new(false, true), Theme::from_name("one-dark"));
        state.diff.old_highlights = vec![Vec::new(); 2];
        state.diff.new_highlights = vec![Vec::new(); 2];

        let long_line = "x".repeat(200);
        let delta = make_delta(vec![DiffLine {
            origin: DiffLineOrigin::Context,
            old_lineno: Some(1),
            new_lineno: Some(1),
            content: long_line,
        }]);

        let metrics = compute_unified_visual_row_metrics(&delta, &state, 16);

        assert_eq!(metrics.row_offsets.len(), 2);
        assert_eq!(metrics.row_heights.len(), 2);
        assert!(metrics.row_heights[1] > 1, "content row should wrap");
        assert_eq!(
            metrics.total_rows,
            metrics.row_heights.iter().sum::<usize>()
        );
    }
}