tuicr 0.1.2

Review AI-generated diffs like a GitHub pull request, right from your terminal.
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
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
};
use unicode_width::UnicodeWidthStr;

use crate::app::{App, DiffViewMode, FocusedPanel, InputMode};
use crate::model::{LineOrigin, LineSide};
use crate::ui::{comment_panel, help_popup, status_bar, styles};

pub fn render(frame: &mut Frame, app: &mut App) {
    // Special handling for commit selection mode
    if app.input_mode == InputMode::CommitSelect {
        render_commit_select(frame, app);
        return;
    }

    let show_command_line = app.input_mode == InputMode::Command;

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(if show_command_line {
            vec![
                Constraint::Length(1), // Header
                Constraint::Min(0),    // Main content
                Constraint::Length(1), // Status bar
                Constraint::Length(1), // Command line
            ]
        } else {
            vec![
                Constraint::Length(1), // Header
                Constraint::Min(0),    // Main content
                Constraint::Length(1), // Status bar
            ]
        })
        .split(frame.area());

    status_bar::render_header(frame, app, chunks[0]);
    render_main_content(frame, app, chunks[1]);
    status_bar::render_status_bar(frame, app, chunks[2]);

    if show_command_line {
        status_bar::render_command_line(frame, app, chunks[3]);
    }

    // Render help popup on top if in help mode
    if app.input_mode == InputMode::Help {
        help_popup::render_help(frame);
    }

    // Render comment input popup if in comment mode
    if app.input_mode == InputMode::Comment {
        comment_panel::render_comment_input(frame, app);
    }

    // Render confirm dialog if in confirm mode
    if app.input_mode == InputMode::Confirm {
        comment_panel::render_confirm_dialog(frame, "Copy review to clipboard?");
    }
}

fn render_commit_select(frame: &mut Frame, app: &App) {
    let area = frame.area();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header
            Constraint::Min(0),    // Commit list
            Constraint::Length(1), // Footer hints
        ])
        .split(area);

    // Header
    let header = Paragraph::new(" Select commits to review ")
        .style(styles::header_style())
        .block(Block::default());
    frame.render_widget(header, chunks[0]);

    // Commit list
    let block = Block::default()
        .title(" Recent Commits ")
        .borders(Borders::ALL)
        .border_style(styles::border_style(true));

    let inner = block.inner(chunks[1]);
    frame.render_widget(block, chunks[1]);

    let items: Vec<Line> = app
        .commit_list
        .iter()
        .enumerate()
        .map(|(i, commit)| {
            let is_selected = app.commit_selected.get(i).copied().unwrap_or(false);
            let is_cursor = i == app.commit_list_cursor;

            let checkbox = if is_selected { "[x]" } else { "[ ]" };
            let pointer = if is_cursor { ">" } else { " " };

            let style = if is_cursor {
                styles::selected_style()
            } else {
                Style::default()
            };

            let checkbox_style = if is_selected {
                styles::reviewed_style()
            } else {
                styles::pending_style()
            };

            // Format: > [x] abc1234  Commit message (author, date)
            let time_str = commit.time.format("%Y-%m-%d").to_string();
            Line::from(vec![
                Span::styled(format!("{} ", pointer), style),
                Span::styled(format!("{} ", checkbox), checkbox_style),
                Span::styled(format!("{} ", commit.short_id), styles::hash_style()),
                Span::styled(truncate_str(&commit.summary, 50), style),
                Span::styled(
                    format!(" ({}, {})", commit.author, time_str),
                    Style::default().fg(styles::FG_SECONDARY),
                ),
            ])
        })
        .collect();

    let list = Paragraph::new(items);
    frame.render_widget(list, inner);

    // Footer hints
    let hints = " j/k:navigate  Space:select  Enter:confirm  q:quit ";
    let footer = Paragraph::new(hints)
        .style(styles::status_bar_style())
        .block(Block::default());
    frame.render_widget(footer, chunks[2]);
}

