gitkraft-tui 0.6.1

GitKraft — Git IDE terminal application (Ratatui TUI)
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
use std::path::PathBuf;

use ratatui::widgets::ListState;
use std::sync::mpsc;

use gitkraft_core::*;

// ── Background task results ───────────────────────────────────────────────────

/// Payload produced by a background `refresh` / `open_repo` task.
#[derive(Debug)]
pub struct RepoPayload {
    pub info: RepoInfo,
    pub branches: Vec<BranchInfo>,
    pub commits: Vec<CommitInfo>,
    pub graph_rows: Vec<gitkraft_core::GraphRow>,
    pub unstaged: Vec<DiffInfo>,
    pub staged: Vec<DiffInfo>,
    pub stashes: Vec<StashEntry>,
    pub remotes: Vec<RemoteInfo>,
}

/// Results produced by background tasks and sent back to the main loop.
#[derive(Debug)]
pub enum BackgroundResult {
    /// A repo open / refresh completed.
    RepoLoaded(Result<RepoPayload, String>),
    /// A fetch completed.
    FetchDone(Result<(), String>),
    /// A commit-diff load completed.
    CommitDiffLoaded(Result<Vec<DiffInfo>, String>),
    /// A staging-only refresh completed (unstaged + staged diffs reloaded).
    StagingRefreshed(Result<StagingPayload, String>),
    /// A single-shot operation (stage, unstage, checkout, commit, stash, etc.)
    /// completed and the staging area should be refreshed.
    OperationDone {
        ok_message: Option<String>,
        err_message: Option<String>,
        /// If `true`, trigger a full refresh after applying the result.
        needs_refresh: bool,
        /// If `true`, trigger only a staging refresh.
        needs_staging_refresh: bool,
    },
    /// A commit file list (lightweight, no diff content) was loaded.
    CommitFileListLoaded(Result<Vec<gitkraft_core::DiffFileEntry>, String>),
    /// A single file's diff was loaded.
    SingleFileDiffLoaded(Result<gitkraft_core::DiffInfo, String>),
}

/// Payload returned by an async staging refresh.
#[derive(Debug)]
pub struct StagingPayload {
    pub unstaged: Vec<DiffInfo>,
    pub staged: Vec<DiffInfo>,
}

// ── Enums ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppScreen {
    Welcome,
    DirBrowser,
    Main,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivePane {
    Branches,
    CommitLog,
    DiffView,
    Staging,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    Normal,
    Input,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputPurpose {
    None,
    CommitMessage,
    BranchName,
    RepoPath,
    SearchQuery,
    StashMessage,
}

/// Which sub-list within the staging pane has focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StagingFocus {
    Unstaged,
    Staged,
}

// ── App State ─────────────────────────────────────────────────────────────────

pub struct App {
    pub should_quit: bool,
    pub screen: AppScreen,
    pub active_pane: ActivePane,
    pub input_mode: InputMode,
    pub input_purpose: InputPurpose,
    pub tick_count: u64,

    /// True while a background task is in flight.
    pub is_loading: bool,
    /// Receiver for results from background tasks.
    pub bg_rx: mpsc::Receiver<BackgroundResult>,
    /// Sender cloned into each spawned task.
    bg_tx: mpsc::Sender<BackgroundResult>,

    pub repo_path: Option<PathBuf>,
    pub repo_info: Option<RepoInfo>,

    pub branches: Vec<BranchInfo>,
    pub branch_list_state: ListState,

    pub commits: Vec<CommitInfo>,
    pub graph_rows: Vec<gitkraft_core::GraphRow>,
    pub commit_list_state: ListState,

    pub unstaged_changes: Vec<DiffInfo>,
    pub staged_changes: Vec<DiffInfo>,
    pub unstaged_list_state: ListState,
    pub staged_list_state: ListState,
    pub staging_focus: StagingFocus,
    pub selected_diff: Option<DiffInfo>,
    pub diff_scroll: u16,
    /// All file diffs for the currently viewed commit (for per-file navigation).
    pub commit_diffs: Vec<DiffInfo>,
    /// Index of the currently selected file in `commit_diffs`.
    pub commit_diff_file_index: usize,
    /// Lightweight file list for the selected commit.
    pub commit_files: Vec<gitkraft_core::DiffFileEntry>,
    /// OID of the currently selected commit (for lazy file diff loading).
    pub selected_commit_oid: Option<String>,

