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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
use std::path::PathBuf;

use crate::error::{Result, TuicrError};
use crate::git::{
    CommitInfo, RepoInfo, get_commit_range_diff, get_recent_commits, get_working_tree_diff,
};
use crate::model::{Comment, CommentType, DiffFile, LineSide, ReviewSession};
use crate::persistence::{find_session_for_repo, load_session};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    Normal,
    Comment,
    Command,
    Help,
    Confirm,
    CommitSelect,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffSource {
    WorkingTree,
    CommitRange(Vec<String>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmAction {
    CopyAndQuit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusedPanel {
    FileList,
    Diff,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffViewMode {
    Unified,
    SideBySide,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageType {
    Info,
    Warning,
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    pub content: String,
    pub message_type: MessageType,
}

pub struct App {
    pub repo_info: RepoInfo,
    pub session: ReviewSession,
    pub diff_files: Vec<DiffFile>,
    pub diff_source: DiffSource,

    pub input_mode: InputMode,
    pub focused_panel: FocusedPanel,
    pub diff_view_mode: DiffViewMode,

    pub file_list_state: FileListState,
    pub diff_state: DiffState,
    pub command_buffer: String,
    pub comment_buffer: String,
    pub comment_cursor: usize,
    pub comment_type: CommentType,
    pub comment_is_file_level: bool,
    pub comment_line: Option<(u32, LineSide)>,
    pub editing_comment_id: Option<String>,

    // Commit selection state
    pub commit_list: Vec<CommitInfo>,
    pub commit_list_cursor: usize,
    pub commit_selected: Vec<bool>,

    pub should_quit: bool,
    pub dirty: bool,
    pub message: Option<Message>,
    pub pending_confirm: Option<ConfirmAction>,
    pub supports_keyboard_enhancement: bool,
}

#[derive(Debug, Default)]
pub struct FileListState {
    pub selected: usize,
}

#[derive(Debug, Default)]
pub struct DiffState {
    pub scroll_offset: usize,
    pub scroll_x: usize,    // Horizontal scroll offset
    pub cursor_line: usize, // Absolute position in the line list
    pub current_file_idx: usize,
    pub viewport_height: usize, // Set during render
}

/// Represents a comment location for deletion
enum CommentLocation {
    FileComment {
        path: std::path::PathBuf,
        index: usize,
    },
    LineComment {
        path: std::path::PathBuf,
        line: u32,
        side: LineSide,
        index: usize,
    },
}

impl App {
    pub fn new() -> Result<Self> {
        let repo_info = RepoInfo::discover()?;

        // Try to get working tree diff first
        let diff_result = get_working_tree_diff(&repo_info.repo);

        match diff_result {
            Ok(diff_files) => {
                // We have unstaged changes - normal flow
                let mut session = Self::load_or_create_session(&repo_info);

                // Ensure all current diff files are in the session
                for file in &diff_files {
                    let path = file.display_path().clone();
                    session.add_file(path, file.status);
                }

                Ok(Self {
                    repo_info,
                    session,
                    diff_files,
                    diff_source: DiffSource::WorkingTree,
                    input_mode: InputMode::Normal,
                    focused_panel: FocusedPanel::Diff,
                    diff_view_mode: DiffViewMode::Unified,
                    file_list_state: FileListState::default(),
                    diff_state: DiffState::default(),
                    command_buffer: String::new(),
                    comment_buffer: String::new(),
                    comment_cursor: 0,
                    comment_type: CommentType::Note,
                    comment_is_file_level: true,
                    comment_line: None,
                    editing_comment_id: None,
                    commit_list: Vec::new(),
                    commit_list_cursor: 0,
                    commit_selected: Vec::new(),
                    should_quit: false,
                    dirty: false,
                    message: None,
                    pending_confirm: None,
                    supports_keyboard_enhancement: false,
                })
            }
            Err(TuicrError::NoChanges) => {
                // No unstaged changes - try to get recent commits
                let commits = get_recent_commits(&repo_info.repo, 5)?;
                if commits.is_empty() {
                    return Err(TuicrError::NoChanges);
                }

                let commit_count = commits.len();
                let session =
                    ReviewSession::new(repo_info.root_path.clone(), repo_info.head_commit.clone());

                Ok(Self {
                    repo_info,
                    session,
                    diff_files: Vec::new(),
                    diff_source: DiffSource::WorkingTree,
                    input_mode: InputMode::CommitSelect,
                    focused_panel: FocusedPanel::Diff,
                    diff_view_mode: DiffViewMode::Unified,
                    file_list_state: FileListState::default(),
                    diff_state: DiffState::default(),
                    command_buffer: String::new(),
                    comment_buffer: String::new(),
                    comment_cursor: 0,
                    comment_type: CommentType::Note,
                    comment_is_file_level: true,
                    comment_line: None,
                    editing_comment_id: None,
                    commit_list: commits,
                    commit_list_cursor: 0,
                    commit_selected: vec![false; commit_count],
                    should_quit: false,
                    dirty: false,
                    message: None,
                    pending_confirm: None,
                    supports_keyboard_enhancement: false,
                })
            }
            Err(e) => Err(e),
        }
    }

    fn load_or_create_session(repo_info: &RepoInfo) -> ReviewSession {
        match find_session_for_repo(&repo_info.root_path) {
            Ok(Some(path)) => match load_session(&path) {
                Ok(s) => {
                    // Delete stale session file if base commit doesn't match
                    if s.base_commit != repo_info.head_commit {
                        let _ = std::fs::remove_file(&path);
                        ReviewSession::new(
                            repo_info.root_path.clone(),
                            repo_info.head_commit.clone(),
                        )
                    } else {
                        s
                    }
                }
                Err(_) => {
                    ReviewSession::new(repo_info.root_path.clone(), repo_info.head_commit.clone())
                }
            },
            _ => ReviewSession::new(repo_info.root_path.clone(), repo_info.head_commit.clone()),
        }
    }

    pub fn reload_diff_files(&mut self) -> Result<usize> {
        let current_path = self.current_file_path().cloned();
        let prev_file_idx = self.diff_state.current_file_idx;
        let prev_cursor_line = self.diff_state.cursor_line;
        let prev_viewport_offset = self
            .diff_state
            .cursor_line
            .saturating_sub(self.diff_state.scroll_offset);
        let prev_relative_line = if self.diff_files.is_empty() {
            0
        } else {
            let start = self.calculate_file_scroll_offset(self.diff_state.current_file_idx);
            prev_cursor_line.saturating_sub(start)
        };

        let diff_files = get_working_tree_diff(&self.repo_info.repo)?;

        for file in &diff_files {
            let path = file.display_path().clone();
            self.session.add_file(path, file.status);
        }

        self.diff_files = diff_files;

        if self.diff_files.is_empty() {
            self.diff_state.current_file_idx = 0;
            self.diff_state.cursor_line = 0;
            self.diff_state.scroll_offset = 0;
            self.file_list_state.selected = 0;
        } else {
            let target_idx = if let Some(path) = current_path {
                self.diff_files
                    .iter()
                    .position(|file| file.display_path() == &path)
                    .unwrap_or_else(|| prev_file_idx.min(self.diff_files.len().saturating_sub(1)))
            } else {
                prev_file_idx.min(self.diff_files.len().saturating_sub(1))
            };

            self.jump_to_file(target_idx);

            let file_start = self.calculate_file_scroll_offset(target_idx);
            let file_height = self.file_render_height(&self.diff_files[target_idx]);
            let relative_line = prev_relative_line.min(file_height.saturating_sub(1));
            self.diff_state.cursor_line = file_start.saturating_add(relative_line);

            let viewport = self.diff_state.viewport_height.max(1);
            let max_relative = viewport.saturating_sub(1);
            let relative_offset = prev_viewport_offset.min(max_relative);
            let total_lines = self.total_lines();
            if total_lines == 0 {
                self.diff_state.scroll_offset = 0;
            } else {
                let max_scroll = total_lines.saturating_sub(1);
                let desired = self
                    .diff_state
                    .cursor_line
                    .saturating_sub(relative_offset)
                    .min(max_scroll);
                self.diff_state.scroll_offset = desired;
            }

            self.ensure_cursor_visible();
            self.update_current_file_from_cursor();
        }

        Ok(self.diff_files.len())
    }

    pub fn current_file(&self) -> Option<&DiffFile> {
        self.diff_files.get(self.diff_state.current_file_idx)
    }

    pub fn current_file_path(&self) -> Option<&PathBuf> {
        self.current_file().map(|f| f.display_path())
    }

    pub fn toggle_reviewed(&mut self) {
        if let Some(path) = self.current_file_path().cloned()
            && let Some(review) = self.session.get_file_mut(&path)
        {
            review.reviewed = !review.reviewed;
            self.dirty = true;

            // Move cursor to the file header line
            let file_idx = self.diff_state.current_file_idx;
            let header_line = self.calculate_file_scroll_offset(file_idx);
            self.diff_state.cursor_line = header_line;
            self.ensure_cursor_visible();
        }
    }

    pub fn file_count(&self) -> usize {
        self.diff_files.len()
    }

    pub fn reviewed_count(&self) -> usize {
        self.session.reviewed_count()
    }

    pub fn set_message(&mut self, msg: impl Into<String>) {
        self.message = Some(Message {
            content: msg.into(),
            message_type: MessageType::Info,
        });
    }

    pub fn set_warning(&mut self, msg: impl Into<String>) {
        self.message = Some(Message {
            content: msg.into(),
            message_type: MessageType::Warning,
        });
    }

    pub fn set_error(&mut self, msg: impl Into<String>) {
        self.message = Some(Message {
            content: msg.into(),
            message_type: MessageType::Error,
        });
    }

    pub fn cursor_down(&mut self, lines: usize) {
        let max_line = self.total_lines().saturating_sub(1);
        self.diff_state.cursor_line = (self.diff_state.cursor_line + lines).min(max_line);
        self.ensure_cursor_visible();
        self.update_current_file_from_cursor();
    }

    pub fn cursor_up(&mut self, lines: usize) {
        self.diff_state.cursor_line = self.diff_state.cursor_line.saturating_sub(lines);
        self.ensure_cursor_visible();
        self.update_current_file_from_cursor();
    }

    pub fn scroll_down(&mut self, lines: usize) {
        // For half-page/page scrolling, move both cursor and scroll
        let max_line = self.total_lines().saturating_sub(1);
        self.diff_state.cursor_line = (self.diff_state.cursor_line + lines).min(max_line);
        self.diff_state.scroll_offset = (self.diff_state.scroll_offset + lines).min(max_line);
        self.ensure_cursor_visible();
        self.update_current_file_from_cursor();
    }

    pub fn scroll_up(&mut self, lines: usize) {
        // For half-page/page scrolling, move both cursor and scroll
        self.diff_state.cursor_line = self.diff_state.cursor_line.saturating_sub(lines);
        self.diff_state.scroll_offset = self.diff_state.scroll_offset.saturating_sub(lines);
        self.ensure_cursor_visible();
        self.update_current_file_from_cursor();
    }

    pub fn scroll_left(&mut self, cols: usize) {
        self.diff_state.scroll_x = self.diff_state.scroll_x.saturating_sub(cols);
    }

    pub fn scroll_right(&mut self, cols: usize) {
        self.diff_state.scroll_x = self.diff_state.scroll_x.saturating_add(cols);
    }

    fn ensure_cursor_visible(&mut self) {
        let viewport = self.diff_state.viewport_height.max(1);
        // If cursor is above the viewport, scroll up
        if self.diff_state.cursor_line < self.diff_state.scroll_offset {
            self.diff_state.scroll_offset = self.diff_state.cursor_line;
        }
        // If cursor is below the viewport, scroll down
        if self.diff_state.cursor_line >= self.diff_state.scroll_offset + viewport {
            self.diff_state.scroll_offset = self.diff_state.cursor_line - viewport + 1;
        }
    }

    pub fn center_cursor(&mut self) {
        let viewport = self.diff_state.viewport_height.max(1);
        let half_viewport = viewport / 2;
        self.diff_state.scroll_offset = self.diff_state.cursor_line.saturating_sub(half_viewport);
    }

    pub fn file_list_down(&mut self, n: usize) {
        let max_idx = self.diff_files.len().saturating_sub(1);
        let new_idx = (self.file_list_state.selected + n).min(max_idx);
        self.jump_to_file(new_idx);
    }

    pub fn file_list_up(&mut self, n: usize) {
        let new_idx = self.file_list_state.selected.saturating_sub(n);
        self.jump_to_file(new_idx);
    }

    pub fn jump_to_file(&mut self, idx: usize) {
        if idx < self.diff_files.len() {
            self.diff_state.current_file_idx = idx;
            self.diff_state.cursor_line = self.calculate_file_scroll_offset(idx);
            self.diff_state.scroll_offset = self.diff_state.cursor_line;
            self.file_list_state.selected = idx;
        }
    }

    pub fn next_file(&mut self) {
        let next =
            (self.diff_state.current_file_idx + 1).min(self.diff_files.len().saturating_sub(1));
        self.jump_to_file(next);
    }

    pub fn prev_file(&mut self) {
        let prev = self.diff_state.current_file_idx.saturating_sub(1);
        self.jump_to_file(prev);
    }

    pub fn next_hunk(&mut self) {
        // Find the next hunk header position after current cursor
        let mut cumulative = 0;
        for file in &self.diff_files {
            let path = file.display_path();

            // File header
            cumulative += 1;

            // If file is reviewed, skip all content
            if self.session.is_file_reviewed(path) {
                continue;
            }

            // File comments
            if let Some(review) = self.session.files.get(path) {
                cumulative += review.file_comments.len();
            }

            if file.is_binary || file.hunks.is_empty() {
                cumulative += 1; // "(binary file)" or "(no changes)"
            } else {
                for hunk in &file.hunks {
                    // This is a hunk header position
                    if cumulative > self.diff_state.cursor_line {
                        self.diff_state.cursor_line = cumulative;
                        self.ensure_cursor_visible();
                        self.update_current_file_from_cursor();
                        return;
                    }
                    cumulative += 1; // hunk header
                    cumulative += hunk.lines.len(); // diff lines
                }
            }
            cumulative += 1; // spacing
        }
    }

    pub fn prev_hunk(&mut self) {
        // Find the previous hunk header position before current cursor
        let mut hunk_positions: Vec<usize> = Vec::new();
        let mut cumulative = 0;

        for file in &self.diff_files {
            let path = file.display_path();

            cumulative += 1; // File header

            // If file is reviewed, skip all content
            if self.session.is_file_reviewed(path) {
                continue;
            }

            if let Some(review) = self.session.files.get(path) {
                cumulative += review.file_comments.len();
            }

            if file.is_binary || file.hunks.is_empty() {
                cumulative += 1;
            } else {
                for hunk in &file.hunks {
                    hunk_positions.push(cumulative);
                    cumulative += 1;
                    cumulative += hunk.lines.len();
                }
            }
            cumulative += 1;
        }

        // Find the last hunk position before current cursor
        for &pos in hunk_positions.iter().rev() {
            if pos < self.diff_state.cursor_line {
                self.diff_state.cursor_line = pos;
                self.ensure_cursor_visible();
                self.update_current_file_from_cursor();
                return;
            }
        }

        // If no previous hunk, go to start
        self.diff_state.cursor_line = 0;
        self.ensure_cursor_visible();
        self.update_current_file_from_cursor();
    }

    fn calculate_file_scroll_offset(&self, file_idx: usize) -> usize {
        let mut offset = 0;
        for (i, file) in self.diff_files.iter().enumerate() {
            if i == file_idx {
                break;
            }
            offset += self.file_render_height(file);
        }
        offset
    }

    fn file_render_height(&self, file: &DiffFile) -> usize {
        let path = file.display_path();

        // If reviewed, only show header (1 line total)
        if self.session.is_file_reviewed(path) {
            return 1;
        }

        let header_lines = 2;
        let content_lines: usize = file.hunks.iter().map(|h| h.lines.len() + 1).sum();
        header_lines + content_lines.max(1)
    }

    fn update_current_file_from_cursor(&mut self) {
        let mut cumulative = 0;
        for (i, file) in self.diff_files.iter().enumerate() {
            let height = self.file_render_height(file);
            if cumulative + height > self.diff_state.cursor_line {
                self.diff_state.current_file_idx = i;
                self.file_list_state.selected = i;
                return;
            }
            cumulative += height;
        }
        if !self.diff_files.is_empty() {
            self.diff_state.current_file_idx = self.diff_files.len() - 1;
            self.file_list_state.selected = self.diff_files.len() - 1;
        }
    }

    pub fn total_lines(&self) -> usize {
        self.diff_files
            .iter()
            .map(|f| self.file_render_height(f))
            .sum()
    }

    /// Calculate the number of display lines a comment takes (header + content + footer)
    fn comment_display_lines(comment: &Comment) -> usize {
        let content_lines = comment.content.split('\n').count();
        2 + content_lines // header + content lines + footer
    }

    /// Returns the source line number and side at the current cursor position, if on a diff line
    pub fn get_line_at_cursor(&self) -> Option<(u32, LineSide)> {
        let target = self.diff_state.cursor_line;
        let mut line_idx = 0;

        for file in &self.diff_files {
            let path = file.display_path();

            // File header
            line_idx += 1;

            // File comments (now multiline with box)
            if let Some(review) = self.session.files.get(path) {
                for comment in &review.file_comments {
                    line_idx += Self::comment_display_lines(comment);
                }
            }

            if file.is_binary || file.hunks.is_empty() {
                // Binary file or no changes line
                line_idx += 1;
            } else {
                // Get line comments for counting
                let line_comments = self
                    .session
                    .files
                    .get(path)
                    .map(|r| &r.line_comments)
                    .cloned()
                    .unwrap_or_default();

                for hunk in &file.hunks {
                    // Hunk header
                    line_idx += 1;

                    // Diff lines
                    for diff_line in &hunk.lines {
                        if line_idx == target {
                            // Found cursor position - return line number and side
                            // Deleted lines use old_lineno with LineSide::Old
                            // Added/context lines use new_lineno with LineSide::New
                            return diff_line
                                .new_lineno
                                .map(|ln| (ln, LineSide::New))
                                .or_else(|| diff_line.old_lineno.map(|ln| (ln, LineSide::Old)));
                        }
                        line_idx += 1;

                        // Count line comments for both sides
                        // Old side (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) {
                                    line_idx += Self::comment_display_lines(comment);
                                }
                            }
                        }
                        // New side (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) {
                                    line_idx += Self::comment_display_lines(comment);
                                }
                            }
                        }
                    }
                }
            }

            // Spacing line
            line_idx += 1;
        }

        None
    }

    /// Find the comment at the current cursor position
    fn find_comment_at_cursor(&self) -> Option<CommentLocation> {
        let target = self.diff_state.cursor_line;
        let mut line_idx = 0;

        for file in &self.diff_files {
            let path = file.display_path().clone();

            // File header
            line_idx += 1;

            // File comments - check if cursor is on one
            if let Some(review) = self.session.files.get(&path) {
                for (idx, comment) in review.file_comments.iter().enumerate() {
                    let comment_lines = Self::comment_display_lines(comment);
                    if target >= line_idx && target < line_idx + comment_lines {
                        return Some(CommentLocation::FileComment { path, index: idx });
                    }
                    line_idx += comment_lines;
                }
            }

            if file.is_binary || file.hunks.is_empty() {
                line_idx += 1;
            } else {
                let line_comments = self
                    .session
                    .files
                    .get(&path)
                    .map(|r| r.line_comments.clone())
                    .unwrap_or_default();

                for hunk in &file.hunks {
                    // Hunk header
                    line_idx += 1;

                    for diff_line in &hunk.lines {
                        // Skip the diff line itself
                        line_idx += 1;

                        // Check comments on old side (deleted lines)
                        if let Some(old_ln) = diff_line.old_lineno
                            && let Some(comments) = line_comments.get(&old_ln)
                        {
                            for (idx, comment) in comments.iter().enumerate() {
                                if comment.side == Some(LineSide::Old) {
                                    let comment_lines = Self::comment_display_lines(comment);
                                    if target >= line_idx && target < line_idx + comment_lines {
                                        return Some(CommentLocation::LineComment {
                                            path,
                                            line: old_ln,
                                            side: LineSide::Old,
                                            index: idx,
                                        });
                                    }
                                    line_idx += comment_lines;
                                }
                            }
                        }

                        // Check comments on new side (added/context lines)
                        if let Some(new_ln) = diff_line.new_lineno
                            && let Some(comments) = line_comments.get(&new_ln)
                        {
                            for (idx, comment) in comments.iter().enumerate() {
                                if comment.side != Some(LineSide::Old) {
                                    let comment_lines = Self::comment_display_lines(comment);
                                    if target >= line_idx && target < line_idx + comment_lines {
                                        return Some(CommentLocation::LineComment {
                                            path,
                                            line: new_ln,
                                            side: LineSide::New,
                                            index: idx,
                                        });
                                    }
                                    line_idx += comment_lines;
                                }
                            }
                        }
                    }
                }
            }

            // Spacing line
            line_idx += 1;
        }

        None
    }

    /// Delete the comment at the current cursor position, if any
    /// Returns true if a comment was deleted
    pub fn delete_comment_at_cursor(&mut self) -> bool {
        let location = self.find_comment_at_cursor();

        match location {
            Some(CommentLocation::FileComment { path, index }) => {
                if let Some(review) = self.session.get_file_mut(&path) {
                    review.file_comments.remove(index);
                    self.dirty = true;
                    self.set_message("Comment deleted");
                    return true;
                }
            }
            Some(CommentLocation::LineComment {
                path,
                line,
                side,
                index,
            }) => {
                if let Some(review) = self.session.get_file_mut(&path)
                    && let Some(comments) = review.line_comments.get_mut(&line)
                {
                    // Find the actual index by counting comments with matching side
                    let mut side_idx = 0;
                    let mut actual_idx = None;
                    for (i, comment) in comments.iter().enumerate() {
                        let comment_side = comment.side.unwrap_or(LineSide::New);
                        if comment_side == side {
                            if side_idx == index {
                                actual_idx = Some(i);
                                break;
                            }
                            side_idx += 1;
                        }
                    }
                    if let Some(idx) = actual_idx {
                        comments.remove(idx);
                        if comments.is_empty() {
                            review.line_comments.remove(&line);
                        }
                        self.dirty = true;
                        self.set_message(format!("Comment on line {} deleted", line));
                        return true;
                    }
                }
            }
            None => {}
        }

        false
    }

    /// Enter edit mode for the comment at the current cursor position
    /// Returns true if a comment was found and edit mode entered
    pub fn enter_edit_mode(&mut self) -> bool {
        let location = self.find_comment_at_cursor();

        match location {
            Some(CommentLocation::FileComment { path, index }) => {
                if let Some(review) = self.session.files.get(&path)
                    && let Some(comment) = review.file_comments.get(index)
                {
                    self.input_mode = InputMode::Comment;
                    self.comment_buffer = comment.content.clone();
                    self.comment_cursor = self.comment_buffer.len();
                    self.comment_type = comment.comment_type;
                    self.comment_is_file_level = true;
                    self.comment_line = None;
                    self.editing_comment_id = Some(comment.id.clone());
                    return true;
                }
            }
            Some(CommentLocation::LineComment {
                path,
                line,
                side,
                index,
            }) => {
                if let Some(review) = self.session.files.get(&path)
                    && let Some(comments) = review.line_comments.get(&line)
                {
                    // Find the actual comment by counting comments with matching side
                    let mut side_idx = 0;
                    for comment in comments.iter() {
                        let comment_side = comment.side.unwrap_or(LineSide::New);
                        if comment_side == side {
                            if side_idx == index {
                                self.input_mode = InputMode::Comment;
                                self.comment_buffer = comment.content.clone();
                                self.comment_cursor = self.comment_buffer.len();
                                self.comment_type = comment.comment_type;
                                self.comment_is_file_level = false;
                                self.comment_line = Some((line, side));
                                self.editing_comment_id = Some(comment.id.clone());
                                return true;
                            }
                            side_idx += 1;
                        }
                    }
                }
            }
            None => {}
        }

        false
    }

    pub fn enter_command_mode(&mut self) {
        self.input_mode = InputMode::Command;
        self.command_buffer.clear();
    }

    pub fn exit_command_mode(&mut self) {
        self.input_mode = InputMode::Normal;
        self.command_buffer.clear();
    }

    pub fn enter_comment_mode(&mut self, file_level: bool, line: Option<(u32, LineSide)>) {
        self.input_mode = InputMode::Comment;
        self.comment_buffer.clear();
        self.comment_cursor = 0;
        self.comment_type = CommentType::Note;
        self.comment_is_file_level = file_level;
        self.comment_line = line;
    }

    pub fn exit_comment_mode(&mut self) {
        self.input_mode = InputMode::Normal;
        self.comment_buffer.clear();
        self.comment_cursor = 0;
        self.editing_comment_id = None;
    }

    pub fn save_comment(&mut self) {
        if self.comment_buffer.trim().is_empty() {
            self.set_message("Comment cannot be empty");
            return;
        }

        let content = self.comment_buffer.trim().to_string();

        if let Some(path) = self.current_file_path().cloned()
            && let Some(review) = self.session.get_file_mut(&path)
        {
            let message: String;

            // Check if we're editing an existing comment
            if let Some(editing_id) = &self.editing_comment_id {
                // Update existing comment
                // Search in file comments
                if let Some(comment) = review
                    .file_comments
                    .iter_mut()
                    .find(|c| &c.id == editing_id)
                {
                    comment.content = content.clone();
                    comment.comment_type = self.comment_type;
                    message = "Comment updated".to_string();
                } else {
                    // If not found in file comments, search in line comments
                    let mut found_comment = None;
                    for comments in review.line_comments.values_mut() {
                        if let Some(comment) = comments.iter_mut().find(|c| &c.id == editing_id) {
                            found_comment = Some(comment);
                            break;
                        }
                    }

                    if let Some(comment) = found_comment {
                        comment.content = content.clone();
                        comment.comment_type = self.comment_type;
                        message = if let Some((line, _)) = self.comment_line {
                            format!("Comment on line {} updated", line)
                        } else {
                            "Comment updated".to_string()
                        };
                    } else {
                        message = "Error: Comment to edit not found".to_string();
                    }
                }
            } else {
                // Create new comment
                if self.comment_is_file_level {
                    let comment = Comment::new(content, self.comment_type, None);
                    review.add_file_comment(comment);
                    message = "File comment added".to_string();
                } else if let Some((line, side)) = self.comment_line {
                    let comment = Comment::new(content, self.comment_type, Some(side));
                    review.add_line_comment(line, comment);
                    message = format!("Comment added to line {}", line);
                } else {
                    // Fallback to file comment if no line specified
                    let comment = Comment::new(content, self.comment_type, None);
                    review.add_file_comment(comment);
                    message = "File comment added".to_string();
                }
            }

            self.dirty = true;
            self.set_message(message);
        }

        self.exit_comment_mode();
    }

    pub fn cycle_comment_type(&mut self) {
        self.comment_type = match self.comment_type {
            CommentType::Note => CommentType::Suggestion,
            CommentType::Suggestion => CommentType::Issue,
            CommentType::Issue => CommentType::Praise,
            CommentType::Praise => CommentType::Note,
        };
    }

    pub fn toggle_help(&mut self) {
        if self.input_mode == InputMode::Help {
            self.input_mode = InputMode::Normal;
        } else {
            self.input_mode = InputMode::Help;
        }
    }

    pub fn enter_confirm_mode(&mut self, action: ConfirmAction) {
        self.input_mode = InputMode::Confirm;
        self.pending_confirm = Some(action);
    }

    pub fn exit_confirm_mode(&mut self) {
        self.input_mode = InputMode::Normal;
        self.pending_confirm = None;
    }

    pub fn toggle_diff_view_mode(&mut self) {
        self.diff_view_mode = match self.diff_view_mode {
            DiffViewMode::Unified => DiffViewMode::SideBySide,
            DiffViewMode::SideBySide => DiffViewMode::Unified,
        };
        let mode_name = match self.diff_view_mode {
            DiffViewMode::Unified => "unified",
            DiffViewMode::SideBySide => "side-by-side",
        };
        self.set_message(format!("Diff view mode: {}", mode_name));
    }

    // Commit selection methods

    pub fn commit_select_up(&mut self) {
        if self.commit_list_cursor > 0 {
            self.commit_list_cursor -= 1;
        }
    }

    pub fn commit_select_down(&mut self) {
        if self.commit_list_cursor < self.commit_list.len().saturating_sub(1) {
            self.commit_list_cursor += 1;
        }
    }

    pub fn toggle_commit_selection(&mut self) {
        if self.commit_list_cursor < self.commit_selected.len() {
            self.commit_selected[self.commit_list_cursor] =
                !self.commit_selected[self.commit_list_cursor];
        }
    }

    pub fn confirm_commit_selection(&mut self) -> Result<()> {
        // Collect selected commit IDs (in order from oldest to newest)
        let selected_ids: Vec<String> = self
            .commit_list
            .iter()
            .enumerate()
            .filter(|(i, _)| self.commit_selected.get(*i).copied().unwrap_or(false))
            .map(|(_, c)| c.id.clone())
            .collect();

        if selected_ids.is_empty() {
            self.set_message("Select at least one commit");
            return Ok(());
        }

        // Get the diff for the selected commits
        let diff_files = get_commit_range_diff(&self.repo_info.repo, &selected_ids)?;

        if diff_files.is_empty() {
            self.set_message("No changes in selected commits");
            return Ok(());
        }

        // Update session with the newest commit as base
        let newest_commit_id = selected_ids.last().unwrap().clone();
        self.session = ReviewSession::new(self.repo_info.root_path.clone(), newest_commit_id);

        // Add files to session
        for file in &diff_files {
            let path = file.display_path().clone();
            self.session.add_file(path, file.status);
        }

        // Update app state
        self.diff_files = diff_files;
        self.diff_source = DiffSource::CommitRange(selected_ids);
        self.input_mode = InputMode::Normal;

        // Reset navigation state
        self.diff_state = DiffState::default();
        self.file_list_state = FileListState::default();

        Ok(())
    }
}