fn truncate_str(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len.saturating_sub(3)])
    }
}

fn render_main_content(frame: &mut Frame, app: &mut App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(20), // File list
            Constraint::Percentage(80), // Diff view
        ])
        .split(area);

    render_file_list(frame, app, chunks[0]);
    render_diff_view(frame, app, chunks[1]);
}

fn render_file_list(frame: &mut Frame, app: &App, area: Rect) {
    let focused = app.focused_panel == FocusedPanel::FileList;

    let block = Block::default()
        .title(" Files ")
        .borders(Borders::ALL)
        .border_style(styles::border_style(focused));

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

    let items: Vec<Line> = app
        .diff_files
        .iter()
        .enumerate()
        .map(|(i, file)| {
            let path = file.display_path();
            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("?");
            let status = file.status.as_char();
            let is_reviewed = app.session.is_file_reviewed(path);
            let review_mark = if is_reviewed { "" } else { " " };
            let is_current = i == app.diff_state.current_file_idx;
            let pointer = if is_current { "" } else { " " };

            let style = if is_current {
                styles::selected_style()
            } else {
                Style::default()
            };

            Line::from(vec![
                Span::styled(pointer.to_string(), style),
                Span::styled(
                    format!("[{}]", review_mark),
                    if is_reviewed {
                        styles::reviewed_style()
                    } else {
                        styles::pending_style()
                    },
                ),
                Span::styled(format!(" {} ", status), styles::file_status_style(status)),
                Span::styled(filename.to_string(), style),
            ])
        })
        .collect();

    let list = Paragraph::new(items);
    frame.render_widget(list, inner);
}

fn render_diff_view(frame: &mut Frame, app: &mut App, area: Rect) {
    match app.diff_view_mode {
        DiffViewMode::Unified => render_unified_diff(frame, app, area),
        DiffViewMode::SideBySide => render_side_by_side_diff(frame, app, area),
    }
}

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

    let block = Block::default()
        .title(" Diff (Unified) ")
        .borders(Borders::ALL)
        .border_style(styles::border_style(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;

    for file in &app.diff_files {
        let path = file.display_path();
        let status = file.status.as_char();
        let is_reviewed = app.session.is_file_reviewed(path);

        // 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 { "" };

        lines.push(Line::from(vec![
            Span::styled(indicator, styles::current_line_indicator_style()),
            Span::styled(
                format!("═══ {}{} [{}] ", review_mark, path.display(), status),
                styles::file_header_style(),
            ),
            Span::styled("".repeat(40), styles::file_header_style()),
        ]));
        line_idx += 1;

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

        // Show file-level comments right after the header
        if let Some(review) = app.session.files.get(path) {
            for comment in &review.file_comments {
                let comment_lines = comment_panel::format_comment_lines(
                    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()),
                    );
                    lines.push(comment_line);
                    line_idx += 1;
                }
            }
        }

        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()),
                Span::styled("(binary file)", styles::dim_style()),
            ]));
            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()),
                Span::styled("(no changes)", styles::dim_style()),
            ]));
            line_idx += 1;
        } else {
            // Get line comments for this file
            let line_comments = app
                .session
                .files
                .get(path)
                .map(|r| &r.line_comments)
                .cloned()
                .unwrap_or_default();

            for hunk in &file.hunks {
                // Hunk header
                let indicator = cursor_indicator_spaced(line_idx, current_line_idx);
                lines.push(Line::from(vec![
                    Span::styled(indicator, styles::current_line_indicator_style()),
                    Span::styled(hunk.header.to_string(), styles::diff_hunk_header_style()),
                ]));
                line_idx += 1;

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

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

                    let indicator = cursor_indicator(line_idx, current_line_idx);

                    // Build line spans - use syntax highlighting if available
                    let mut line_spans = vec![
                        Span::styled(indicator, styles::current_line_indicator_style()),
                        Span::styled(line_num, styles::dim_style()),
                        Span::styled(format!("{} ", prefix), style),
                    ];

                    // Add content spans
                    if let Some(ref highlighted) = diff_line.highlighted_spans {
                        // Use syntax-highlighted spans
                        for (span_style, span_text) in highlighted {
                            line_spans.push(Span::styled(span_text.clone(), *span_style));
                        }
                    } else {
                        // Fall back to default diff styling
                        line_spans.push(Span::styled(diff_line.content.clone(), 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
                        && let Some(comments) = line_comments.get(&old_ln)
                    {
                        for comment in comments {
                            if comment.side == Some(LineSide::Old) {
                                let comment_lines = comment_panel::format_comment_lines(
                                    comment.comment_type,
                                    &comment.content,
                                    Some(old_ln),
                                );
                                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(),
                                        ),
                                    );
                                    lines.push(comment_line);
                                    line_idx += 1;
                                }
                            }
                        }
                    }
                    // New side comments (for added/context lines)
                    if let Some(new_ln) = diff_line.new_lineno
                        && let Some(comments) = line_comments.get(&new_ln)
                    {
                        for comment in comments {
                            if comment.side != Some(LineSide::Old) {
                                let comment_lines = comment_panel::format_comment_lines(
                                    comment.comment_type,
                                    &comment.content,
                                    Some(new_ln),
                                );
                                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(),
                                        ),
                                    );
                                    lines.push(comment_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(),
        )));
        line_idx += 1;
    }

    // Apply scroll offset
    let scroll_x = app.diff_state.scroll_x;
    let visible_lines: Vec<Line> = lines
        .into_iter()
        .skip(app.diff_state.scroll_offset)
        .take(inner.height as usize)
        .map(|line| apply_horizontal_scroll(line, scroll_x))
        .collect();

    let diff = Paragraph::new(visible_lines);
    frame.render_widget(diff, inner);
}