    pub stashes: Vec<StashEntry>,
    pub stash_list_state: ListState,
    pub remotes: Vec<RemoteInfo>,

    pub input_buffer: String,
    /// Optional stash message (set via input mode before saving).
    pub stash_message_buffer: String,

    pub status_message: Option<String>,
    pub error_message: Option<String>,

    /// When `true`, the next `d` press actually discards; otherwise the first
    /// `d` sets this flag and shows a confirmation prompt.
    pub confirm_discard: bool,

    /// Whether the theme selection panel is visible.
    pub show_theme_panel: bool,
    /// Whether the options panel is visible.
    pub show_options_panel: bool,
    /// Currently selected theme index (0-26).
    pub current_theme_index: usize,
    /// ListState for the theme list widget.
    pub theme_list_state: ListState,

    /// Recently opened repositories loaded from persistence.
    pub recent_repos: Vec<gitkraft_core::RepoHistoryEntry>,

    /// Current directory being browsed in the directory picker.
    pub browser_dir: PathBuf,
    /// Entries in the current browser directory.
    pub browser_entries: Vec<std::path::PathBuf>,
    /// List state for the directory browser.
    pub browser_list_state: ListState,
    /// Screen to return to when the directory browser is dismissed.
    pub browser_return_screen: AppScreen,
}

impl App {
    // ── Constructor ───────────────────────────────────────────────────────

