giff 0.2.0

Visualizes the differences between the current HEAD and a specified branch in a git repository using a formatted table output in your terminal. The differences are displayed with color-coded additions and deletions for better readability.
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
use crate::diff::{self, FileChanges};
use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::widgets::Clear;
use ratatui::{
    prelude::*,
    style::{Color, Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Borders, List, ListItem, Paragraph},
    Frame, Terminal,
};
use std::collections::HashMap;
use std::process::Command;
use std::{error::Error, io};

enum AppMode {
    Diff,
    Rebase,
}

#[derive(Clone, PartialEq)]
enum ChangeState {
    Unselected,
    Accepted,
    Rejected,
}

#[derive(Clone, PartialEq)]
struct Change {
    line_num: usize,
    content: String,
    paired_content: Option<String>, // The paired line (if any)
    state: ChangeState,
    is_base: bool,
    context: Vec<String>,
}

struct App<'a> {
    file_changes: &'a FileChanges,
    branch: &'a str,
    current_file_idx: usize,
    file_names: Vec<String>,
    scroll_positions: HashMap<String, u16>,
    focused_pane: Pane,
    view_mode: ViewMode,
    app_mode: AppMode,
    rebase_changes: HashMap<String, Vec<Change>>,
    current_change_idx: usize,
    rebase_notification: Option<String>,
    show_rebase_modal: bool,
}

enum Pane {
    FileList,
    DiffContent,
}

enum ViewMode {
    SideBySide,
    Unified,
}

pub fn run_app(file_changes: FileChanges, branch: &str) -> Result<(), Box<dyn Error>> {
    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    // Create app state
    let file_names: Vec<String> = file_changes.keys().cloned().collect();
    let file_names_sorted = {
        let mut names = file_names.clone();
        names.sort();
        names
    };

    let mut scroll_positions = HashMap::new();
    for name in &file_names_sorted {
        scroll_positions.insert(name.clone(), 0);
    }

    // Check if rebase is needed
    let rebase_notification = diff::check_rebase_needed()?;

    let app = App {
        file_changes: &file_changes,
        branch,
        current_file_idx: 0,
        file_names: file_names_sorted,
        scroll_positions,
        focused_pane: Pane::FileList,
        view_mode: ViewMode::SideBySide,
        app_mode: AppMode::Diff,
        rebase_changes: HashMap::new(),
        current_change_idx: 0,
        rebase_notification: rebase_notification.clone(),
        show_rebase_modal: rebase_notification.is_some(),
    };

    // Run the main loop
    let res = run_ui(&mut terminal, app);

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    if let Err(err) = res {
        println!("{:?}", err)
    }

    Ok(())
}