/// Context for rendering side-by-side diff lines
struct SideBySideContext {
    content_width: usize,
    current_line_idx: usize,
}

/// Get cursor indicator (single character for inline content)
fn cursor_indicator(line_idx: usize, current_line_idx: usize) -> &'static str {
    if line_idx == current_line_idx {
        ""
    } else {
        " "
    }
}

/// Get cursor indicator with spacing (two characters for line prefixes)
fn cursor_indicator_spaced(line_idx: usize, current_line_idx: usize) -> &'static str {
    if line_idx == current_line_idx {
        ""
    } else {
        "  "
    }
}

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

    let block = Block::default()
        .title(" Diff (Side-by-Side) ")
        .borders(Borders::ALL)
        .border_style(styles::border_style(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;

    // Calculate column widths (split the area in half)
    // Layout: indicator(1) + linenum(4) + space(1) + prefix(1) + content + " │ "(3) + linenum(4) + space(1) + prefix(1) + content
    // Total overhead: 1 + 5 + 1 + 3 + 5 + 1 = 16
    let available_width = inner.width.saturating_sub(16) as usize;
    let content_width = available_width / 2;

    let ctx = SideBySideContext {
        content_width,
        current_line_idx: app.diff_state.cursor_line,
    };

    // Build all diff lines for side-by-side view
    let mut lines: Vec<Line> = Vec::new();
    let mut line_idx: usize = 0;

    for file in &app.diff_files {
        let path = file.display_path();
        let status = file.status.as_char();
        let is_reviewed = app.session.is_file_reviewed(path);

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

        let review_mark = if is_reviewed { "" } else { "" };

        lines.push(Line::from(vec![
            Span::styled(indicator, styles::current_line_indicator_style()),
            Span::styled(
                format!("═══ {}{} [{}] ", review_mark, path.display(), status),
                styles::file_header_style(),
            ),
            Span::styled("".repeat(40), styles::file_header_style()),
        ]));
        line_idx += 1;

        // If file is reviewed, skip rendering the body
        if is_reviewed {
            continue;
        }

        // Show file-level comments
        if let Some(review) = app.session.files.get(path) {
            for comment in &review.file_comments {
                let comment_lines = comment_panel::format_comment_lines(
                    comment.comment_type,
                    &comment.content,
                    None,
                );
                for mut comment_line in comment_lines {
                    let indicator = cursor_indicator(line_idx, ctx.current_line_idx);
                    comment_line.spans.insert(
                        0,
                        Span::styled(indicator, styles::current_line_indicator_style()),
                    );
                    lines.push(comment_line);
                    line_idx += 1;
                }
            }
        }

        if file.is_binary {
            let indicator = cursor_indicator_spaced(line_idx, ctx.current_line_idx);
            lines.push(Line::from(vec![
                Span::styled(indicator, styles::current_line_indicator_style()),
                Span::styled("(binary file)", styles::dim_style()),
            ]));
            line_idx += 1;
        } else if file.hunks.is_empty() {
            let indicator = cursor_indicator_spaced(line_idx, ctx.current_line_idx);
            lines.push(Line::from(vec![
                Span::styled(indicator, styles::current_line_indicator_style()),
                Span::styled("(no changes)", styles::dim_style()),
            ]));
            line_idx += 1;
        } else {
            let line_comments = app
                .session
                .files
                .get(path)
                .map(|r| &r.line_comments)
                .cloned()
                .unwrap_or_default();

            for hunk in &file.hunks {
                // Hunk header
                let indicator = cursor_indicator_spaced(line_idx, ctx.current_line_idx);
                lines.push(Line::from(vec![
                    Span::styled(indicator, styles::current_line_indicator_style()),
                    Span::styled(hunk.header.to_string(), styles::diff_hunk_header_style()),
                ]));
                line_idx += 1;

                // Process diff lines in side-by-side format
                line_idx = render_hunk_lines_side_by_side(
                    &hunk.lines,
                    &line_comments,
                    &ctx,
                    line_idx,
                    &mut lines,
                );
            }
        }

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

    // Apply scroll offset
    let scroll_x = app.diff_state.scroll_x;
    let visible_lines: Vec<Line> = lines
        .into_iter()
        .skip(app.diff_state.scroll_offset)
        .take(inner.height as usize)
        .map(|line| apply_horizontal_scroll(line, scroll_x))
        .collect();

    let diff = Paragraph::new(visible_lines);
    frame.render_widget(diff, inner);
}

/// Process and render all diff lines in a hunk for side-by-side view
fn render_hunk_lines_side_by_side(
    hunk_lines: &[crate::model::DiffLine],
    line_comments: &std::collections::HashMap<u32, Vec<crate::model::Comment>>,
    ctx: &SideBySideContext,
    mut line_idx: usize,
    lines: &mut Vec<Line>,
) -> usize {
    let mut i = 0;
    while i < hunk_lines.len() {
        let diff_line = &hunk_lines[i];

        match diff_line.origin {
            LineOrigin::Context => {
                line_idx = render_context_line_side_by_side(
                    diff_line,
                    line_comments,
                    ctx,
                    line_idx,
                    lines,
                );
                i += 1;
            }
            LineOrigin::Deletion => {
                let (new_line_idx, lines_processed) = render_deletion_addition_pair_side_by_side(
                    hunk_lines,
                    i,
                    line_comments,
                    ctx,
                    line_idx,
                    lines,
                );
                line_idx = new_line_idx;
                i = lines_processed;
            }
            LineOrigin::Addition => {
                line_idx = render_standalone_addition_side_by_side(
                    diff_line,
                    line_comments,
                    ctx,
                    line_idx,
                    lines,
                );
                i += 1;
            }
        }
    }
    line_idx
}

/// Render a context line (appears on both sides)
fn render_context_line_side_by_side(
    diff_line: &crate::model::DiffLine,
    line_comments: &std::collections::HashMap<u32, Vec<crate::model::Comment>>,
    ctx: &SideBySideContext,
    mut line_idx: usize,
    lines: &mut Vec<Line>,
) -> usize {
    let line_num = diff_line
        .old_lineno
        .or(diff_line.new_lineno)
        .map(|n| format!("{:>4}", n))
        .unwrap_or_else(|| "    ".to_string());

    let indicator = cursor_indicator(line_idx, ctx.current_line_idx);

    let mut spans = vec![
        Span::styled(indicator, styles::current_line_indicator_style()),
        Span::styled(format!("{} ", line_num), styles::dim_style()),
        Span::styled(" ".to_string(), styles::diff_context_style()),
    ];

    // Left side content - use syntax highlighting if available
    if let Some(ref highlighted) = diff_line.highlighted_spans {
        let content_spans =
            truncate_or_pad_spans(highlighted, ctx.content_width, styles::diff_context_style());
        spans.extend(content_spans);
    } else {
        let content = truncate_or_pad(&diff_line.content, ctx.content_width);
        spans.push(Span::styled(content, styles::diff_context_style()));
    }

    // Separator
    spans.push(Span::styled("", styles::dim_style()));
    spans.push(Span::styled(format!("{} ", line_num), styles::dim_style()));
    spans.push(Span::styled(" ".to_string(), styles::diff_context_style()));

    // Right side content - use same highlighting
    if let Some(ref highlighted) = diff_line.highlighted_spans {
        let content_spans =
            truncate_or_pad_spans(highlighted, ctx.content_width, styles::diff_context_style());
        spans.extend(content_spans);
    } else {
        let content = truncate_or_pad(&diff_line.content, ctx.content_width);
        spans.push(Span::styled(content, styles::diff_context_style()));
    }

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

    // Add comments if any
    if let Some(new_ln) = diff_line.new_lineno {
        line_idx = add_comments_to_line(new_ln, line_comments, LineSide::New, ctx, line_idx, lines);
    }

    line_idx
}

/// Render paired deletions and additions side-by-side
fn render_deletion_addition_pair_side_by_side(
    hunk_lines: &[crate::model::DiffLine],
    start_idx: usize,
    line_comments: &std::collections::HashMap<u32, Vec<crate::model::Comment>>,
    ctx: &SideBySideContext,
    mut line_idx: usize,
    lines: &mut Vec<Line>,
) -> (usize, usize) {
    // Find the range of consecutive deletions
    let mut del_end = start_idx + 1;
    while del_end < hunk_lines.len() && hunk_lines[del_end].origin == LineOrigin::Deletion {
        del_end += 1;
    }

    // Find the range of consecutive additions following the deletions
    let add_start = del_end;
    let mut add_end = add_start;
    while add_end < hunk_lines.len() && hunk_lines[add_end].origin == LineOrigin::Addition {
        add_end += 1;
    }

    let del_count = del_end - start_idx;
    let add_count = add_end - add_start;
    let max_lines = del_count.max(add_count);

    // Render each pair of deletion/addition
    for offset in 0..max_lines {
        let indicator = cursor_indicator(line_idx, ctx.current_line_idx);

        let mut spans = vec![Span::styled(
            indicator,
            styles::current_line_indicator_style(),
        )];

        // Left side (deletion)
        if offset < del_count {
            let del_line = &hunk_lines[start_idx + offset];
            add_deletion_spans(&mut spans, del_line, ctx.content_width);
        } else {
            add_empty_column_spans(&mut spans, ctx.content_width);
        }

        spans.push(Span::styled("", styles::dim_style()));

        // Right side (addition)
        if offset < add_count {
            let add_line = &hunk_lines[add_start + offset];
            add_addition_spans(&mut spans, add_line, ctx.content_width);
        } else {
            add_empty_column_spans(&mut spans, ctx.content_width);
        }

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

        // Add comments for deletion
        if offset < del_count {
            let del_line = &hunk_lines[start_idx + offset];
            if let Some(old_ln) = del_line.old_lineno {
                line_idx = add_comments_to_line(
                    old_ln,
                    line_comments,
                    LineSide::Old,
                    ctx,
                    line_idx,
                    lines,
                );
            }
        }

        // Add comments for addition
        if offset < add_count {
            let add_line = &hunk_lines[add_start + offset];
            if let Some(new_ln) = add_line.new_lineno {
                line_idx = add_comments_to_line(
                    new_ln,
                    line_comments,
                    LineSide::New,
                    ctx,
                    line_idx,
                    lines,
                );
            }
        }
    }

    (line_idx, add_end)
}

/// Render a standalone addition (no matching deletion)
fn render_standalone_addition_side_by_side(
    diff_line: &crate::model::DiffLine,
    line_comments: &std::collections::HashMap<u32, Vec<crate::model::Comment>>,
    ctx: &SideBySideContext,
    mut line_idx: usize,
    lines: &mut Vec<Line>,
) -> usize {
    let indicator = cursor_indicator(line_idx, ctx.current_line_idx);

    let mut spans = vec![Span::styled(
        indicator,
        styles::current_line_indicator_style(),
    )];
    add_empty_column_spans(&mut spans, ctx.content_width);
    spans.push(Span::styled("", styles::dim_style()));
    add_addition_spans(&mut spans, diff_line, ctx.content_width);

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

    // Add comments if any
    if let Some(new_ln) = diff_line.new_lineno {
        line_idx = add_comments_to_line(new_ln, line_comments, LineSide::New, ctx, line_idx, lines);
    }

    line_idx
}

/// Add deletion line spans to the spans vector
fn add_deletion_spans(
    spans: &mut Vec<Span>,
    diff_line: &crate::model::DiffLine,
    content_width: usize,
) {
    let line_num = diff_line
        .old_lineno
        .map(|n| format!("{:>4}", n))
        .unwrap_or_else(|| "    ".to_string());

    spans.push(Span::styled(format!("{} ", line_num), styles::dim_style()));
    spans.push(Span::styled("-".to_string(), styles::diff_del_style()));

    // Use syntax highlighting if available
    if let Some(ref highlighted) = diff_line.highlighted_spans {
        let content_spans =
            truncate_or_pad_spans(highlighted, content_width, styles::diff_del_style());
        spans.extend(content_spans);
    } else {
        // Fall back to plain text
        let content = truncate_or_pad(&diff_line.content, content_width);
        spans.push(Span::styled(content, styles::diff_del_style()));
    }
}

/// Add addition line spans to the spans vector
fn add_addition_spans(
    spans: &mut Vec<Span>,
    diff_line: &crate::model::DiffLine,
    content_width: usize,
) {
    let line_num = diff_line
        .new_lineno
        .map(|n| format!("{:>4}", n))
        .unwrap_or_else(|| "    ".to_string());

    spans.push(Span::styled(format!("{} ", line_num), styles::dim_style()));
    spans.push(Span::styled("+".to_string(), styles::diff_add_style()));

    // Use syntax highlighting if available
    if let Some(ref highlighted) = diff_line.highlighted_spans {
        let content_spans =
            truncate_or_pad_spans(highlighted, content_width, styles::diff_add_style());
        spans.extend(content_spans);
    } else {
        // Fall back to plain text
        let content = truncate_or_pad(&diff_line.content, content_width);
        spans.push(Span::styled(content, styles::diff_add_style()));
    }
}

/// Add empty column spans (for when one side has no content)
fn add_empty_column_spans(spans: &mut Vec<Span>, content_width: usize) {
    // line_num(4) + space(1) + prefix(1) + content
    spans.push(Span::styled(
        " ".repeat(5 + 1 + content_width),
        Style::default(),
    ));
}

/// Add comments for a specific line
fn add_comments_to_line(
    line_num: u32,
    line_comments: &std::collections::HashMap<u32, Vec<crate::model::Comment>>,
    side: LineSide,
    ctx: &SideBySideContext,
    mut line_idx: usize,
    lines: &mut Vec<Line>,
) -> usize {
    if let Some(comments) = line_comments.get(&line_num) {
        for comment in comments {
            let comment_side = comment.side.unwrap_or(LineSide::New);
            if (side == LineSide::Old && comment_side == LineSide::Old)
                || (side == LineSide::New && comment_side != LineSide::Old)
            {
                let comment_lines = comment_panel::format_comment_lines(
                    comment.comment_type,
                    &comment.content,
                    Some(line_num),
                );
                for mut comment_line in comment_lines {
                    let indicator = cursor_indicator(line_idx, ctx.current_line_idx);
                    comment_line.spans.insert(
                        0,
                        Span::styled(indicator, styles::current_line_indicator_style()),
                    );
                    lines.push(comment_line);
                    line_idx += 1;
                }
            }
        }
    }
    line_idx
}

/// Truncate or pad a string to a specific width
fn truncate_or_pad(s: &str, width: usize) -> String {
    let char_count = s.chars().count();
    if char_count > width {
        s.chars().take(width.saturating_sub(3)).collect::<String>() + "..."
    } else {
        format!("{:width$}", s, width = width)
    }
}

/// Truncate or pad highlighted spans to a specific display width
/// Uses unicode width to properly handle wide characters (CJK, emoji, etc.)
/// Returns a vector of spans that fits exactly within the width
fn truncate_or_pad_spans(
    spans: &[(Style, String)],
    width: usize,
    base_style: Style,
) -> Vec<Span<'static>> {
    // Count total display width
    let total_width: usize = spans.iter().map(|(_, text)| text.width()).sum();

    if total_width > width {
        // Need to truncate
        let mut result = Vec::new();
        let mut remaining = width.saturating_sub(3); // Reserve space for "..."

        for (style, text) in spans {
            if remaining == 0 {
                break;
            }

            let text_width = text.width();
            if text_width <= remaining {
                result.push(Span::styled(text.clone(), *style));
                remaining -= text_width;
            } else {
                // Truncate this span character by character to fit remaining width
                let mut truncated = String::new();
                let mut current_width = 0;
                for c in text.chars() {
                    let char_width = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                    if current_width + char_width > remaining {
                        break;
                    }
                    truncated.push(c);
                    current_width += char_width;
                }
                if !truncated.is_empty() {
                    result.push(Span::styled(truncated, *style));
                }
                remaining = 0;
            }
        }

        // Add ellipsis
        result.push(Span::styled("...".to_string(), base_style));
        result
    } else if total_width < width {
        // Need to pad
        let mut result: Vec<Span> = spans
            .iter()
            .map(|(style, text)| Span::styled(text.clone(), *style))
            .collect();

        // Add padding
        let padding = " ".repeat(width - total_width);
        result.push(Span::styled(padding, base_style));
        result
    } else {
        // Perfect fit
        spans
            .iter()
            .map(|(style, text)| Span::styled(text.clone(), *style))
            .collect()
    }
}

/// Apply horizontal scroll to a line while preserving the first span (cursor indicator)
fn apply_horizontal_scroll(line: Line, scroll_x: usize) -> Line {
    if scroll_x == 0 || line.spans.is_empty() {
        return line;
    }

    let mut spans: Vec<Span> = line.spans.into_iter().collect();

    // Preserve the first span (indicator)
    let indicator = spans.remove(0);

    // Skip scroll_x characters from the remaining spans
    let mut chars_to_skip = scroll_x;
    let mut new_spans = vec![indicator];

    for span in spans {
        let content = span.content.to_string();
        let char_count = content.chars().count();
        if chars_to_skip >= char_count {
            chars_to_skip -= char_count;
            // Skip this span entirely
        } else if chars_to_skip > 0 {
            // Partially skip this span
            let new_content: String = content.chars().skip(chars_to_skip).collect();
            chars_to_skip = 0;
            new_spans.push(Span::styled(new_content, span.style));
        } else {
            // Keep this span as-is
            new_spans.push(Span::styled(content, span.style));
        }
    }

    Line::from(new_spans)
}