gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! View-related methods (start_*_view, end_*_view, *_move_up/down, export_*, etc.)

use std::path::Path;

use super::{App, InputMode};
use crate::compare::{BranchCompare, CompareTab};
use crate::config::FilterPreset;
use crate::export::{
    export_heatmap_csv, export_heatmap_json, export_ownership_csv, export_ownership_json,
    export_stats_csv, export_stats_json, export_timeline_csv, export_timeline_json,
};
use crate::git::{BlameLine, FileHistoryEntry, FilePatch, StashEntry};
use crate::insights::{ActionRecommendation, HandoffContext, ReviewPack};
use crate::related_files::RelatedFiles;
use crate::stats::{
    ActivityTimeline, ChangeCouplingAnalysis, CodeOwnership, CommitImpactAnalysis,
    CommitQualityAnalysis, FileHeatmap, RepoStats,
};
use crate::topology::{analyze_branch_recommendations, BranchTopology};

impl App {
    // ===== Topology view related =====

    /// Start topology view
    pub fn start_topology_view(&mut self, topology: BranchTopology) {
        // Calculate branch recommendations
        let recommendations = analyze_branch_recommendations(&topology);
        self.branch_recommendations_cache = Some(recommendations);
        self.topology_cache = Some(topology);
        self.topology_nav.reset();
        self.input_mode = InputMode::TopologyView;
    }