fn prepare_rebase_changes(app: &mut App) {
    app.rebase_changes.clear();

    for file_name in &app.file_names {
        if let Some((base_lines, head_lines)) = app.file_changes.get(file_name) {
            let mut changes = Vec::new();

            // Helper function to extract context (3 lines before and after)
            let get_context = |lines: &[(usize, String)], line_num: usize| -> Vec<String> {
                let mut context = Vec::new();
                let start = if line_num > 3 { line_num - 3 } else { 1 };

                // Context lines before the change
                for i in start..line_num {
                    if let Some((_, line)) = lines.iter().find(|(num, _)| *num == i) {
                        context.push(format!("{}: {}", i, line));
                    }
                }

                // Context lines after the change
                for i in line_num + 1..=line_num + 3 {
                    if let Some((_, line)) = lines.iter().find(|(num, _)| *num == i) {
                        context.push(format!("{}: {}", i, line));
                    }
                }

                context
            };

            // First, find corresponding deleted/added lines to pair them
            let mut paired_changes = HashMap::new();

            // Map line numbers to their content for easier matching
            let mut base_map = HashMap::new();
            for (line_num, line) in base_lines {
                if line.starts_with('-') {
                    base_map.insert(*line_num, line.clone());
                }
            }

            let mut head_map = HashMap::new();
            for (line_num, line) in head_lines {
                if line.starts_with('+') {
                    head_map.insert(*line_num, line.clone());
                }
            }

            // Try to match lines - this is a simple approach
            // For more sophisticated matching, you'd need a diff algorithm
            for (base_num, base_line) in &base_map {
                let _base_content = base_line.strip_prefix('-').unwrap_or(base_line);

                // Try to find a matching added line with similar content
                for (head_num, head_line) in &head_map {
                    let _head_content = head_line.strip_prefix('+').unwrap_or(head_line);

                    // If line numbers are close and content is similar - pair them
                    // This is a very simplistic approach and might need refinement
                    if (*head_num as isize - *base_num as isize).abs() < 5 {
                        paired_changes.insert(*base_num, *head_num);
                        break;
                    }
                }
            }

            // Add removed lines from base with their paired added lines
            for (line_num, line) in base_lines {
                if line.starts_with('-') {
                    let context = get_context(base_lines, *line_num);

                    // Check if this line has a paired addition
                    let paired_head_num = paired_changes.get(line_num);
                    let paired_content = paired_head_num
                        .and_then(|head_num| head_map.get(head_num))
                        .cloned();

                    changes.push(Change {
                        line_num: *line_num,
                        content: line.clone(),
                        paired_content,
                        state: ChangeState::Unselected,
                        is_base: true,
                        context,
                    });
                }
            }

            // Add added lines from head that weren't paired
            for (line_num, line) in head_lines {
                if line.starts_with('+') && !paired_changes.values().any(|num| num == line_num) {
                    let context = get_context(head_lines, *line_num);
                    changes.push(Change {
                        line_num: *line_num,
                        content: line.clone(),
                        paired_content: None,
                        state: ChangeState::Unselected,
                        is_base: false,
                        context,
                    });
                }
            }

            // Sort by line number
            changes.sort_by_key(|change| change.line_num);

            app.rebase_changes.insert(file_name.clone(), changes);
        }
    }

    app.current_change_idx = 0;
}