    #[must_use]
    pub fn new() -> Self {
        let settings = gitkraft_core::features::persistence::load_settings().unwrap_or_default();

        let theme_index = theme_name_to_index(settings.theme_name.as_deref().unwrap_or(""));

        let recent_repos = settings.recent_repos;

        let (bg_tx, bg_rx) = mpsc::channel();

        Self {
            should_quit: false,
            screen: AppScreen::Welcome,
            active_pane: ActivePane::Branches,
            input_mode: InputMode::Normal,
            input_purpose: InputPurpose::None,
            tick_count: 0,

            is_loading: false,
            bg_rx,
            bg_tx,

            repo_path: None,
            repo_info: None,

            branches: Vec::new(),
            branch_list_state: ListState::default(),

            commits: Vec::new(),
            graph_rows: Vec::new(),
            commit_list_state: ListState::default(),

            unstaged_changes: Vec::new(),
            staged_changes: Vec::new(),
            unstaged_list_state: ListState::default(),
            staged_list_state: ListState::default(),
            staging_focus: StagingFocus::Unstaged,
            selected_diff: None,
            diff_scroll: 0,
            commit_diffs: Vec::new(),
            commit_diff_file_index: 0,
            commit_files: Vec::new(),
            selected_commit_oid: None,

            stashes: Vec::new(),
            stash_list_state: ListState::default(),
            remotes: Vec::new(),

            input_buffer: String::new(),
            stash_message_buffer: String::new(),

            status_message: None,
            error_message: None,

            confirm_discard: false,

            show_theme_panel: false,
            show_options_panel: false,
            current_theme_index: theme_index,
            theme_list_state: {
                let mut s = ListState::default();
                s.select(Some(theme_index));
                s
            },

            recent_repos,

            browser_dir: dirs::home_dir().unwrap_or_else(|| PathBuf::from("/")),
            browser_entries: Vec::new(),
            browser_list_state: ListState::default(),
            browser_return_screen: AppScreen::Welcome,
        }
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl App {
    // ── Theme helpers ────────────────────────────────────────────────────

    pub fn cycle_theme_next(&mut self) {
        let count = 27; // number of themes
        self.current_theme_index = (self.current_theme_index + 1) % count;
        self.theme_list_state.select(Some(self.current_theme_index));
        self.status_message = Some(format!("Theme: {}", self.current_theme_name()));
    }

    pub fn cycle_theme_prev(&mut self) {
        let count = 27;
        if self.current_theme_index == 0 {
            self.current_theme_index = count - 1;
        } else {
            self.current_theme_index -= 1;
        }
        self.theme_list_state.select(Some(self.current_theme_index));
        self.status_message = Some(format!("Theme: {}", self.current_theme_name()));
    }

    pub fn current_theme_name(&self) -> &'static str {
        gitkraft_core::THEME_NAMES
            .get(self.current_theme_index)
            .copied()
            .unwrap_or("Default")
    }

    /// Return the `UiTheme` for the currently selected theme index.
    pub fn theme(&self) -> crate::features::theme::palette::UiTheme {
        crate::features::theme::palette::theme_for_index(self.current_theme_index)
    }

    /// Persist the current theme selection to disk.
    pub fn save_theme(&self) {
        let _ = gitkraft_core::features::persistence::save_theme(self.current_theme_name());
    }

    // ── High-level operations ────────────────────────────────────────────

    pub fn open_repo(&mut self, path: PathBuf) {
        self.error_message = None;
        self.status_message = Some("Opening repository…".into());
        self.is_loading = true;
        self.repo_path = Some(path.clone());
        self.screen = AppScreen::Main;

        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let result = load_repo_blocking(&path);
            let _ = tx.send(BackgroundResult::RepoLoaded(result));
        });
    }

    pub fn refresh(&mut self) {
        self.error_message = None;
        self.is_loading = true;
        self.status_message = Some("Refreshing…".into());

        let path = match self.repo_path.clone() {
            Some(p) => p,
            None => {
                self.error_message = Some("No repository open".into());
                self.is_loading = false;
                return;
            }
        };

        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let result = load_repo_blocking(&path);
            let _ = tx.send(BackgroundResult::RepoLoaded(result));
        });
    }

    /// Process any pending results from background tasks.
    /// Call this once per tick in the event loop.
    pub fn poll_background(&mut self) {
        while let Ok(result) = self.bg_rx.try_recv() {
            match result {
                BackgroundResult::RepoLoaded(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(payload) => {
                            let canonical = payload
                                .info
                                .workdir
                                .clone()
                                .unwrap_or_else(|| self.repo_path.clone().unwrap_or_default());
                            self.repo_path = Some(canonical.clone());

                            // Persist
                            let _ = gitkraft_core::features::persistence::record_repo_opened(
                                &canonical,
                            );
                            if let Ok(settings) =
                                gitkraft_core::features::persistence::load_settings()
                            {
                                self.recent_repos = settings.recent_repos;
                            }

                            self.repo_info = Some(payload.info);
                            self.branches = payload.branches;
                            clamp_list_state(&mut self.branch_list_state, self.branches.len());
                            self.graph_rows = payload.graph_rows;
                            self.commits = payload.commits;
                            clamp_list_state(&mut self.commit_list_state, self.commits.len());
                            self.unstaged_changes = payload.unstaged;
                            clamp_list_state(
                                &mut self.unstaged_list_state,
                                self.unstaged_changes.len(),
                            );
                            self.staged_changes = payload.staged;
                            clamp_list_state(
                                &mut self.staged_list_state,
                                self.staged_changes.len(),
                            );
                            self.stashes = payload.stashes;
                            clamp_list_state(&mut self.stash_list_state, self.stashes.len());
                            self.remotes = payload.remotes;
                            self.screen = AppScreen::Main;
                            self.status_message = Some("Repository loaded".into());
                        }
                        Err(e) => {
                            self.error_message = Some(e);
                            self.status_message = None;
                        }
                    }
                }
                BackgroundResult::FetchDone(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(()) => {
                            self.status_message = Some("Fetched from origin".into());
                            self.refresh();
                        }
                        Err(e) => self.error_message = Some(format!("fetch: {e}")),
                    }
                }
                BackgroundResult::CommitDiffLoaded(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(diffs) => {
                            if diffs.is_empty() {
                                self.selected_diff = None;
                                self.commit_diffs.clear();
                                self.commit_diff_file_index = 0;
                                self.status_message = Some("No changes in this commit".into());
                            } else {
                                self.commit_diffs = diffs.clone();
                                self.commit_diff_file_index = 0;
                                self.selected_diff = Some(diffs[0].clone());
                                self.diff_scroll = 0;
                                if diffs.len() > 1 {
                                    self.status_message = Some(format!(
                                        "Showing file 1/{} — use h/l to switch files",
                                        diffs.len()
                                    ));
                                }
                            }
                        }
                        Err(e) => self.error_message = Some(format!("commit diff: {e}")),
                    }
                }
                BackgroundResult::CommitFileListLoaded(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(files) => {
                            let count = files.len();
                            self.commit_files = files;
                            self.commit_diffs.clear();
                            self.commit_diff_file_index = 0;
                            self.selected_diff = None;
                            self.diff_scroll = 0;

                            if count == 0 {
                                self.status_message = Some("No changes in this commit".into());
                            } else {
                                self.status_message = Some(format!("{count} file(s) changed"));
                                // Auto-load the first file's diff
                                let first_path = self.commit_files[0].display_path().to_string();
                                self.load_single_file_diff(first_path);
                            }
                        }
                        Err(e) => self.error_message = Some(format!("file list: {e}")),
                    }
                }
                BackgroundResult::SingleFileDiffLoaded(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(diff) => {
                            // Store in commit_diffs for the file list sidebar.
                            // If this is the first file, also set selected_diff.
                            if self.commit_diffs.len() <= self.commit_diff_file_index {
                                self.commit_diffs.push(diff.clone());
                            } else {
                                self.commit_diffs[self.commit_diff_file_index] = diff.clone();
                            }
                            self.selected_diff = Some(diff);
                            self.diff_scroll = 0;
                            if self.commit_files.len() > 1 {
                                self.status_message = Some(format!(
                                    "File {}/{} — use h/l to switch files",
                                    self.commit_diff_file_index + 1,
                                    self.commit_files.len()
                                ));
                            }
                        }
                        Err(e) => self.error_message = Some(format!("file diff: {e}")),
                    }
                }
                BackgroundResult::StagingRefreshed(res) => {
                    self.is_loading = false;
                    match res {
                        Ok(payload) => self.apply_staging_payload(payload),
                        Err(e) => self.error_message = Some(format!("staging refresh: {e}")),
                    }
                }
                BackgroundResult::OperationDone {
                    ok_message,
                    err_message,
                    needs_refresh,
                    needs_staging_refresh,
                } => {
                    self.is_loading = false;
                    if let Some(msg) = err_message {
                        self.error_message = Some(msg);
                    } else if let Some(msg) = ok_message {
                        self.status_message = Some(msg);
                    }
                    if needs_refresh {
                        self.refresh();
                    } else if needs_staging_refresh {
                        self.refresh_staging();
                    }
                }
            }
        }
    }

    /// Reload only the staging area (unstaged + staged diffs).
    pub fn refresh_staging(&mut self) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => {
                self.error_message = Some("No repository open".into());
                return;
            }
        };
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                let unstaged = gitkraft_core::features::diff::get_working_dir_diff(&repo)
                    .map_err(|e| e.to_string())?;
                let staged = gitkraft_core::features::diff::get_staged_diff(&repo)
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(StagingPayload { unstaged, staged })
            })();
            let _ = tx.send(BackgroundResult::StagingRefreshed(res));
        });
    }

    fn apply_staging_payload(&mut self, payload: StagingPayload) {
        self.unstaged_changes = payload.unstaged;
        if self.unstaged_changes.is_empty() {
            self.unstaged_list_state.select(None);
        } else if self.unstaged_list_state.selected().is_none() {
            self.unstaged_list_state.select(Some(0));
        } else if let Some(i) = self.unstaged_list_state.selected() {
            if i >= self.unstaged_changes.len() {
                self.unstaged_list_state
                    .select(Some(self.unstaged_changes.len() - 1));
            }
        }

        self.staged_changes = payload.staged;
        if self.staged_changes.is_empty() {
            self.staged_list_state.select(None);
        } else if self.staged_list_state.selected().is_none() {
            self.staged_list_state.select(Some(0));
        } else if let Some(i) = self.staged_list_state.selected() {
            if i >= self.staged_changes.len() {
                self.staged_list_state
                    .select(Some(self.staged_changes.len() - 1));
            }
        }
    }

    // ── Staging operations ───────────────────────────────────────────────

    pub fn stage_selected(&mut self) {
        let idx = match self.unstaged_list_state.selected() {
            Some(i) => i,
            None => {
                self.status_message = Some("No unstaged file selected".into());
                return;
            }
        };
        let file_path = self.unstaged_file_path(idx);
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::staging::stage_file(&repo, &file_path)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().map(|_| format!("Staged: {file_path}")),
                err_message: res.err().map(|e| format!("stage: {e}")),
                needs_refresh: false,
                needs_staging_refresh: true,
            });
        });
    }

    pub fn unstage_selected(&mut self) {
        let idx = match self.staged_list_state.selected() {
            Some(i) => i,
            None => {
                self.status_message = Some("No staged file selected".into());
                return;
            }
        };
        let file_path = self.staged_file_path(idx);
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::staging::unstage_file(&repo, &file_path)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().map(|_| format!("Unstaged: {file_path}")),
                err_message: res.err().map(|e| format!("unstage: {e}")),
                needs_refresh: false,
                needs_staging_refresh: true,
            });
        });
    }

    pub fn stage_all(&mut self) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::staging::stage_all(&repo).map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().map(|_| "Staged all files".into()),
                err_message: res.err().map(|e| format!("stage all: {e}")),
                needs_refresh: false,
                needs_staging_refresh: true,
            });
        });
    }

    pub fn unstage_all(&mut self) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::staging::unstage_all(&repo).map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().map(|_| "Unstaged all files".into()),
                err_message: res.err().map(|e| format!("unstage all: {e}")),
                needs_refresh: false,
                needs_staging_refresh: true,
            });
        });
    }

    pub fn discard_selected(&mut self) {
        let idx = match self.unstaged_list_state.selected() {
            Some(i) => i,
            None => {
                self.status_message = Some("No unstaged file selected".into());
                return;
            }
        };
        let file_path = self.unstaged_file_path(idx);
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.confirm_discard = false;
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::staging::discard_file_changes(&repo, &file_path)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res
                    .as_ref()
                    .ok()
                    .map(|_| format!("Discarded changes: {file_path}")),
                err_message: res.err().map(|e| format!("discard: {e}")),
                needs_refresh: false,
                needs_staging_refresh: true,
            });
        });
    }

    // ── Commit ───────────────────────────────────────────────────────────

    pub fn create_commit(&mut self) {
        let msg = self.input_buffer.trim().to_string();
        if msg.is_empty() {
            self.error_message = Some("Commit message cannot be empty".into());
            return;
        }
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.input_buffer.clear();
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                let info = gitkraft_core::features::commits::create_commit(&repo, &msg)
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(format!("Committed: {} {}", info.short_oid, info.summary))
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().cloned(),
                err_message: res.err().map(|e| format!("commit: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    // ── Branches ─────────────────────────────────────────────────────────

    pub fn checkout_selected_branch(&mut self) {
        let idx = match self.branch_list_state.selected() {
            Some(i) => i,
            None => return,
        };
        if idx >= self.branches.len() {
            return;
        }
        let name = self.branches[idx].name.clone();
        if self.branches[idx].is_head {
            self.status_message = Some(format!("Already on '{name}'"));
            return;
        }
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::branches::checkout_branch(&repo, &name)
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(format!("Checked out: {name}"))
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().cloned(),
                err_message: res.err().map(|e| format!("checkout: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    pub fn create_branch(&mut self) {
        let name = self.input_buffer.trim().to_string();
        if name.is_empty() {
            self.error_message = Some("Branch name cannot be empty".into());
            return;
        }
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.input_buffer.clear();
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::branches::create_branch(&repo, &name)
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(format!("Created branch: {name}"))
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().cloned(),
                err_message: res.err().map(|e| format!("create branch: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    pub fn delete_selected_branch(&mut self) {
        let idx = match self.branch_list_state.selected() {
            Some(i) => i,
            None => return,
        };
        if idx >= self.branches.len() {
            return;
        }
        let branch = &self.branches[idx];
        if branch.is_head {
            self.error_message = Some("Cannot delete the current branch".into());
            return;
        }
        let name = branch.name.clone();
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::branches::delete_branch(&repo, &name)
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(format!("Deleted branch: {name}"))
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().cloned(),
                err_message: res.err().map(|e| format!("delete branch: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    // ── Stash ────────────────────────────────────────────────────────────

    pub fn stash_save(&mut self) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        let msg = if self.stash_message_buffer.trim().is_empty() {
            None
        } else {
            Some(self.stash_message_buffer.trim().to_string())
        };
        self.stash_message_buffer.clear();
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let mut repo = open_repo_str(&repo_path)?;
                let entry = gitkraft_core::features::stash::stash_save(&mut repo, msg.as_deref())
                    .map_err(|e| e.to_string())?;
                Ok::<_, String>(format!("Stashed: {}", entry.message))
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res.as_ref().ok().cloned(),
                err_message: res.err().map(|e| format!("stash save: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    pub fn stash_pop_selected(&mut self) {
        let idx = self.stash_list_state.selected().unwrap_or(0);
        if idx >= self.stashes.len() {
            self.error_message = Some("No stash selected".into());
            return;
        }
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let mut repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::stash::stash_pop(&mut repo, idx).map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res
                    .as_ref()
                    .ok()
                    .map(|_| format!("Stash @{{{idx}}} popped")),
                err_message: res.err().map(|e| format!("stash pop: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    pub fn stash_drop_selected(&mut self) {
        let idx = self.stash_list_state.selected().unwrap_or(0);
        if idx >= self.stashes.len() {
            self.error_message = Some("No stash to drop".into());
            return;
        }
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let mut repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::stash::stash_drop(&mut repo, idx)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::OperationDone {
                ok_message: res
                    .as_ref()
                    .ok()
                    .map(|_| format!("Stash @{{{idx}}} dropped")),
                err_message: res.err().map(|e| format!("stash drop: {e}")),
                needs_refresh: true,
                needs_staging_refresh: false,
            });
        });
    }

    // ── Diff ─────────────────────────────────────────────────────────────

    /// Load the file list for the currently selected commit (phase 1 of two-phase loading).
    pub fn load_commit_diff(&mut self) {
        let idx = match self.commit_list_state.selected() {
            Some(i) => i,
            None => return,
        };
        if idx >= self.commits.len() {
            return;
        }
        let oid = self.commits[idx].oid.clone();
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        self.status_message = Some("Loading files…".into());
        self.selected_commit_oid = Some(oid.clone());
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::diff::get_commit_file_list(&repo, &oid)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::CommitFileListLoaded(res));
        });
    }

    /// Load the diff for a single file in the selected commit (phase 2).
    pub fn load_single_file_diff(&mut self, file_path: String) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        let oid = match self.selected_commit_oid.clone() {
            Some(o) => o,
            None => return,
        };
        self.is_loading = true;
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::diff::get_single_file_diff(&repo, &oid, &file_path)
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::SingleFileDiffLoaded(res));
        });
    }

    /// Switch to the next file in the commit diff list.
    pub fn next_diff_file(&mut self) {
        if self.commit_files.is_empty() {
            return;
        }
        self.commit_diff_file_index = (self.commit_diff_file_index + 1) % self.commit_files.len();
        let file_path = self.commit_files[self.commit_diff_file_index]
            .display_path()
            .to_string();
        self.diff_scroll = 0;
        self.status_message = Some(format!(
            "File {}/{}",
            self.commit_diff_file_index + 1,
            self.commit_files.len()
        ));
        self.load_single_file_diff(file_path);
    }

    /// Switch to the previous file in the commit diff list.
    pub fn prev_diff_file(&mut self) {
        if self.commit_files.is_empty() {
            return;
        }
        if self.commit_diff_file_index == 0 {
            self.commit_diff_file_index = self.commit_files.len() - 1;
        } else {
            self.commit_diff_file_index -= 1;
        }
        let file_path = self.commit_files[self.commit_diff_file_index]
            .display_path()
            .to_string();
        self.diff_scroll = 0;
        self.status_message = Some(format!(
            "File {}/{}",
            self.commit_diff_file_index + 1,
            self.commit_files.len()
        ));
        self.load_single_file_diff(file_path);
    }

    /// Close the current repository and return to the welcome screen.
    pub fn close_repo(&mut self) {
        self.repo_path = None;
        self.repo_info = None;
        self.branches.clear();
        self.branch_list_state = ListState::default();
        self.commits.clear();
        self.graph_rows.clear();
        self.commit_list_state = ListState::default();
        self.unstaged_changes.clear();
        self.staged_changes.clear();
        self.unstaged_list_state = ListState::default();
        self.staged_list_state = ListState::default();
        self.staging_focus = StagingFocus::Unstaged;
        self.selected_diff = None;
        self.commit_diffs.clear();
        self.commit_diff_file_index = 0;
        self.commit_files.clear();
        self.selected_commit_oid = None;
        self.diff_scroll = 0;
        self.stashes.clear();
        self.stash_list_state = ListState::default();
        self.remotes.clear();
        self.input_buffer.clear();
        self.stash_message_buffer.clear();
        self.status_message = None;
        self.error_message = None;
        self.confirm_discard = false;
        self.show_theme_panel = false;
        self.show_options_panel = false;
        self.screen = AppScreen::Welcome;
        // Reload recent repos
        if let Ok(settings) = gitkraft_core::features::persistence::load_settings() {
            self.recent_repos = settings.recent_repos;
        }
    }

    /// Populate `browser_entries` with the contents of `browser_dir`.
    pub fn refresh_browser(&mut self) {
        let mut entries = Vec::new();
        if let Ok(read_dir) = std::fs::read_dir(&self.browser_dir) {
            for entry in read_dir.flatten() {
                let path = entry.path();
                // Show only directories to help navigate & identify repos
                if path.is_dir() {
                    entries.push(path);
                }
            }
        }
        entries.sort_by(|a, b| {
            let a_name = a
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_lowercase();
            let b_name = b
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .to_lowercase();
            // Dot-dirs last
            let a_dot = a_name.starts_with('.');
            let b_dot = b_name.starts_with('.');
            a_dot.cmp(&b_dot).then(a_name.cmp(&b_name))
        });
        self.browser_entries = entries;
        self.browser_list_state = ListState::default();
        if !self.browser_entries.is_empty() {
            self.browser_list_state.select(Some(0));
        }
    }

    /// Open the directory browser starting from a given path.
    pub fn open_browser(&mut self, start: PathBuf) {
        self.browser_return_screen = self.screen.clone();
        self.browser_dir = start;
        self.refresh_browser();
        self.screen = AppScreen::DirBrowser;
    }
    /// Load the diff for a selected staging file into the diff pane.
    pub fn load_staging_diff(&mut self) {
        match self.staging_focus {
            StagingFocus::Unstaged => {
                if let Some(idx) = self.unstaged_list_state.selected() {
                    if idx < self.unstaged_changes.len() {
                        self.selected_diff = Some(self.unstaged_changes[idx].clone());
                        self.diff_scroll = 0;
                    }
                }
            }
            StagingFocus::Staged => {
                if let Some(idx) = self.staged_list_state.selected() {
                    if idx < self.staged_changes.len() {
                        self.selected_diff = Some(self.staged_changes[idx].clone());
                        self.diff_scroll = 0;
                    }
                }
            }
        }
    }

    // ── Remote ───────────────────────────────────────────────────────────

    pub fn fetch_remote(&mut self) {
        let repo_path = match self.repo_path.clone() {
            Some(p) => p,
            None => return,
        };
        self.is_loading = true;
        self.status_message = Some("Fetching…".into());
        let tx = self.bg_tx.clone();
        std::thread::spawn(move || {
            let res = (|| {
                let repo = open_repo_str(&repo_path)?;
                gitkraft_core::features::remotes::fetch_remote(&repo, "origin")
                    .map_err(|e| e.to_string())
            })();
            let _ = tx.send(BackgroundResult::FetchDone(res));
        });
    }

    // ── Path helpers ─────────────────────────────────────────────────────

    fn unstaged_file_path(&self, idx: usize) -> String {
        if idx >= self.unstaged_changes.len() {
            return String::new();
        }
        self.unstaged_changes[idx].display_path().to_owned()
    }

    fn staged_file_path(&self, idx: usize) -> String {
        if idx >= self.staged_changes.len() {
            return String::new();
        }
        self.staged_changes[idx].display_path().to_owned()
    }
}

// ── Free-standing helpers ─────────────────────────────────────────────────────

/// Open a repository, mapping the error to a `String` for background-task results.
fn open_repo_str(path: &std::path::Path) -> Result<git2::Repository, String> {
    gitkraft_core::features::repo::open_repo(path).map_err(|e| e.to_string())
}
/// Map a persisted theme name back to its index (0–26).
fn theme_name_to_index(name: &str) -> usize {
    gitkraft_core::theme_index_by_name(name)
}

/// Clamp a `ListState` selection to be within `[0, len)`, or `None` if empty.
fn clamp_list_state(state: &mut ListState, len: usize) {
    if len == 0 {
        state.select(None);
    } else if state.selected().is_none() {
        state.select(Some(0));
    } else if let Some(i) = state.selected() {
        if i >= len {
            state.select(Some(len - 1));
        }
    }
}

/// Blocking helper that loads all repo data in one go.
/// Runs inside `spawn_blocking` — must not touch any async APIs.
fn load_repo_blocking(path: &std::path::Path) -> Result<RepoPayload, String> {
    let mut repo = open_repo_str(path)?;

    let info = gitkraft_core::features::repo::get_repo_info(&repo).map_err(|e| e.to_string())?;
    let branches =
        gitkraft_core::features::branches::list_branches(&repo).map_err(|e| e.to_string())?;
    let commits =
        gitkraft_core::features::commits::list_commits(&repo, 500).map_err(|e| e.to_string())?;
    let graph_rows = gitkraft_core::features::graph::build_graph(&commits);
    let unstaged =
        gitkraft_core::features::diff::get_working_dir_diff(&repo).map_err(|e| e.to_string())?;
    let staged =
        gitkraft_core::features::diff::get_staged_diff(&repo).map_err(|e| e.to_string())?;
    let remotes =
        gitkraft_core::features::remotes::list_remotes(&repo).map_err(|e| e.to_string())?;
    let stashes =
        gitkraft_core::features::stash::list_stashes(&mut repo).map_err(|e| e.to_string())?;

    Ok(RepoPayload {
        info,
        branches,
        commits,
        graph_rows,
        unstaged,
        staged,
        stashes,
        remotes,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_app_defaults() {
        let app = App::new();
        assert!(!app.should_quit);
        assert_eq!(app.screen, AppScreen::Welcome);
        assert_eq!(app.input_mode, InputMode::Normal);
        assert!(app.commits.is_empty());
        assert!(app.branches.is_empty());
        assert!(app.repo_path.is_none());
    }

    #[test]
    fn cycle_theme_next_wraps() {
        let mut app = App::new();
        app.current_theme_index = 0;
        app.cycle_theme_next();
        assert_eq!(app.current_theme_index, 1);
        // Cycle to end
        for _ in 0..26 {
            app.cycle_theme_next();
        }
        assert_eq!(app.current_theme_index, 0); // wrapped
    }

    #[test]
    fn cycle_theme_prev_wraps() {
        let mut app = App::new();
        app.current_theme_index = 0;
        app.cycle_theme_prev();
        assert_eq!(app.current_theme_index, 26); // wrapped to last
    }

    #[test]
    fn theme_returns_struct() {
        let mut app = App::new();
        app.current_theme_index = 0;
        let theme = app.theme();
        // Default theme's active border comes from the core accent (88, 166, 255)
        assert_eq!(
            format!("{:?}", theme.border_active),
            format!("{:?}", ratatui::style::Color::Rgb(88, 166, 255))
        );
    }

    #[test]
    fn theme_name_to_index_known() {
        assert_eq!(theme_name_to_index("Default"), 0);
        assert_eq!(theme_name_to_index("Dracula"), 8);
        assert_eq!(theme_name_to_index("Nord"), 9);
    }

    #[test]
    fn theme_name_to_index_unknown_returns_zero() {
        assert_eq!(theme_name_to_index("NonExistentTheme"), 0);
        assert_eq!(theme_name_to_index(""), 0);
    }
}