    /// End topology view
    pub fn end_topology_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.topology_cache = None;
        self.branch_recommendations_cache = None;
    }

    /// Get recommended action for the selected branch
    pub fn selected_branch_recommendation(&self) -> Option<&crate::topology::BranchRecommendation> {
        let branch_name = self.selected_topology_branch()?;
        self.branch_recommendations_cache.as_ref().and_then(|r| {
            r.recommendations
                .iter()
                .find(|rec| rec.branch_name == branch_name)
        })
    }

    /// Move topology selection up
    pub fn topology_move_up(&mut self) {
        self.topology_nav.move_up();
    }

    /// Move topology selection down
    pub fn topology_move_down(&mut self) {
        if let Some(ref topology) = self.topology_cache {
            self.topology_nav.move_down(topology.branches.len());
        }
    }

    /// Set visible line count for topology view and adjust scroll
    pub fn topology_adjust_scroll(&mut self, visible_lines: usize) {
        self.topology_nav.adjust_scroll(visible_lines);
    }

    /// Get selected topology branch name
    pub fn selected_topology_branch(&self) -> Option<&str> {
        self.topology_cache.as_ref().and_then(|t| {
            t.branches
                .get(self.topology_nav.selected_index)
                .map(|b| b.name.as_str())
        })
    }

    // ===== Suggestion related =====

    /// Generate commit suggestions
    pub fn generate_commit_suggestions(&mut self) {
        use crate::suggestion::generate_suggestions;

        let staged: Vec<crate::git::FileStatus> = self
            .file_statuses
            .iter()
            .filter(|s| s.kind.is_staged())
            .cloned()
            .collect();
        self.commit_suggestions = generate_suggestions(&staged);
        self.suggestion_selected_index = 0;
    }

    /// Apply suggestion
    pub fn apply_suggestion(&mut self, index: usize) {
        if let Some(suggestion) = self.commit_suggestions.get(index) {
            self.commit_type = Some(suggestion.commit_type);
            self.commit_message = suggestion.full_message();
        }
    }

    /// Move suggestion selection up
    pub fn suggestion_move_up(&mut self) {
        if self.suggestion_selected_index > 0 {
            self.suggestion_selected_index -= 1;
        }
    }

    /// Move suggestion selection down
    pub fn suggestion_move_down(&mut self) {
        if !self.commit_suggestions.is_empty()
            && self.suggestion_selected_index < self.commit_suggestions.len() - 1
        {
            self.suggestion_selected_index += 1;
        }
    }

    // ===== Stats view related =====

    /// Start stats view
    pub fn start_stats_view(&mut self, stats: RepoStats) {
        self.stats_view.cache = Some(stats);
        self.stats_view.nav.reset();
        self.input_mode = InputMode::StatsView;
    }

    /// End stats view
    pub fn end_stats_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.stats_view.cache = None;
    }

    /// Export statistics
    pub fn export_stats(&mut self) -> Option<String> {
        if let Some(ref stats) = self.stats_view.cache {
            let csv_path = Path::new("gitstack_stats.csv");
            let json_path = Path::new("gitstack_stats.json");

            let mut results = Vec::new();

            if let Err(e) = export_stats_csv(stats, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_stats_json(stats, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    /// Move selection up in stats view
    pub fn stats_move_up(&mut self) {
        self.stats_view.nav.move_up();
    }

    /// Move selection down in stats view
    pub fn stats_move_down(&mut self) {
        if let Some(ref stats) = self.stats_view.cache {
            self.stats_view.nav.move_down(stats.authors.len());
        }
    }

    /// Adjust stats view scroll
    pub fn stats_adjust_scroll(&mut self, visible_lines: usize) {
        self.stats_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected author name
    pub fn selected_author(&self) -> Option<&str> {
        self.stats_view.cache.as_ref().and_then(|s| {
            s.authors
                .get(self.stats_view.nav.selected_index)
                .map(|a| a.name.as_str())
        })
    }

    /// Apply filter by author
    pub fn filter_by_author(&mut self, author: &str) {
        self.filter_text = format!("/author:{}", author);
        self.reapply_filter();
    }

    // ===== Heatmap view related =====

    /// Start heatmap view
    pub fn start_heatmap_view(&mut self, heatmap: FileHeatmap) {
        self.heatmap_view.cache = Some(heatmap);
        self.heatmap_view.nav.reset();
        self.input_mode = InputMode::HeatmapView;
    }

    /// End heatmap view
    pub fn end_heatmap_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.heatmap_view.cache = None;
    }

    /// Export heatmap
    pub fn export_heatmap(&mut self) -> Option<String> {
        if let Some(ref heatmap) = self.heatmap_view.cache {
            let csv_path = Path::new("gitstack_heatmap.csv");
            let json_path = Path::new("gitstack_heatmap.json");

            let mut results = Vec::new();

            if let Err(e) = export_heatmap_csv(heatmap, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_heatmap_json(heatmap, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    /// Switch heatmap aggregation level to next (+ key)
    pub fn heatmap_increase_aggregation(&mut self) {
        if let Some(heatmap) = self.heatmap_view.cache.take() {
            let new_level = heatmap.aggregation_level.next();
            self.heatmap_view.cache = Some(heatmap.with_aggregation(new_level));
            self.heatmap_view.nav.selected_index = 0;
            self.heatmap_view.nav.scroll_offset = 0;
            self.status_message = Some(format!("Aggregation: {}", new_level.display_name()));
        }
    }

    /// Switch heatmap aggregation level to previous (- key)
    pub fn heatmap_decrease_aggregation(&mut self) {
        if let Some(heatmap) = self.heatmap_view.cache.take() {
            let new_level = heatmap.aggregation_level.prev();
            self.heatmap_view.cache = Some(heatmap.with_aggregation(new_level));
            self.heatmap_view.nav.selected_index = 0;
            self.heatmap_view.nav.scroll_offset = 0;
            self.status_message = Some(format!("Aggregation: {}", new_level.display_name()));
        }
    }

    /// Move selection up in heatmap view
    pub fn heatmap_move_up(&mut self) {
        self.heatmap_view.nav.move_up();
    }

    /// Move selection down in heatmap view
    pub fn heatmap_move_down(&mut self) {
        if let Some(ref heatmap) = self.heatmap_view.cache {
            self.heatmap_view.nav.move_down(heatmap.files.len());
        }
    }

    /// Adjust heatmap view scroll
    pub fn heatmap_adjust_scroll(&mut self, visible_lines: usize) {
        self.heatmap_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected file path
    pub fn selected_heatmap_file(&self) -> Option<&str> {
        self.heatmap_view.cache.as_ref().and_then(|h| {
            h.files
                .get(self.heatmap_view.nav.selected_index)
                .map(|f| f.path.as_str())
        })
    }

    /// Apply filter by file
    pub fn filter_by_file(&mut self, file_path: &str) {
        self.filter_text = format!("/file:{}", file_path);
        self.reapply_filter();
    }

    // ===== File history view related =====

    /// Start file history view
    pub fn start_file_history_view(&mut self, path: String, history: Vec<FileHistoryEntry>) {
        self.file_history_view.path = Some(path);
        self.file_history_view.cache = Some(history);
        self.file_history_view.nav.reset();
        self.input_mode = InputMode::FileHistoryView;
    }

    /// End file history view
    pub fn end_file_history_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.file_history_view.cache = None;
        self.file_history_view.path = None;
    }

    /// Move selection up in file history view
    pub fn file_history_move_up(&mut self) {
        self.file_history_view.nav.move_up();
    }

    /// Move selection down in file history view
    pub fn file_history_move_down(&mut self) {
        if let Some(ref history) = self.file_history_view.cache {
            self.file_history_view.nav.move_down(history.len());
        }
    }

    /// Adjust file history view scroll
    pub fn file_history_adjust_scroll(&mut self, visible_lines: usize) {
        self.file_history_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected file history entry
    pub fn selected_file_history(&self) -> Option<&FileHistoryEntry> {
        self.file_history_view
            .cache
            .as_ref()
            .and_then(|h| h.get(self.file_history_view.nav.selected_index))
    }

    // ===== Timeline view related =====

    /// Start timeline view
    pub fn start_timeline_view(&mut self, timeline: ActivityTimeline) {
        self.timeline_cache = Some(timeline);
        self.input_mode = InputMode::TimelineView;
    }

    /// End timeline view
    pub fn end_timeline_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.timeline_cache = None;
    }

    /// Export timeline
    pub fn export_timeline(&mut self) -> Option<String> {
        if let Some(ref timeline) = self.timeline_cache {
            let csv_path = Path::new("gitstack_timeline.csv");
            let json_path = Path::new("gitstack_timeline.json");

            let mut results = Vec::new();

            if let Err(e) = export_timeline_csv(timeline, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_timeline_json(timeline, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    // ===== Blame view related =====

    /// Start blame view
    pub fn start_blame_view(&mut self, path: String, blame: Vec<BlameLine>) {
        self.blame_view.path = Some(path);
        self.blame_view.cache = Some(blame);
        self.blame_view.nav.reset();
        self.input_mode = InputMode::BlameView;
    }

    /// End blame view
    pub fn end_blame_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.blame_view.cache = None;
        self.blame_view.path = None;
    }

    /// Move selection up in blame view
    pub fn blame_move_up(&mut self) {
        self.blame_view.nav.move_up();
    }

    /// Move selection down in blame view
    pub fn blame_move_down(&mut self) {
        if let Some(ref blame) = self.blame_view.cache {
            self.blame_view.nav.move_down(blame.len());
        }
    }

    /// Adjust blame view scroll
    pub fn blame_adjust_scroll(&mut self, visible_lines: usize) {
        self.blame_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected blame line
    pub fn selected_blame_line(&self) -> Option<&BlameLine> {
        self.blame_view
            .cache
            .as_ref()
            .and_then(|b| b.get(self.blame_view.nav.selected_index))
    }

    // ===== Code ownership view related =====

    /// Start code ownership view
    pub fn start_ownership_view(&mut self, ownership: CodeOwnership) {
        self.ownership_view.cache = Some(ownership);
        self.ownership_view.nav.reset();
        self.input_mode = InputMode::OwnershipView;
    }

    /// End code ownership view
    pub fn end_ownership_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.ownership_view.cache = None;
    }

    /// Export code ownership
    pub fn export_ownership(&mut self) -> Option<String> {
        if let Some(ref ownership) = self.ownership_view.cache {
            let csv_path = Path::new("gitstack_ownership.csv");
            let json_path = Path::new("gitstack_ownership.json");

            let mut results = Vec::new();

            if let Err(e) = export_ownership_csv(ownership, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_ownership_json(ownership, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    /// Move selection up in code ownership view
    pub fn ownership_move_up(&mut self) {
        self.ownership_view.nav.move_up();
    }

    /// Move selection down in code ownership view
    pub fn ownership_move_down(&mut self) {
        if let Some(ref ownership) = self.ownership_view.cache {
            self.ownership_view.nav.move_down(ownership.entries.len());
        }
    }

    /// Adjust code ownership view scroll
    pub fn ownership_adjust_scroll(&mut self, visible_lines: usize) {
        self.ownership_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected ownership entry
    pub fn selected_ownership_entry(&self) -> Option<&crate::stats::CodeOwnershipEntry> {
        self.ownership_view
            .cache
            .as_ref()
            .and_then(|o| o.entries.get(self.ownership_view.nav.selected_index))
    }

    // ===== Stash view related methods =====

    /// Start stash view
    pub fn start_stash_view(&mut self, stashes: Vec<StashEntry>) {
        self.stash_view.cache = Some(stashes);
        self.stash_view.nav.reset();
        self.input_mode = InputMode::StashView;
    }

    /// End stash view
    pub fn end_stash_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.stash_view.cache = None;
    }

    /// Move selection up in stash view
    pub fn stash_move_up(&mut self) {
        self.stash_view.nav.move_up();
    }

    /// Move selection down in stash view
    pub fn stash_move_down(&mut self) {
        if let Some(ref stashes) = self.stash_view.cache {
            self.stash_view.nav.move_down(stashes.len());
        }
    }

    /// Adjust stash view scroll
    pub fn stash_adjust_scroll(&mut self, visible_lines: usize) {
        self.stash_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected stash entry
    pub fn selected_stash_entry(&self) -> Option<&StashEntry> {
        self.stash_view
            .cache
            .as_ref()
            .and_then(|s| s.get(self.stash_view.nav.selected_index))
    }

    /// Update stash list
    pub fn update_stash_cache(&mut self, stashes: Vec<StashEntry>) {
        let prev_len = self.stash_view.cache.as_ref().map(|s| s.len()).unwrap_or(0);
        self.stash_view.cache = Some(stashes);
        // Adjust selection index (e.g., after deletion)
        if let Some(ref stashes) = self.stash_view.cache {
            if !stashes.is_empty() && self.stash_view.nav.selected_index >= stashes.len() {
                self.stash_view.nav.selected_index = stashes.len() - 1;
            }
            // Reset index to 0 if empty
            if stashes.is_empty() {
                self.stash_view.nav.selected_index = 0;
            }
        }
        let _ = prev_len; // suppress unused warning
    }

    // ===== Patch view related methods =====

    /// Start patch view
    pub fn start_patch_view(&mut self, patch: FilePatch) {
        self.patch_view.cache = Some(patch);
        self.patch_view.scroll_offset = 0;
        self.input_mode = InputMode::PatchView;
    }

    /// End patch view
    pub fn end_patch_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.show_detail = true; // Return to detail view
        self.patch_view.cache = None;
    }

    /// Scroll up in patch view
    pub fn patch_scroll_up(&mut self) {
        if self.patch_view.scroll_offset > 0 {
            self.patch_view.scroll_offset -= 1;
        }
    }

    /// Scroll down in patch view
    pub fn patch_scroll_down(&mut self, visible_lines: usize) {
        if let Some(ref patch) = self.patch_view.cache {
            let max_scroll = patch.lines.len().saturating_sub(visible_lines);
            if self.patch_view.scroll_offset < max_scroll {
                self.patch_view.scroll_offset += 1;
            }
        }
    }

    // ===== Filter preset related =====

    /// Apply filter preset (1-5 keys)
    pub fn apply_preset(&mut self, slot: usize) {
        if let Some(preset) = self.filter_presets.get(slot) {
            let query = preset.query.clone();
            let name = preset.name.clone();
            self.filter_text = query;
            self.apply_filter();
            self.set_status_message(format!("Preset {}: {}", slot, name));
        }
    }

    /// Start preset save dialog (Ctrl+S)
    pub fn start_preset_save(&mut self) {
        if self.filter_text.is_empty() {
            self.set_status_message("No filter to save".to_string());
            return;
        }
        // Select empty slot or slot 1
        self.preset_save_slot = self.filter_presets.next_empty_slot().unwrap_or(1);
        self.preset_save_name.clear();
        self.input_mode = InputMode::PresetSave;
    }

    /// End preset save dialog
    pub fn end_preset_save(&mut self) {
        self.input_mode = InputMode::Filter;
        self.preset_save_name.clear();
    }

    /// Preset save: move slot selection up
    pub fn preset_slot_up(&mut self) {
        if self.preset_save_slot > 1 {
            self.preset_save_slot -= 1;
        }
    }

    /// Preset save: move slot selection down
    pub fn preset_slot_down(&mut self) {
        if self.preset_save_slot < 5 {
            self.preset_save_slot += 1;
        }
    }

    /// Preset save: add character to name input
    pub fn preset_name_push(&mut self, c: char) {
        self.preset_save_name.push(c);
    }

    /// Preset save: remove character from name input
    pub fn preset_name_pop(&mut self) {
        self.preset_save_name.pop();
    }

    /// Save preset
    pub fn save_preset(&mut self) -> bool {
        if self.filter_text.is_empty() {
            return false;
        }

        let name = if self.preset_save_name.is_empty() {
            format!("Preset {}", self.preset_save_slot)
        } else {
            self.preset_save_name.clone()
        };

        self.filter_presets.set(
            self.preset_save_slot,
            FilterPreset {
                name: name.clone(),
                query: self.filter_text.clone(),
            },
        );

        if self.filter_presets.save().is_ok() {
            self.set_status_message(format!("Saved to slot {}: {}", self.preset_save_slot, name));
            true
        } else {
            self.set_status_message("Failed to save preset".to_string());
            false
        }
    }

    /// Delete preset
    pub fn delete_preset(&mut self, slot: usize) {
        match slot {
            1 => self.filter_presets.slot1 = None,
            2 => self.filter_presets.slot2 = None,
            3 => self.filter_presets.slot3 = None,
            4 => self.filter_presets.slot4 = None,
            5 => self.filter_presets.slot5 = None,
            _ => return,
        }
        if self.filter_presets.save().is_ok() {
            self.set_status_message(format!("Deleted preset {}", slot));
        }
    }

    // ===== Branch compare view related =====

    /// Start branch compare view
    pub fn start_branch_compare_view(&mut self, compare: BranchCompare) {
        self.branch_compare_view.cache = Some(compare);
        self.branch_compare_view.tab = CompareTab::Ahead;
        self.branch_compare_view.nav.reset();
        self.input_mode = InputMode::BranchCompareView;
    }

    /// End branch compare view
    pub fn end_branch_compare_view(&mut self) {
        self.branch_compare_view.cache = None;
        self.input_mode = InputMode::TopologyView;
    }

    /// Toggle tab
    pub fn branch_compare_toggle_tab(&mut self) {
        self.branch_compare_view.tab = self.branch_compare_view.tab.toggle();
        self.branch_compare_view.nav.reset();
    }

    /// Move selection up
    pub fn branch_compare_move_up(&mut self) {
        self.branch_compare_view.nav.move_up();
    }

    /// Move selection down
    pub fn branch_compare_move_down(&mut self) {
        if let Some(ref compare) = self.branch_compare_view.cache {
            let count = match self.branch_compare_view.tab {
                CompareTab::Ahead => compare.ahead_commits.len(),
                CompareTab::Behind => compare.behind_commits.len(),
            };
            self.branch_compare_view.nav.move_down(count);
        }
    }

    /// Adjust scroll
    pub fn branch_compare_adjust_scroll(&mut self, visible_lines: usize) {
        self.branch_compare_view.nav.adjust_scroll(visible_lines);
    }

    /// Get currently selected commit
    pub fn selected_branch_compare_commit(&self) -> Option<&crate::compare::CompareCommit> {
        let compare = self.branch_compare_view.cache.as_ref()?;
        let commits = match self.branch_compare_view.tab {
            CompareTab::Ahead => &compare.ahead_commits,
            CompareTab::Behind => &compare.behind_commits,
        };
        commits.get(self.branch_compare_view.nav.selected_index)
    }

    // ===== Related commit priority =====

    /// Toggle relevance mode
    pub fn toggle_relevance_mode(&mut self) {
        self.relevance_mode = !self.relevance_mode;
        if self.relevance_mode {
            self.apply_relevance_sort();
        } else {
            // Reapply filter when returning to normal mode
            self.reapply_filter();
        }
    }

    /// Set working files
    pub fn set_working_files(&mut self, files: Vec<String>) {
        self.working_files = files;
        // Re-sort if relevance mode is active
        if self.relevance_mode {
            self.apply_relevance_sort();
        }
    }

    /// Calculate relevance scores and apply sorting
    pub fn apply_relevance_sort(&mut self) {
        if self.working_files.is_empty() {
            self.set_status_message("No working files to compare".to_string());
            self.relevance_mode = false;
            return;
        }

        // Calculate relevance scores
        let events: Vec<&crate::event::GitEvent> = self.all_events.iter().collect();
        let scores = crate::relevance::calculate_relevance(&self.working_files, &events, |hash| {
            self.file_cache.get(hash).cloned()
        });

        // Cache scores
        self.relevance_scores.clear();
        for score in &scores {
            self.relevance_scores
                .insert(score.hash.clone(), score.score);
        }

        // Sort by score (highest first, items without scores at the end)
        self.filtered_indices.sort_by(|&a, &b| {
            let score_a = self
                .all_events
                .get(a)
                .and_then(|e| self.relevance_scores.get(&e.short_hash))
                .copied()
                .unwrap_or(-1.0);
            let score_b = self
                .all_events
                .get(b)
                .and_then(|e| self.relevance_scores.get(&e.short_hash))
                .copied()
                .unwrap_or(-1.0);
            score_b
                .partial_cmp(&score_a)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        self.selected_index = 0;
        let related_count = scores.len();
        self.set_status_message(format!("Relevance mode: {} related commits", related_count));
    }

    /// Get relevance score for the specified hash
    pub fn get_relevance_score(&self, hash: &str) -> Option<f32> {
        self.relevance_scores.get(hash).copied()
    }

    /// Whether relevance mode is active
    pub fn is_relevance_mode(&self) -> bool {
        self.relevance_mode
    }

    // ===== Related files view related =====

    /// Start related files view
    pub fn start_related_files_view(&mut self, related_files: RelatedFiles) {
        self.related_files_view.cache = Some(related_files);
        self.related_files_view.nav.reset();
        self.input_mode = InputMode::RelatedFilesView;
    }

    /// End related files view
    pub fn close_related_files_view(&mut self) {
        self.related_files_view.cache = None;
        self.input_mode = InputMode::Normal;
        self.open_detail(); // Return to detail view
    }

    /// Move down in related files view
    pub fn related_files_move_down(&mut self) {
        if let Some(ref related) = self.related_files_view.cache {
            self.related_files_view.nav.move_down(related.related.len());
        }
    }

    /// Move up in related files view
    pub fn related_files_move_up(&mut self) {
        self.related_files_view.nav.move_up();
    }

    /// Adjust related files view scroll
    pub fn related_files_adjust_scroll(&mut self, visible_lines: usize) {
        self.related_files_view.nav.adjust_scroll(visible_lines);
    }

    // ===== Impact Score view related =====

    /// Start Impact Score view
    pub fn start_impact_score_view(&mut self, analysis: CommitImpactAnalysis) {
        self.impact_score_view.cache = Some(analysis);
        self.impact_score_view.nav.reset();
        self.input_mode = InputMode::ImpactScoreView;
    }

    /// End Impact Score view
    pub fn end_impact_score_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.impact_score_view.cache = None;
    }

    /// Move selection up in Impact Score view
    pub fn impact_score_move_up(&mut self) {
        self.impact_score_view.nav.move_up();
    }

    /// Move selection down in Impact Score view
    pub fn impact_score_move_down(&mut self) {
        if let Some(ref analysis) = self.impact_score_view.cache {
            self.impact_score_view.nav.move_down(analysis.commits.len());
        }
    }

    /// Adjust Impact Score view scroll
    pub fn impact_score_adjust_scroll(&mut self, visible_lines: usize) {
        self.impact_score_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected Impact Score entry
    pub fn selected_impact_score(&self) -> Option<&crate::stats::CommitImpactScore> {
        self.impact_score_view
            .cache
            .as_ref()
            .and_then(|a| a.commits.get(self.impact_score_view.nav.selected_index))
    }

    /// Export Impact Score
    pub fn export_impact_scores(&mut self) -> Option<String> {
        use crate::export::{export_impact_csv, export_impact_json};

        if let Some(ref analysis) = self.impact_score_view.cache {
            let csv_path = Path::new("gitstack_impact.csv");
            let json_path = Path::new("gitstack_impact.json");

            let mut results = Vec::new();

            if let Err(e) = export_impact_csv(analysis, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_impact_json(analysis, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    // ===== Change Coupling view related =====

    /// Start Change Coupling view
    pub fn start_change_coupling_view(&mut self, analysis: ChangeCouplingAnalysis) {
        self.change_coupling_view.cache = Some(analysis);
        self.change_coupling_view.nav.reset();
        self.input_mode = InputMode::ChangeCouplingView;
    }

    /// End Change Coupling view
    pub fn end_change_coupling_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.change_coupling_view.cache = None;
    }

    /// Move selection up in Change Coupling view
    pub fn change_coupling_move_up(&mut self) {
        self.change_coupling_view.nav.move_up();
    }

    /// Move selection down in Change Coupling view
    pub fn change_coupling_move_down(&mut self) {
        if let Some(ref analysis) = self.change_coupling_view.cache {
            self.change_coupling_view
                .nav
                .move_down(analysis.couplings.len());
        }
    }

    /// Adjust Change Coupling view scroll
    pub fn change_coupling_adjust_scroll(&mut self, visible_lines: usize) {
        self.change_coupling_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected Change Coupling entry
    pub fn selected_change_coupling(&self) -> Option<&crate::stats::FileCoupling> {
        self.change_coupling_view.cache.as_ref().and_then(|a| {
            a.couplings
                .get(self.change_coupling_view.nav.selected_index)
        })
    }

    /// Export Change Coupling
    pub fn export_change_coupling(&mut self) -> Option<String> {
        use crate::export::{export_coupling_csv, export_coupling_json};

        if let Some(ref analysis) = self.change_coupling_view.cache {
            let csv_path = Path::new("gitstack_coupling.csv");
            let json_path = Path::new("gitstack_coupling.json");

            let mut results = Vec::new();

            if let Err(e) = export_coupling_csv(analysis, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_coupling_json(analysis, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    // ===== Quality Score view related =====

    /// Start Quality Score view
    pub fn start_quality_score_view(&mut self, analysis: CommitQualityAnalysis) {
        self.quality_score_view.cache = Some(analysis);
        self.quality_score_view.nav.reset();
        self.input_mode = InputMode::QualityScoreView;
    }

    /// End Quality Score view
    pub fn end_quality_score_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.quality_score_view.cache = None;
    }

    /// Move selection up in Quality Score view
    pub fn quality_score_move_up(&mut self) {
        self.quality_score_view.nav.move_up();
    }

    /// Move selection down in Quality Score view
    pub fn quality_score_move_down(&mut self) {
        if let Some(ref analysis) = self.quality_score_view.cache {
            self.quality_score_view
                .nav
                .move_down(analysis.commits.len());
        }
    }

    /// Adjust Quality Score view scroll
    pub fn quality_score_adjust_scroll(&mut self, visible_lines: usize) {
        self.quality_score_view.nav.adjust_scroll(visible_lines);
    }

    /// Get selected Quality Score entry
    pub fn selected_quality_score(&self) -> Option<&crate::stats::CommitQualityScore> {
        self.quality_score_view
            .cache
            .as_ref()
            .and_then(|a| a.commits.get(self.quality_score_view.nav.selected_index))
    }

    /// Export Quality Score
    pub fn export_quality_scores(&mut self) -> Option<String> {
        use crate::export::{export_quality_csv, export_quality_json};

        if let Some(ref analysis) = self.quality_score_view.cache {
            let csv_path = Path::new("gitstack_quality.csv");
            let json_path = Path::new("gitstack_quality.json");

            let mut results = Vec::new();

            if let Err(e) = export_quality_csv(analysis, csv_path) {
                results.push(format!("CSV error: {}", e));
            } else {
                results.push(format!("CSV: {}", csv_path.display()));
            }

            if let Err(e) = export_quality_json(analysis, json_path) {
                results.push(format!("JSON error: {}", e));
            } else {
                results.push(format!("JSON: {}", json_path.display()));
            }

            let message = format!("Exported: {}", results.join(", "));
            self.status_message = Some(message.clone());
            Some(message)
        } else {
            None
        }
    }

    // ===== Commit detail file navigation =====

    /// Move file selection up in commit detail panel
    pub fn commit_detail_file_move_up(&mut self) {
        if self.commit_detail.selected_file > 0 {
            self.commit_detail.selected_file -= 1;
        }
    }

    /// Move file selection down in commit detail panel
    pub fn commit_detail_file_move_down(&mut self) {
        if let Some(ref diff) = self.detail_diff_cache {
            if !diff.files.is_empty() && self.commit_detail.selected_file < diff.files.len() - 1 {
                self.commit_detail.selected_file += 1;
            }
        }
    }

    /// Toggle diff expand/collapse for the selected file in commit detail panel
    pub fn commit_detail_toggle_file_diff(&mut self) {
        let idx = self.commit_detail.selected_file;
        if !self.commit_detail.expanded_files.remove(&idx) {
            self.commit_detail.expanded_files.insert(idx);
        }
    }

    /// Expand diff for all files in commit detail panel
    pub fn commit_detail_expand_all(&mut self) {
        if let Some(ref diff) = self.detail_diff_cache {
            for i in 0..diff.files.len() {
                self.commit_detail.expanded_files.insert(i);
            }
        }
    }

    /// Collapse diff for all files in commit detail panel
    pub fn commit_detail_collapse_all(&mut self) {
        self.commit_detail.expanded_files.clear();
    }

    /// Commit detail: reset file selection, expand state, and scroll
    pub fn reset_commit_detail_file_state(&mut self) {
        self.commit_detail.selected_file = 0;
        self.commit_detail.expanded_files.clear();
        self.commit_detail.scroll = 0;
        self.commit_detail.h_scroll = 0;
    }

    /// Commit detail: auto-adjust scroll to keep selected file visible
    pub fn commit_detail_auto_scroll(&mut self, visible_height: usize) {
        // When first file is selected, reset scroll to 0 to show header
        if self.commit_detail.selected_file == 0 {
            self.commit_detail.scroll = 0;
            return;
        }
        // Header line count (commit info + stats + separator = ~10 lines)
        let header_lines: usize = 10;
        // Calculate line count up to selected file
        let mut line_count = header_lines;
        if let Some(ref diff) = self.detail_diff_cache {
            for i in 0..self.commit_detail.selected_file {
                line_count += 1; // File header line
                if self.commit_detail.expanded_files.contains(&i) {
                    if let Some(patch) = diff.patches.iter().find(|p| p.path == diff.files[i].path)
                    {
                        line_count += patch.lines.len();
                    }
                }
                line_count += 1; // Separator empty line
            }
        }
        // Adjust scroll to keep selected line in visible range
        if line_count < self.commit_detail.scroll {
            self.commit_detail.scroll = line_count;
        } else if line_count >= self.commit_detail.scroll + visible_height {
            self.commit_detail.scroll = line_count.saturating_sub(visible_height / 2);
        }
    }

    // ===== Review queue view =====

    /// Start review queue view
    pub fn start_review_queue_view(&mut self) {
        let queue = crate::review_queue::ReviewQueue::load();
        self.review_queue_view.cache = Some(queue);
        self.review_queue_view.nav.reset();
        self.input_mode = InputMode::ReviewQueueView;
    }

    /// End review queue view
    pub fn end_review_queue_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.review_queue_view.cache = None;
    }

    /// Move review queue selection up
    pub fn review_queue_move_up(&mut self) {
        self.review_queue_view.nav.move_up();
    }

    /// Move review queue selection down
    pub fn review_queue_move_down(&mut self) {
        if let Some(ref queue) = self.review_queue_view.cache {
            self.review_queue_view.nav.move_down(queue.items.len());
        }
    }

    // ===== PR create view =====

    /// Start PR create view
    pub fn start_pr_create(&mut self) {
        self.pr_create_state = crate::pr::PrCreateState {
            gh_available: crate::pr::check_gh_available(),
            base_branch: self.branch_name().to_string(),
            ..Default::default()
        };
        self.input_mode = InputMode::PrCreate;
    }

    /// End PR create view
    pub fn end_pr_create(&mut self) {
        self.input_mode = InputMode::Normal;
    }

    // ===== Review pack view =====

    /// Start review pack view
    pub fn start_review_pack_view(&mut self, pack: ReviewPack, verdict: Option<serde_json::Value>) {
        self.review_pack_view.cache = Some(pack);
        self.review_pack_view.verdict = verdict;
        self.review_pack_view.nav.reset();
        self.input_mode = InputMode::ReviewPackView;
    }

    /// End review pack view
    pub fn end_review_pack_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.review_pack_view.cache = None;
        self.review_pack_view.verdict = None;
    }

    /// Move selection up in review pack view
    pub fn review_pack_move_up(&mut self) {
        self.review_pack_view.nav.move_up();
    }

    /// Move selection down in review pack view
    pub fn review_pack_move_down(&mut self) {
        if let Some(ref pack) = self.review_pack_view.cache {
            let total = pack.top_risks.len()
                + pack.test_gaps.len()
                + pack.recommended_actions.len()
                + pack.owner_candidates.len();
            self.review_pack_view.nav.move_down(total);
        }
    }

    /// Adjust review pack view scroll
    pub fn review_pack_adjust_scroll(&mut self, visible_lines: usize) {
        self.review_pack_view.nav.adjust_scroll(visible_lines);
    }

    // ===== Next actions view =====

    /// Start next actions view
    pub fn start_next_actions_view(&mut self, actions: Vec<ActionRecommendation>) {
        self.next_actions_view.cache = Some(actions);
        self.next_actions_view.nav.reset();
        self.input_mode = InputMode::NextActionsView;
    }

    /// End next actions view
    pub fn end_next_actions_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.next_actions_view.cache = None;
    }

    /// Move selection up in next actions view
    pub fn next_actions_move_up(&mut self) {
        self.next_actions_view.nav.move_up();
    }

    /// Move selection down in next actions view
    pub fn next_actions_move_down(&mut self) {
        if let Some(ref actions) = self.next_actions_view.cache {
            self.next_actions_view.nav.move_down(actions.len());
        }
    }

    /// Adjust next actions view scroll
    pub fn next_actions_adjust_scroll(&mut self, visible_lines: usize) {
        self.next_actions_view.nav.adjust_scroll(visible_lines);
    }

    // ===== Handoff view =====

    /// Start handoff view
    pub fn start_handoff_view(&mut self, context: HandoffContext) {
        self.handoff_view.cache = Some(context);
        self.handoff_view.nav.reset();
        self.input_mode = InputMode::HandoffView;
    }

    /// End handoff view
    pub fn end_handoff_view(&mut self) {
        self.input_mode = InputMode::Normal;
        self.handoff_view.cache = None;
    }

    /// Move selection up in handoff view
    pub fn handoff_move_up(&mut self) {
        self.handoff_view.nav.move_up();
    }

    /// Move selection down in handoff view
    pub fn handoff_move_down(&mut self) {
        if let Some(ref ctx) = self.handoff_view.cache {
            let total = ctx.next_actions.len() + 1; // +1 for prompt section
            self.handoff_view.nav.move_down(total);
        }
    }

    /// Adjust handoff view scroll
    pub fn handoff_adjust_scroll(&mut self, visible_lines: usize) {
        self.handoff_view.nav.adjust_scroll(visible_lines);
    }
}