fn run_ui<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
    loop {
        terminal.draw(|f| ui(f, &mut app))?;

        if let Event::Key(key) = event::read()? {
            if key.kind == KeyEventKind::Press {
                // Handle rebase modal if shown
                if app.show_rebase_modal {
                    match key.code {
                        KeyCode::Char('r') => {
                            // Get upstream branch
                            if let Ok(output) = Command::new("git")
                                .args(["rev-parse", "--abbrev-ref", "HEAD@{u}"])
                                .output()
                            {
                                if output.status.success() {
                                    let upstream =
                                        String::from_utf8_lossy(&output.stdout).trim().to_string();
                                    // Perform rebase
                                    match diff::perform_rebase(&upstream) {
                                        Ok(success) => {
                                            if success {
                                                // Rebase successful
                                                app.show_rebase_modal = false;
                                                app.rebase_notification = Some(
                                                    "Rebase completed successfully!".to_string(),
                                                );
                                                // We'd update file_changes here, but it's immutable in your structure
                                                // We'll need to switch back to diff mode
                                            } else {
                                                app.rebase_notification = Some(
                                                         "Rebase failed. There might be conflicts to resolve.".to_string()
                                                     );
                                            }
                                        }
                                        Err(e) => {
                                            app.rebase_notification =
                                                Some(format!("Error during rebase: {}", e));
                                        }
                                    }
                                }
                            }
                        }
                        KeyCode::Char('i') => {
                            // Ignore rebase suggestion
                            app.show_rebase_modal = false;
                        }
                        KeyCode::Esc => {
                            // Dismiss modal
                            app.show_rebase_modal = false;
                        }
                        _ => {}
                    }
                    continue; // Skip other key processing when modal is shown
                }
                match key.code {
                    KeyCode::Char('q') | KeyCode::Esc => {
                        match app.app_mode {
                            AppMode::Diff => return Ok(()),
                            AppMode::Rebase => {
                                // Return to diff mode without applying changes
                                app.app_mode = AppMode::Diff;
                            }
                        }
                    }
                    KeyCode::Char('r') => {
                        if let AppMode::Diff = app.app_mode {
                            app.app_mode = AppMode::Rebase;
                            prepare_rebase_changes(&mut app);
                        }
                    }
                    KeyCode::Char('a') => {
                        if let AppMode::Rebase = app.app_mode {
                            if let Some(file) = app.file_names.get(app.current_file_idx) {
                                if let Some(changes) = app.rebase_changes.get_mut(file) {
                                    if app.current_change_idx < changes.len() {
                                        changes[app.current_change_idx].state =
                                            ChangeState::Accepted;
                                        // Auto-advance to next change
                                        if app.current_change_idx < changes.len() - 1 {
                                            app.current_change_idx += 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    KeyCode::Char('x') => {
                        if let AppMode::Rebase = app.app_mode {
                            if let Some(file) = app.file_names.get(app.current_file_idx) {
                                if let Some(changes) = app.rebase_changes.get_mut(file) {
                                    if app.current_change_idx < changes.len() {
                                        changes[app.current_change_idx].state =
                                            ChangeState::Rejected;
                                        // Auto-advance to next change
                                        if app.current_change_idx < changes.len() - 1 {
                                            app.current_change_idx += 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    KeyCode::Char('c') => {
                        if let AppMode::Rebase = app.app_mode {
                            // Commit rebase changes
                            let mut any_changes_applied = false;

                            for (file, changes) in &app.rebase_changes {
                                let mut changes_to_apply = Vec::new();

                                for change in changes {
                                    if change.state == ChangeState::Accepted {
                                        if change.is_base {
                                            // For removed lines that were accepted, we want to apply
                                            // the paired content (if available) or remove the line
                                            if let Some(paired_content) = &change.paired_content {
                                                // Apply the paired content
                                                let clean_content = paired_content
                                                    .strip_prefix('+')
                                                    .unwrap_or(paired_content);

                                                changes_to_apply.push((
                                                    change.line_num,
                                                    clean_content.to_string(),
                                                    true,
                                                ));
                                            } else {
                                                // Just mark the line for removal
                                                changes_to_apply.push((
                                                    change.line_num,
                                                    change.content.clone(),
                                                    true,
                                                ));
                                            }
                                        } else {
                                            // For added lines, apply normally
                                            changes_to_apply.push((
                                                change.line_num,
                                                change.content.clone(),
                                                true,
                                            ));
                                        }
                                    }
                                }

                                if !changes_to_apply.is_empty() {
                                    any_changes_applied = true;
                                    if let Err(e) = diff::apply_changes(file, &changes_to_apply) {
                                        // Handle error (could add a status message to the UI)
                                        eprintln!("Error applying changes to {}: {}", file, e);
                                    }
                                }
                            }

                            // Show success message (this would be better with a status message in the UI)
                            if any_changes_applied {
                                // Could add a flash message here if the UI supported it
                            }

                            // Return to diff mode
                            app.app_mode = AppMode::Diff;
                        }
                    }
                    KeyCode::Char('j') | KeyCode::Down => match app.app_mode {
                        AppMode::Diff => match app.focused_pane {
                            Pane::FileList => {
                                if app.current_file_idx < app.file_names.len() - 1 {
                                    app.current_file_idx += 1;
                                }
                            }
                            Pane::DiffContent => {
                                if let Some(file) = app.file_names.get(app.current_file_idx) {
                                    let scroll =
                                        app.scroll_positions.get(file).unwrap_or(&0).clone();
                                    app.scroll_positions.insert(file.clone(), scroll + 1);
                                }
                            }
                        },
                        AppMode::Rebase => {
                            if let Some(file) = app.file_names.get(app.current_file_idx) {
                                if let Some(changes) = app.rebase_changes.get(file) {
                                    if !changes.is_empty()
                                        && app.current_change_idx < changes.len() - 1
                                    {
                                        app.current_change_idx += 1;
                                    }
                                }
                            }
                        }
                    },
                    KeyCode::Char('k') | KeyCode::Up => match app.app_mode {
                        AppMode::Diff => match app.focused_pane {
                            Pane::FileList => {
                                if app.current_file_idx > 0 {
                                    app.current_file_idx -= 1;
                                }
                            }
                            Pane::DiffContent => {
                                if let Some(file) = app.file_names.get(app.current_file_idx) {
                                    let scroll =
                                        app.scroll_positions.get(file).unwrap_or(&0).clone();
                                    if scroll > 0 {
                                        app.scroll_positions.insert(file.clone(), scroll - 1);
                                    }
                                }
                            }
                        },
                        AppMode::Rebase => {
                            if app.current_change_idx > 0 {
                                app.current_change_idx -= 1;
                            }
                        }
                    },
                    KeyCode::Tab => {
                        // Toggle between file list and diff content (only in diff mode)
                        if let AppMode::Diff = app.app_mode {
                            app.focused_pane = match app.focused_pane {
                                Pane::FileList => Pane::DiffContent,
                                Pane::DiffContent => Pane::FileList,
                            }
                        }
                    }
                    KeyCode::Char('h') | KeyCode::Left => {
                        if let AppMode::Diff = app.app_mode {
                            app.focused_pane = Pane::FileList;
                        }
                    }
                    KeyCode::Char('l') | KeyCode::Right => {
                        if let AppMode::Diff = app.app_mode {
                            app.focused_pane = Pane::DiffContent;
                        }
                    }
                    KeyCode::Char('u') => {
                        // Toggle between unified and side-by-side view (only in diff mode)
                        if let AppMode::Diff = app.app_mode {
                            app.view_mode = match app.view_mode {
                                ViewMode::SideBySide => ViewMode::Unified,
                                ViewMode::Unified => ViewMode::SideBySide,
                            }
                        }
                    }
                    KeyCode::Char('n') => {
                        // Navigate to next file with changes in rebase mode
                        if let AppMode::Rebase = app.app_mode {
                            let mut next_idx = app.current_file_idx;
                            let mut found = false;

                            // Look for the next file with changes
                            while next_idx < app.file_names.len() - 1 {
                                next_idx += 1;
                                if let Some(changes) =
                                    app.rebase_changes.get(&app.file_names[next_idx])
                                {
                                    if !changes.is_empty() {
                                        app.current_file_idx = next_idx;
                                        app.current_change_idx = 0;
                                        found = true;
                                        break;
                                    }
                                }
                            }

                            // If no more files with changes after current, loop to beginning
                            if !found {
                                for (idx, file_name) in app.file_names.iter().enumerate() {
                                    if idx >= app.current_file_idx {
                                        continue;
                                    }

                                    if let Some(changes) = app.rebase_changes.get(file_name) {
                                        if !changes.is_empty() {
                                            app.current_file_idx = idx;
                                            app.current_change_idx = 0;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    KeyCode::Char('p') => {
                        // Navigate to previous file with changes in rebase mode
                        if let AppMode::Rebase = app.app_mode {
                            let mut prev_idx = app.current_file_idx;
                            let mut found = false;

                            // Look for the previous file with changes
                            while prev_idx > 0 {
                                prev_idx -= 1;
                                if let Some(changes) =
                                    app.rebase_changes.get(&app.file_names[prev_idx])
                                {
                                    if !changes.is_empty() {
                                        app.current_file_idx = prev_idx;
                                        app.current_change_idx = 0;
                                        found = true;
                                        break;
                                    }
                                }
                            }

                            // If no more files with changes before current, loop to end
                            if !found {
                                for (idx, file_name) in app.file_names.iter().enumerate().rev() {
                                    if idx <= app.current_file_idx {
                                        continue;
                                    }

                                    if let Some(changes) = app.rebase_changes.get(file_name) {
                                        if !changes.is_empty() {
                                            app.current_file_idx = idx;
                                            app.current_change_idx = 0;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}

fn ui(f: &mut Frame, app: &mut App) {
    let size = f.size();

    // Create main layout with 3 parts: header, content, footer
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Main content
            Constraint::Length(3), // Help
        ])
        .split(size);

    // Render header with title and controls
    render_header(f, app, main_chunks[0]);

    // Main content depends on the app mode
    match app.app_mode {
        AppMode::Diff => {
            // Render diff mode content
            match app.view_mode {
                ViewMode::SideBySide => {
                    let content_chunks = Layout::default()
                        .direction(Direction::Horizontal)
                        .constraints([
                            Constraint::Percentage(20), // File list
                            Constraint::Percentage(40), // Base content
                            Constraint::Percentage(40), // Head content
                        ])
                        .split(main_chunks[1]);

                    // Render file list
                    render_file_list(f, app, content_chunks[0]);

                    // Only render content if files exist
                    if !app.file_names.is_empty() {
                        // Render base content
                        render_base_content(f, app, content_chunks[1]);

                        // Render head content
                        render_head_content(f, app, content_chunks[2]);
                    }
                }
                ViewMode::Unified => {
                    let content_chunks = Layout::default()
                        .direction(Direction::Horizontal)
                        .constraints([
                            Constraint::Percentage(20), // File list
                            Constraint::Percentage(80), // Unified content
                        ])
                        .split(main_chunks[1]);

                    // Render file list
                    render_file_list(f, app, content_chunks[0]);

                    // Only render content if files exist
                    if !app.file_names.is_empty() {
                        // Render unified diff
                        render_unified_diff(f, app, content_chunks[1]);
                    }
                }
            }
        }
        AppMode::Rebase => {
            // Render rebase mode content
            render_rebase_ui(f, app, main_chunks[1]);
        }
    }

    // Render help footer
    render_help(f, app, main_chunks[2]);

    // Render rebase notification if needed
    if app.show_rebase_modal {
        render_rebase_notification(f, app, size);
    }
}

fn render_header(f: &mut Frame, app: &App, area: Rect) {
    let view_mode_text = match app.view_mode {
        ViewMode::SideBySide => "Side-by-Side",
        ViewMode::Unified => "Unified",
    };
    let title = format!(
        " giff - Comparing {} to HEAD [{}] ",
        app.branch, view_mode_text
    );
    let header = Paragraph::new(title)
        .style(Style::default().fg(Color::White).bg(Color::Blue))
        .block(Block::default().borders(Borders::ALL));
    f.render_widget(header, area);
}

fn render_file_list(f: &mut Frame, app: &App, area: Rect) {
    let items: Vec<ListItem> = app
        .file_names
        .iter()
        .enumerate()
        .map(|(i, file)| {
            let content = Line::from(Span::styled(
                file.clone(),
                Style::default().add_modifier(if i == app.current_file_idx {
                    Modifier::BOLD
                } else {
                    Modifier::empty()
                }),
            ));
            ListItem::new(content)
        })
        .collect();

    let files_list = List::new(items)
        .block(Block::default().title("Files").borders(Borders::ALL))
        .highlight_style(
            Style::default()
                .bg(Color::Blue)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol(">> ");

    // Use different style if FileList is focused
    let files_list = match app.focused_pane {
        Pane::FileList => files_list.block(
            Block::default()
                .title("Files")
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Yellow)),
        ),
        _ => files_list,
    };

    f.render_stateful_widget(
        files_list,
        area,
        &mut ratatui::widgets::ListState::default().with_selected(Some(app.current_file_idx)),
    );
}

fn render_base_content(f: &mut Frame, app: &App, area: Rect) {
    let current_file = if let Some(file) = app.file_names.get(app.current_file_idx) {
        file
    } else {
        return; // No file selected
    };

    let (base_lines, _) = if let Some(changes) = app.file_changes.get(current_file) {
        changes
    } else {
        return; // File not found in changes
    };

    let scroll = app.scroll_positions.get(current_file).unwrap_or(&0);

    let content = Text::from(
        base_lines
            .iter()
            .map(|(line_num, line)| {
                let color = if line.starts_with('-') {
                    Color::Red
                } else if line.starts_with('+') {
                    Color::Green
                } else {
                    Color::White
                };

                Line::from(Span::styled(
                    format!("{:4} {}", line_num, line),
                    Style::default().fg(color),
                ))
            })
            .collect::<Vec<Line>>(),
    );

    let base_paragraph = Paragraph::new(content)
        .block(
            Block::default()
                .title(format!("{} ({})", app.branch, current_file))
                .borders(Borders::ALL),
        )
        .scroll((*scroll, 0));

    // Use different style if DiffContent is focused
    let base_paragraph = match app.focused_pane {
        Pane::DiffContent => base_paragraph.block(
            Block::default()
                .title(format!("{} ({})", app.branch, current_file))
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Yellow)),
        ),
        _ => base_paragraph,
    };

    f.render_widget(base_paragraph, area);
}

fn render_head_content(f: &mut Frame, app: &App, area: Rect) {
    let current_file = if let Some(file) = app.file_names.get(app.current_file_idx) {
        file
    } else {
        return; // No file selected
    };

    let (_, head_lines) = if let Some(changes) = app.file_changes.get(current_file) {
        changes
    } else {
        return; // File not found in changes
    };

    let scroll = app.scroll_positions.get(current_file).unwrap_or(&0);

    let content = Text::from(
        head_lines
            .iter()
            .map(|(line_num, line)| {
                let color = if line.starts_with('-') {
                    Color::Red
                } else if line.starts_with('+') {
                    Color::Green
                } else {
                    Color::White
                };

                Line::from(Span::styled(
                    format!("{:4} {}", line_num, line),
                    Style::default().fg(color),
                ))
            })
            .collect::<Vec<Line>>(),
    );

    let head_paragraph = Paragraph::new(content)
        .block(
            Block::default()
                .title(format!("HEAD ({})", current_file))
                .borders(Borders::ALL),
        )
        .scroll((*scroll, 0));

    // Use different style if DiffContent is focused
    let head_paragraph = match app.focused_pane {
        Pane::DiffContent => head_paragraph.block(
            Block::default()
                .title(format!("HEAD ({})", current_file))
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Yellow)),
        ),
        _ => head_paragraph,
    };

    f.render_widget(head_paragraph, area);
}

fn render_unified_diff(f: &mut Frame, app: &App, area: Rect) {
    let current_file = if let Some(file) = app.file_names.get(app.current_file_idx) {
        file
    } else {
        return; // No file selected
    };

    let (base_lines, head_lines) = if let Some(changes) = app.file_changes.get(current_file) {
        changes
    } else {
        return; // File not found in changes
    };

    let scroll = app.scroll_positions.get(current_file).unwrap_or(&0);

    // Create unified diff by interleaving lines
    let mut unified_content = Vec::new();

    // Collect all line numbers from both sides
    let mut all_lines: Vec<(usize, bool)> = Vec::new(); // (line_number, is_head)
    for (num, _) in base_lines {
        all_lines.push((*num, false));
    }
    for (num, _) in head_lines {
        all_lines.push((*num, true));
    }

    // Sort by line number
    all_lines.sort_by_key(|(num, _)| *num);

    // Process lines
    let mut processed_lines = Vec::new();
    for (num, is_head) in all_lines {
        if is_head {
            // Find this line in head_lines
            if let Some((_, line)) = head_lines.iter().find(|(line_num, _)| *line_num == num) {
                if !line.starts_with('-') && !processed_lines.contains(&num) {
                    unified_content.push(Line::from(Span::styled(
                        format!("{:4} {}", num, line),
                        Style::default().fg(if line.starts_with('+') {
                            Color::Green
                        } else {
                            Color::White
                        }),
                    )));
                    processed_lines.push(num);
                }
            }
        } else {
            // Find this line in base_lines
            if let Some((_, line)) = base_lines.iter().find(|(line_num, _)| *line_num == num) {
                if !line.starts_with('+') && !processed_lines.contains(&num) {
                    unified_content.push(Line::from(Span::styled(
                        format!("{:4} {}", num, line),
                        Style::default().fg(if line.starts_with('-') {
                            Color::Red
                        } else {
                            Color::White
                        }),
                    )));
                    processed_lines.push(num);
                }
            }
        }
    }

    let unified_paragraph = Paragraph::new(Text::from(unified_content))
        .block(
            Block::default()
                .title(format!(
                    "Unified Diff: {} vs HEAD ({})",
                    app.branch, current_file
                ))
                .borders(Borders::ALL),
        )
        .scroll((*scroll, 0));

    // Use different style if DiffContent is focused
    let unified_paragraph = match app.focused_pane {
        Pane::DiffContent => unified_paragraph.block(
            Block::default()
                .title(format!(
                    "Unified Diff: {} vs HEAD ({})",
                    app.branch, current_file
                ))
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::Yellow)),
        ),
        _ => unified_paragraph,
    };

    f.render_widget(unified_paragraph, area);
}

fn render_rebase_ui(f: &mut Frame, app: &App, area: Rect) {
    // First, clear the background by rendering a filled block
    let clear_block = Block::default()
        .style(Style::default().bg(Color::Black)) // Use the terminal's default background
        .borders(Borders::NONE);
    f.render_widget(clear_block, area);

    // Now, set up the rebase UI layout
    let content_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(20), // File list
            Constraint::Percentage(80), // Rebase content
        ])
        .split(area);

    // Render file list
    render_file_list(f, app, content_chunks[0]);

    // Render rebase content area
    if !app.file_names.is_empty() {
        let current_file = &app.file_names[app.current_file_idx];

        // Create a clean background for the rebase area
        let rebase_bg = Block::default()
            .style(Style::default().bg(Color::Black))
            .borders(Borders::ALL)
            .title(format!("Rebase: {}", current_file));
        f.render_widget(&rebase_bg, content_chunks[1]);

        let inner_area = rebase_bg.inner(content_chunks[1]);

        if let Some(changes) = app.rebase_changes.get(current_file) {
            if changes.is_empty() {
                // Show a message if there are no changes
                let no_changes_text = Paragraph::new("No changes to rebase in this file")
                    .style(Style::default().fg(Color::White))
                    .alignment(Alignment::Center);

                f.render_widget(no_changes_text, inner_area);
                return;
            }

            // Split the rebase area into current change and context
            let rebase_chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Percentage(40), // Current change
                    Constraint::Percentage(60), // Context
                ])
                .split(inner_area);

            // Current change section
            if app.current_change_idx < changes.len() {
                let current_change = &changes[app.current_change_idx];

                // Format the current change nicely
                let change_type = if current_change.is_base {
                    "Removed"
                } else {
                    "Added"
                };
                let state_symbol = match current_change.state {
                    ChangeState::Unselected => "[ ]",
                    ChangeState::Accepted => "[✓]",
                    ChangeState::Rejected => "[✗]",
                };

                let line_content = current_change
                    .content
                    .strip_prefix('+')
                    .or_else(|| current_change.content.strip_prefix('-'))
                    .unwrap_or(&current_change.content);

                let header = format!(
                    "{} {} (Line {})",
                    state_symbol, change_type, current_change.line_num
                );

                let mut content_text = vec![
                    Line::from(Span::styled(
                        header,
                        Style::default()
                            .fg(Color::White)
                            .add_modifier(Modifier::BOLD),
                    )),
                    Line::from(""),
                    Line::from(Span::styled(
                        format!("Current: {}", line_content),
                        Style::default()
                            .fg(if current_change.is_base {
                                Color::Red
                            } else {
                                Color::Green
                            })
                            .add_modifier(Modifier::BOLD),
                    )),
                ];

                // If there's paired content (for changed lines), show it
                if let Some(paired_content) = &current_change.paired_content {
                    let paired_text = paired_content
                        .strip_prefix('+')
                        .or_else(|| paired_content.strip_prefix('-'))
                        .unwrap_or(paired_content);

                    content_text.push(Line::from(""));
                    content_text.push(Line::from(Span::styled(
                        format!("Incoming: {}", paired_text),
                        Style::default()
                            .fg(Color::Green)
                            .add_modifier(Modifier::BOLD),
                    )));

                    // Add explicit choice text for removed lines
                    if current_change.is_base {
                        content_text.push(Line::from(""));
                        content_text.push(Line::from(Span::styled(
                            "Press 'a' to ACCEPT the incoming change (green)",
                            Style::default().fg(Color::Green),
                        )));
                        content_text.push(Line::from(Span::styled(
                            "Press 'x' to KEEP the current line and reject the incoming change",
                            Style::default().fg(Color::Red),
                        )));
                    }
                }

                let change_block = Paragraph::new(Text::from(content_text))
                    .block(
                        Block::default()
                            .title(format!(
                                "Change {}/{}",
                                app.current_change_idx + 1,
                                changes.len()
                            ))
                            .borders(Borders::ALL)
                            .border_style(Style::default().fg(Color::Yellow)),
                    )
                    .alignment(Alignment::Left);

                f.render_widget(change_block, rebase_chunks[0]);

                // Context section
                let mut context_lines = Vec::new();
                context_lines.push(Line::from(Span::styled(
                    "Context:",
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                )));
                context_lines.push(Line::from(""));

                for line in &current_change.context {
                    context_lines.push(Line::from(Span::styled(
                        line,
                        Style::default().fg(Color::Gray),
                    )));
                }

                // Add instructions
                context_lines.push(Line::from(""));
                context_lines.push(Line::from(Span::styled(
                    "Press 'a' to accept this change",
                    Style::default().fg(Color::Green),
                )));
                context_lines.push(Line::from(Span::styled(
                    "Press 'x' to reject this change",
                    Style::default().fg(Color::Red),
                )));
                context_lines.push(Line::from(Span::styled(
                    "Press 'j'/'k' to navigate between changes",
                    Style::default().fg(Color::White),
                )));
                context_lines.push(Line::from(Span::styled(
                    "Press 'n'/'p' to navigate between files",
                    Style::default().fg(Color::White),
                )));
                context_lines.push(Line::from(Span::styled(
                    "Press 'c' to commit all accepted changes",
                    Style::default().fg(Color::Yellow),
                )));
                context_lines.push(Line::from(Span::styled(
                    "Press 'Esc' or 'q' to cancel and return to diff view",
                    Style::default().fg(Color::White),
                )));

                let context_block = Paragraph::new(Text::from(context_lines)).block(
                    Block::default()
                        .title("Context and Help")
                        .borders(Borders::ALL),
                );

                f.render_widget(context_block, rebase_chunks[1]);
            }
        } else {
            // Show message if no changes for this file
            let no_changes_text = Paragraph::new("No changes found for this file")
                .style(Style::default().fg(Color::White))
                .alignment(Alignment::Center);

            f.render_widget(no_changes_text, inner_area);
        }
    }
}

fn render_rebase_notification(f: &mut Frame, app: &App, area: Rect) {
    if let Some(notification) = &app.rebase_notification {
        // Calculate modal size
        let mut max_line_length = 0;
        let mut line_count = 0;
        for line in notification.lines() {
            max_line_length = max_line_length.max(line.len());
            line_count += 1;
        }
        let modal_width = (max_line_length as u16 + 4).min(80);
        let modal_height = (line_count as u16 + 6).min(20);

        let modal_area = centered_rect(modal_width, modal_height, area);

        // Render background
        let background = Block::default()
            .style(Style::default().bg(Color::Black))
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Yellow))
            .title("Rebase Recommended");

        f.render_widget(Clear, modal_area); // Clear the area
        f.render_widget(&background, modal_area);

        let inner_area = background.inner(modal_area);

        // Split into message area and buttons
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(line_count as u16 + 2),
                Constraint::Length(3),
            ])
            .split(inner_area);

        // Render notification message
        let message = Paragraph::new(notification.clone())
            .style(Style::default().fg(Color::White))
            .alignment(Alignment::Center)
            .wrap(ratatui::widgets::Wrap { trim: true });

        f.render_widget(message, chunks[0]);

        // Render buttons
        let buttons = Paragraph::new("Press 'r' to rebase now   Press 'i' to ignore")
            .style(Style::default().fg(Color::White))
            .alignment(Alignment::Center);

        f.render_widget(buttons, chunks[1]);
    }
}

fn centered_rect(width: u16, height: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - height * 100 / r.height) / 2),
            Constraint::Length(height),
            Constraint::Percentage((100 - height * 100 / r.height) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - width * 100 / r.width) / 2),
            Constraint::Length(width),
            Constraint::Percentage((100 - width * 100 / r.width) / 2),
        ])
        .split(popup_layout[1])[1]
}

fn render_help(f: &mut Frame, app: &App, area: Rect) {
    let help_text = match app.app_mode {
        AppMode::Diff => "Esc/q: Quit | j/k: Navigate | Tab: Change focus | h/l: Switch panes | u: Toggle view | r: Enter rebase mode",
        AppMode::Rebase => "Esc/q: Cancel | j/k: Navigate changes | a: Accept change | x: Reject change | c: Commit changes",
    };

    let help = Paragraph::new(help_text)
        .style(Style::default().fg(Color::White))
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL));
    f.render_widget(help, area);
}