git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
use anyhow::Result;
use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
    MouseButton, MouseEventKind,
};
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Margin, Position, Rect},
    style::Modifier,
    text::{Line, Span},
    widgets::{
        Block, Borders, List, ListItem, ListState, Paragraph, Scrollbar, ScrollbarOrientation,
        ScrollbarState, Wrap,
    },
};

use crate::core::diff::DiffHunk;
use crate::tui::theme::TuiTheme;

// ---------------------------------------------------------------------------
// Data model
// ---------------------------------------------------------------------------

/// Where a hunk came from — determines how to apply/reverse on confirm.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum HunkOrigin {
    /// From `git diff --cached` (already staged).
    Staged,
    /// From `git diff` (unstaged working-tree change).
    Unstaged,
    /// From a commit diff (`git diff <oid>^..<oid>`).
    Commit,
}

/// A single hunk with a toggle state and origin.
pub(crate) struct HunkEntry {
    pub hunk: DiffHunk,
    pub selected: bool,
    pub origin: HunkOrigin,
}

/// A file and its parsed hunks, with git status information.
pub(crate) struct FileEntry {
    pub path: String,
    pub hunks: Vec<HunkEntry>,
    /// Index (staged) status character: ' ', 'A', 'M', 'D', 'R', or '?'.
    pub index_status: char,
    /// Worktree (unstaged) status character: ' ', 'M', 'D', 'R', '?', or '!'.
    pub worktree_status: char,
    /// Whether this file is binary (no hunk-level patching possible).
    pub binary: bool,
}

impl FileEntry {
    /// Compute the effective status characters based on current hunk selections.
    ///
    /// Returns `(index_char, worktree_char)` reflecting what `git status` would
    /// show if the current selections were applied.
    pub(crate) fn effective_status(&self) -> (char, char) {
        let will_have_staged = self.hunks.iter().any(|h| h.selected);
        let will_have_unstaged = self.hunks.iter().any(|h| !h.selected);

        let is_untracked = self.index_status == '?' && self.worktree_status == '?';

        if is_untracked {
            return if will_have_staged {
                ('A', ' ')
            } else {
                ('?', '?')
            };
        }

        // Staged new file fully deselected → back to untracked.
        if self.index_status == 'A' && !will_have_staged {
            return ('?', '?');
        }

        let eff_index = if will_have_staged {
            match self.index_status {
                'A' | 'M' | 'D' | 'R' => self.index_status,
                _ => match self.worktree_status {
                    'D' => 'D',
                    _ => 'M',
                },
            }
        } else {
            ' '
        };

        let eff_worktree = if will_have_unstaged {
            match self.worktree_status {
                'M' | 'D' => self.worktree_status,
                _ => match self.index_status {
                    'D' => 'D',
                    _ => 'M',
                },
            }
        } else {
            ' '
        };

        (eff_index, eff_worktree)
    }
}

/// Which pane is focused.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Pane {
    Left,
    Right,
}

/// An entry in the display list for the file tree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DisplayRow {
    /// Directory header grouping files at indices `dir_start..=dir_end`.
    Directory { dir_start: usize, dir_end: usize },
    /// A single file — index into the `files` vec.
    File(usize),
}

/// All state for the interactive hunk selector.
struct HunkSelectorApp {
    files: Vec<FileEntry>,
    display_rows: Vec<DisplayRow>,
    cursor_pos: usize,
    hunk_index: usize,
    active_pane: Pane,
    theme: TuiTheme,
    should_quit: bool,
    confirmed: bool,
    scroll_offset: u16,
    /// Cached layout rects for mouse hit-testing (updated each render).
    left_pane_area: Rect,
    right_pane_area: Rect,
}

// ---------------------------------------------------------------------------
// Tree helpers
// ---------------------------------------------------------------------------

/// Extract the directory portion of a path, or `""` for root-level files.
fn directory_of(path: &str) -> &str {
    match path.rfind('/') {
        Some(pos) => &path[..pos],
        None => "",
    }
}

/// Extract just the filename from a path.
fn filename_of(path: &str) -> &str {
    match path.rfind('/') {
        Some(pos) => &path[pos + 1..],
        None => path,
    }
}

/// Build the display row list from sorted file entries, grouping files in the
/// same directory under a directory header.
fn build_display_rows(files: &[FileEntry]) -> Vec<DisplayRow> {
    let mut rows = Vec::new();
    let mut i = 0;
    while i < files.len() {
        let dir = directory_of(&files[i].path);
        if dir.is_empty() {
            // Root-level file — no directory header.
            rows.push(DisplayRow::File(i));
            i += 1;
        } else {
            // Directory group — find all consecutive files with the same parent dir.
            let dir_start = i;
            while i < files.len() && directory_of(&files[i].path) == dir {
                i += 1;
            }
            let dir_end = i - 1;
            rows.push(DisplayRow::Directory { dir_start, dir_end });
            for j in dir_start..=dir_end {
                rows.push(DisplayRow::File(j));
            }
        }
    }
    rows
}

// ---------------------------------------------------------------------------
// App logic
// ---------------------------------------------------------------------------

impl HunkSelectorApp {
    fn new(files: Vec<FileEntry>, theme: TuiTheme) -> Self {
        let display_rows = build_display_rows(&files);
        Self {
            files,
            display_rows,
            cursor_pos: 0,
            hunk_index: 0,
            active_pane: Pane::Left,
            theme,
            should_quit: false,
            confirmed: false,
            scroll_offset: 0,
            left_pane_area: Rect::default(),
            right_pane_area: Rect::default(),
        }
    }

    /// Return the file index if the cursor is on a file row, or `None` on a
    /// directory header.
    fn current_file_index(&self) -> Option<usize> {
        match self.display_rows.get(self.cursor_pos) {
            Some(DisplayRow::File(i)) => Some(*i),
            _ => None,
        }
    }

    // -- rendering ----------------------------------------------------------

    fn render(&mut self, frame: &mut Frame) {
        let area = frame.area();

        // Reserve one row for the status bar.
        let outer = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(1)])
            .split(area);

        // Two panes: ~30% file list, ~70% diff view.
        let panes = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(30), Constraint::Percentage(70)])
            .split(outer[0]);

        self.left_pane_area = panes[0];
        self.right_pane_area = panes[1];
        self.render_file_list(frame, panes[0]);
        self.render_diff_view(frame, panes[1]);
        self.render_status_bar(frame, outer[1]);
    }

    fn render_file_list(&mut self, frame: &mut Frame, area: Rect) {
        let items: Vec<ListItem> = self
            .display_rows
            .iter()
            .map(|row| match row {
                DisplayRow::Directory { dir_start, .. } => {
                    let dir = directory_of(&self.files[*dir_start].path);
                    let text = format!("\u{25BC} {}", dir);
                    ListItem::new(Line::from(Span::styled(text, self.theme.file_normal)))
                }
                DisplayRow::File(idx) => {
                    let f = &self.files[*idx];
                    let (eff_idx, eff_wt) = f.effective_status();
                    let in_dir = !directory_of(&f.path).is_empty();
                    let name = if in_dir {
                        filename_of(&f.path)
                    } else {
                        &f.path
                    };
                    let indent = if in_dir { "  " } else { "" };

                    let is_untracked = eff_idx == '?' && eff_wt == '?';
                    let mut spans: Vec<Span> = if is_untracked {
                        vec![Span::styled(
                            format!("{}??", indent),
                            self.theme.untracked_status,
                        )]
                    } else {
                        vec![
                            Span::raw(indent.to_string()),
                            Span::styled(eff_idx.to_string(), self.theme.staged_status),
                            Span::styled(eff_wt.to_string(), self.theme.unstaged_status),
                        ]
                    };
                    let name_style = if eff_idx == '?' || eff_wt == '?' {
                        self.theme.file_normal
                    } else if eff_idx != ' ' && eff_wt == ' ' {
                        self.theme.file_fully_staged
                    } else if eff_idx != ' ' && eff_wt != ' ' {
                        self.theme.file_partially_staged
                    } else {
                        self.theme.file_normal
                    };
                    spans.push(Span::styled(format!(" {}", name), name_style));
                    ListItem::new(Line::from(spans))
                }
            })
            .collect();

        let border_style = if self.active_pane == Pane::Left {
            self.theme.border_active
        } else {
            self.theme.border
        };

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

        let list = List::new(items)
            .block(block)
            .highlight_style(self.theme.file_selected)
            .highlight_symbol("> ");

        let mut state = ListState::default();
        state.select(Some(self.cursor_pos));
        frame.render_stateful_widget(list, area, &mut state);

        // Scrollbar — only when the list overflows the visible inner height.
        let inner = area.inner(Margin {
            horizontal: 1,
            vertical: 1,
        });
        let inner_height = inner.height as usize;
        let total = self.display_rows.len();
        if total > inner_height {
            // Ratatui maps thumb to bottom when position = content_length - 1.
            // Setting content_length = max_pos + 1 makes the max scroll position
            // land at content_length - 1, and gives thumb_size = track * inner_height
            // / total_rows (the correct visible fraction).
            let max_pos = total - inner_height;
            let mut sb_state = ScrollbarState::new(max_pos + 1)
                .position(self.cursor_pos.min(max_pos))
                .viewport_content_length(inner_height);
            let sb_area = area.inner(Margin {
                horizontal: 0,
                vertical: 1,
            });
            frame.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(None)
                    .end_symbol(None)
                    .track_symbol(None),
                sb_area,
                &mut sb_state,
            );
        }
    }

    fn render_diff_view(&mut self, frame: &mut Frame, area: Rect) {
        let border_style = if self.active_pane == Pane::Right {
            self.theme.border_active
        } else {
            self.theme.border
        };

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

        if self.files.is_empty() {
            let empty = Paragraph::new("No files").block(block);
            frame.render_widget(empty, area);
            return;
        }

        // Directory header selected — show summary.
        let file_idx = match self.current_file_index() {
            Some(i) => i,
            None => {
                if let Some(DisplayRow::Directory { dir_start, dir_end }) =
                    self.display_rows.get(self.cursor_pos)
                {
                    let count = dir_end - dir_start + 1;
                    let dir = directory_of(&self.files[*dir_start].path);
                    let text = format!("{} file(s) in {}/", count, dir);
                    let p = Paragraph::new(text).block(block);
                    frame.render_widget(p, area);
                } else {
                    let empty = Paragraph::new("No files").block(block);
                    frame.render_widget(empty, area);
                }
                return;
            }
        };

        let file = &self.files[file_idx];
        let total_hunks = file.hunks.len();
        let mut lines: Vec<Line> = Vec::new();

        for (i, entry) in file.hunks.iter().enumerate() {
            let marker = if entry.selected { "\u{2713}" } else { " " };
            let origin_label = match entry.origin {
                HunkOrigin::Staged => " (staged)",
                HunkOrigin::Unstaged => "",
                HunkOrigin::Commit => "",
            };
            let header_text = format!(
                "[{}] Hunk {}/{}{}",
                marker,
                i + 1,
                total_hunks,
                origin_label
            );

            // Highlight the focused hunk header when right pane is active.
            let header_style = if self.active_pane == Pane::Right && i == self.hunk_index {
                self.theme.hunk_header.add_modifier(Modifier::REVERSED)
            } else {
                self.theme.hunk_header
            };
            lines.push(Line::from(Span::styled(header_text, header_style)));

            // Render each line of the hunk text with syntax coloring.
            for raw_line in entry.hunk.text.lines() {
                let style = if raw_line.starts_with('+') {
                    self.theme.added
                } else if raw_line.starts_with('-') {
                    self.theme.removed
                } else if raw_line.starts_with("@@") {
                    self.theme.hunk_header
                } else {
                    self.theme.context
                };
                lines.push(Line::from(Span::styled(raw_line.to_string(), style)));
            }

            // Blank separator between hunks.
            if i + 1 < total_hunks {
                lines.push(Line::from(""));
            }
        }

        // Two empty lines at the bottom for breathing room.
        lines.push(Line::from(""));
        lines.push(Line::from(""));

        let inner = area.inner(Margin {
            horizontal: 1,
            vertical: 1,
        });
        let inner_width = inner.width as usize;
        let inner_height = inner.height as usize;

        // With wrapping enabled, each logical line may span multiple rendered rows.
        // Compute total rendered rows so the scrollbar reflects actual content height.
        let total_rows: usize = lines
            .iter()
            .map(|line| {
                let width: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
                if inner_width == 0 || width == 0 {
                    1
                } else {
                    width.div_ceil(inner_width)
                }
            })
            .sum();

        // Clamp scroll so the last line of content is always at the bottom.
        let max_scroll = total_rows.saturating_sub(inner_height) as u16;
        self.scroll_offset = self.scroll_offset.min(max_scroll);

        let paragraph = Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false })
            .scroll((self.scroll_offset, 0));

        frame.render_widget(paragraph, area);

        if total_rows > inner_height {
            // Ratatui maps thumb to bottom when position = content_length - 1.
            // Setting content_length = max_scroll + 1 makes scroll_offset = max_scroll
            // land at content_length - 1, and gives thumb_size = track * inner_height
            // / total_rows (the correct visible fraction).
            let max_scroll_usize = total_rows - inner_height;
            let mut sb_state = ScrollbarState::new(max_scroll_usize + 1)
                .position(self.scroll_offset as usize)
                .viewport_content_length(inner_height);
            let sb_area = area.inner(Margin {
                horizontal: 0,
                vertical: 1,
            });
            frame.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(None)
                    .end_symbol(None)
                    .track_symbol(None),
                sb_area,
                &mut sb_state,
            );
        }
    }

    fn render_status_bar(&self, frame: &mut Frame, area: Rect) {
        let text = " Navigate: \u{2191}/\u{2193} or j/k | Switch Pane: tab | Toggle: space | Confirm: c or Enter | Quit: q or Esc";
        let bar = Paragraph::new(text).style(self.theme.status_bar);
        frame.render_widget(bar, area);
    }

    // -- keyboard handling --------------------------------------------------

    fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        match code {
            KeyCode::Char('q') | KeyCode::Esc => {
                self.should_quit = true;
                self.confirmed = false;
            }
            KeyCode::Char('c') if !modifiers.contains(KeyModifiers::CONTROL) => {
                self.should_quit = true;
                self.confirmed = true;
            }
            KeyCode::Enter => {
                self.should_quit = true;
                self.confirmed = true;
            }
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                // Ctrl-C: quit without staging.
                self.should_quit = true;
                self.confirmed = false;
            }
            KeyCode::Tab | KeyCode::BackTab => {
                self.active_pane = match self.active_pane {
                    Pane::Left => Pane::Right,
                    Pane::Right => Pane::Left,
                };
            }
            KeyCode::Up | KeyCode::Char('k') => self.navigate_up(),
            KeyCode::Down | KeyCode::Char('j') => self.navigate_down(),
            KeyCode::Char(' ') => self.toggle(),
            _ => {}
        }
    }

    fn handle_mouse(&mut self, kind: MouseEventKind, col: u16, row: u16) {
        let pos = Position { x: col, y: row };

        if self.left_pane_area.contains(pos) {
            match kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    // Inner area: subtract 1-row border top.
                    let inner_top = self.left_pane_area.y + 1;
                    if row < inner_top {
                        return;
                    }
                    let clicked = (row - inner_top) as usize;
                    if clicked < self.display_rows.len() {
                        self.cursor_pos = clicked;
                        self.hunk_index = 0;
                        self.scroll_offset = 0;
                        self.active_pane = Pane::Left;
                    }
                }
                MouseEventKind::ScrollUp => {
                    if self.cursor_pos > 0 {
                        self.cursor_pos -= 1;
                        self.hunk_index = 0;
                        self.scroll_offset = 0;
                    }
                }
                MouseEventKind::ScrollDown => {
                    if self.cursor_pos + 1 < self.display_rows.len() {
                        self.cursor_pos += 1;
                        self.hunk_index = 0;
                        self.scroll_offset = 0;
                    }
                }
                _ => {}
            }
        } else if self.right_pane_area.contains(pos) {
            match kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    self.active_pane = Pane::Right;
                    let file_idx = match self.current_file_index() {
                        Some(i) => i,
                        None => return,
                    };
                    // Inner area: subtract 1-row border top, then account for scroll.
                    let inner_top = self.right_pane_area.y + 1;
                    if row < inner_top {
                        return;
                    }
                    let clicked_line = row - inner_top + self.scroll_offset;
                    // Walk hunks to find which one was clicked.
                    let file = &self.files[file_idx];
                    let total = file.hunks.len();
                    let mut line: u16 = 0;
                    for (i, entry) in file.hunks.iter().enumerate() {
                        let hunk_lines = 1 + entry.hunk.text.lines().count() as u16;
                        let separator = if i + 1 < total { 1 } else { 0 };
                        if clicked_line < line + hunk_lines {
                            // Clicked inside this hunk — toggle if on header row.
                            self.hunk_index = i;
                            if clicked_line == line {
                                let h = &mut self.files[file_idx].hunks[i];
                                h.selected = !h.selected;
                            }
                            return;
                        }
                        line += hunk_lines + separator;
                    }
                }
                MouseEventKind::ScrollUp => {
                    self.scroll_offset = self.scroll_offset.saturating_sub(3);
                }
                MouseEventKind::ScrollDown => {
                    self.scroll_offset += 3;
                }
                _ => {}
            }
        }
    }

    fn navigate_up(&mut self) {
        if self.display_rows.is_empty() {
            return;
        }
        match self.active_pane {
            Pane::Left => {
                if self.cursor_pos > 0 {
                    self.cursor_pos -= 1;
                    self.hunk_index = 0;
                    self.scroll_offset = 0;
                }
            }
            Pane::Right => {
                if self.current_file_index().is_some() && self.hunk_index > 0 {
                    self.hunk_index -= 1;
                    self.adjust_scroll_to_hunk();
                } else if self.current_file_index().is_some() && self.hunk_index == 0 {
                    // Move to the last hunk of the previous file.
                    if let Some(prev) = self.prev_file_row() {
                        self.cursor_pos = prev;
                        let file_idx = match self.display_rows[prev] {
                            DisplayRow::File(i) => i,
                            _ => unreachable!(),
                        };
                        let count = self.files[file_idx].hunks.len();
                        self.hunk_index = count.saturating_sub(1);
                        self.adjust_scroll_to_hunk();
                    }
                }
            }
        }
    }

    fn navigate_down(&mut self) {
        if self.display_rows.is_empty() {
            return;
        }
        match self.active_pane {
            Pane::Left => {
                if self.cursor_pos + 1 < self.display_rows.len() {
                    self.cursor_pos += 1;
                    self.hunk_index = 0;
                    self.scroll_offset = 0;
                }
            }
            Pane::Right => {
                if let Some(file_idx) = self.current_file_index() {
                    let hunk_count = self.files[file_idx].hunks.len();
                    if self.hunk_index + 1 < hunk_count {
                        self.hunk_index += 1;
                        self.adjust_scroll_to_hunk();
                    } else {
                        // Move to the first hunk of the next file.
                        if let Some(next) = self.next_file_row() {
                            self.cursor_pos = next;
                            self.hunk_index = 0;
                            self.scroll_offset = 0;
                        }
                    }
                }
            }
        }
    }

    fn toggle(&mut self) {
        if self.display_rows.is_empty() {
            return;
        }
        match self.active_pane {
            Pane::Left => match self.display_rows[self.cursor_pos] {
                DisplayRow::Directory { dir_start, dir_end } => {
                    // Toggle all hunks in all files under this directory.
                    let any_selected = (dir_start..=dir_end)
                        .any(|i| self.files[i].hunks.iter().any(|h| h.selected));
                    let new_state = !any_selected;
                    for i in dir_start..=dir_end {
                        for h in &mut self.files[i].hunks {
                            h.selected = new_state;
                        }
                    }
                }
                DisplayRow::File(idx) => {
                    // Toggle all hunks in the current file.
                    let any_selected = self.files[idx].hunks.iter().any(|h| h.selected);
                    let new_state = !any_selected;
                    for h in &mut self.files[idx].hunks {
                        h.selected = new_state;
                    }
                }
            },
            Pane::Right => {
                if let Some(file_idx) = self.current_file_index()
                    && let Some(h) = self.files[file_idx].hunks.get_mut(self.hunk_index)
                {
                    h.selected = !h.selected;
                }
            }
        }
    }

    /// Find the previous File row before `cursor_pos`, skipping directory headers.
    fn prev_file_row(&self) -> Option<usize> {
        let mut pos = self.cursor_pos;
        while pos > 0 {
            pos -= 1;
            if matches!(self.display_rows[pos], DisplayRow::File(_)) {
                return Some(pos);
            }
        }
        None
    }

    /// Find the next File row after `cursor_pos`, skipping directory headers.
    fn next_file_row(&self) -> Option<usize> {
        let mut pos = self.cursor_pos;
        while pos + 1 < self.display_rows.len() {
            pos += 1;
            if matches!(self.display_rows[pos], DisplayRow::File(_)) {
                return Some(pos);
            }
        }
        None
    }

    /// Rough scroll adjustment: each hunk header + its lines contribute to the
    /// total row count. We estimate line offsets to keep the focused hunk visible.
    fn adjust_scroll_to_hunk(&mut self) {
        let file_idx = match self.current_file_index() {
            Some(i) => i,
            None => return,
        };
        let file = &self.files[file_idx];
        let mut row: u16 = 0;
        for (i, entry) in file.hunks.iter().enumerate() {
            if i == self.hunk_index {
                break;
            }
            // 1 for the header line, plus content lines, plus 1 separator.
            row += 1 + entry.hunk.text.lines().count() as u16 + 1;
        }
        self.scroll_offset = row;
    }
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Run the interactive hunk selector TUI.
///
/// Returns `Ok(Some(files))` with updated selection state if the user confirms,
/// or `Ok(None)` if cancelled / empty input.
pub fn run_hunk_selector(files: Vec<FileEntry>, theme: TuiTheme) -> Result<Option<Vec<FileEntry>>> {
    if files.is_empty() {
        return Ok(None);
    }

    let mut terminal = ratatui::init();
    crossterm::execute!(std::io::stdout(), EnableMouseCapture)?;

    // Panic-safe cleanup: install a hook that restores the terminal before the
    // default handler fires.
    let prev_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let _ = crossterm::execute!(std::io::stdout(), DisableMouseCapture);
        ratatui::restore();
        prev_hook(info);
    }));

    let result = run_event_loop(&mut terminal, files, theme);

    // Restore terminal state on normal exit.
    crossterm::execute!(std::io::stdout(), DisableMouseCapture)?;
    ratatui::restore();

    // Remove our custom panic hook — back to default.
    let _ = std::panic::take_hook();

    result
}

fn run_event_loop(
    terminal: &mut ratatui::DefaultTerminal,
    files: Vec<FileEntry>,
    theme: TuiTheme,
) -> Result<Option<Vec<FileEntry>>> {
    let mut app = HunkSelectorApp::new(files, theme);

    loop {
        terminal.draw(|frame| app.render(frame))?;

        match event::read()? {
            Event::Key(key) => {
                // On Windows, crossterm fires both Press and Release. Only handle Press.
                if key.kind != KeyEventKind::Press {
                    continue;
                }
                app.handle_key(key.code, key.modifiers);
            }
            Event::Mouse(mouse) => {
                app.handle_mouse(mouse.kind, mouse.column, mouse.row);
            }
            _ => {}
        }

        if app.should_quit {
            return if app.confirmed {
                Ok(Some(app.files))
            } else {
                Ok(None)
            };
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::diff::DiffHunk;
    use crate::core::graph::Theme;
    use crate::tui::theme::TuiTheme;

    fn make_hunk(text: &str) -> DiffHunk {
        DiffHunk {
            text: text.to_string(),
            modified_lines: vec![],
        }
    }

    fn make_theme() -> TuiTheme {
        TuiTheme::from_graph_theme(&Theme::dark())
    }

    /// Root-level files (no directory grouping) — keeps existing tests simple.
    fn make_files() -> Vec<FileEntry> {
        vec![
            FileEntry {
                path: "main.rs".to_string(),
                hunks: vec![
                    HunkEntry {
                        hunk: make_hunk("@@ -1,3 +1,4 @@\n context\n-old\n+new\n"),
                        selected: true,
                        origin: HunkOrigin::Staged,
                    },
                    HunkEntry {
                        hunk: make_hunk("@@ -10,2 +11,3 @@\n context\n+added\n"),
                        selected: false,
                        origin: HunkOrigin::Unstaged,
                    },
                ],
                index_status: 'M',
                worktree_status: 'M',
                binary: false,
            },
            FileEntry {
                path: "lib.rs".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -5,2 +5,2 @@\n-old line\n+new line\n"),
                    selected: false,
                    origin: HunkOrigin::Unstaged,
                }],
                index_status: ' ',
                worktree_status: 'M',
                binary: false,
            },
        ]
    }

    /// Files in a subdirectory — for tree-specific tests.
    fn make_files_in_dir() -> Vec<FileEntry> {
        vec![
            FileEntry {
                path: "src/main.rs".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                    selected: true,
                    origin: HunkOrigin::Staged,
                }],
                index_status: 'M',
                worktree_status: ' ',
                binary: false,
            },
            FileEntry {
                path: "src/lib.rs".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-x\n+y\n"),
                    selected: false,
                    origin: HunkOrigin::Unstaged,
                }],
                index_status: ' ',
                worktree_status: 'M',
                binary: false,
            },
        ]
    }

    /// Mix of root-level files and files in directories.
    fn make_files_mixed() -> Vec<FileEntry> {
        vec![
            FileEntry {
                path: "README.md".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                    selected: false,
                    origin: HunkOrigin::Unstaged,
                }],
                index_status: ' ',
                worktree_status: 'M',
                binary: false,
            },
            FileEntry {
                path: "src/main.rs".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                    selected: true,
                    origin: HunkOrigin::Staged,
                }],
                index_status: 'M',
                worktree_status: ' ',
                binary: false,
            },
            FileEntry {
                path: "src/lib.rs".to_string(),
                hunks: vec![HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-x\n+y\n"),
                    selected: false,
                    origin: HunkOrigin::Unstaged,
                }],
                index_status: ' ',
                worktree_status: 'M',
                binary: false,
            },
        ]
    }

    #[test]
    fn new_initializes_correctly() {
        let files = make_files();
        let app = HunkSelectorApp::new(files, make_theme());
        assert_eq!(app.cursor_pos, 0);
        assert_eq!(app.hunk_index, 0);
        assert_eq!(app.active_pane, Pane::Left);
        assert!(!app.should_quit);
        assert!(!app.confirmed);
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn navigate_files_in_left_pane() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        assert_eq!(app.cursor_pos, 0);

        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);

        // Can't go past the last file.
        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);

        app.navigate_up();
        assert_eq!(app.cursor_pos, 0);

        // Can't go before 0.
        app.navigate_up();
        assert_eq!(app.cursor_pos, 0);
    }

    #[test]
    fn navigate_hunks_in_right_pane() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.active_pane = Pane::Right;

        // File 0 has 2 hunks.
        assert_eq!(app.cursor_pos, 0);
        assert_eq!(app.hunk_index, 0);
        app.navigate_down();
        assert_eq!(app.hunk_index, 1);

        // Past last hunk → move to next file, first hunk.
        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);
        assert_eq!(app.hunk_index, 0);

        // File 1 has 1 hunk — can't go further.
        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);
        assert_eq!(app.hunk_index, 0);

        // Up from first hunk of file 1 → last hunk of file 0.
        app.navigate_up();
        assert_eq!(app.cursor_pos, 0);
        assert_eq!(app.hunk_index, 1);

        app.navigate_up();
        assert_eq!(app.hunk_index, 0);

        // Can't go before first hunk of first file.
        app.navigate_up();
        assert_eq!(app.cursor_pos, 0);
        assert_eq!(app.hunk_index, 0);
    }

    #[test]
    fn navigate_hunks_cross_file_with_dir_headers() {
        let mut app = HunkSelectorApp::new(make_files_in_dir(), make_theme());
        app.active_pane = Pane::Right;
        // display_rows: [Dir(0..1), File(0), File(1)]
        // Start on dir header — right pane nav is no-op.
        assert_eq!(app.cursor_pos, 0);
        assert!(app.current_file_index().is_none());

        // Move cursor to file 0 first.
        app.active_pane = Pane::Left;
        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);
        app.active_pane = Pane::Right;

        // File 0 has 1 hunk. Down → should skip dir headers and land on file 1.
        app.navigate_down();
        assert_eq!(app.cursor_pos, 2);
        assert_eq!(app.current_file_index(), Some(1));
        assert_eq!(app.hunk_index, 0);

        // Up from file 1 → back to file 0's last hunk.
        app.navigate_up();
        assert_eq!(app.cursor_pos, 1);
        assert_eq!(app.current_file_index(), Some(0));
        assert_eq!(app.hunk_index, 0); // file 0 has only 1 hunk
    }

    #[test]
    fn toggle_hunk_in_right_pane() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.active_pane = Pane::Right;

        assert!(app.files[0].hunks[0].selected);
        app.toggle();
        assert!(!app.files[0].hunks[0].selected);
        app.toggle();
        assert!(app.files[0].hunks[0].selected);
    }

    #[test]
    fn toggle_file_in_left_pane() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        // First file: one staged (selected), one unstaged (not selected) → any_selected=true
        assert!(app.files[0].hunks[0].selected);
        assert!(!app.files[0].hunks[1].selected);

        app.toggle(); // Left pane: deselect all (since any are selected).
        assert!(app.files[0].hunks.iter().all(|h| !h.selected));

        app.toggle(); // Now none selected → select all.
        assert!(app.files[0].hunks.iter().all(|h| h.selected));
    }

    #[test]
    fn quit_sets_flags() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.handle_key(KeyCode::Char('q'), KeyModifiers::NONE);
        assert!(app.should_quit);
        assert!(!app.confirmed);
    }

    #[test]
    fn confirm_sets_flags() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.handle_key(KeyCode::Char('c'), KeyModifiers::NONE);
        assert!(app.should_quit);
        assert!(app.confirmed);
    }

    #[test]
    fn enter_confirms() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.handle_key(KeyCode::Enter, KeyModifiers::NONE);
        assert!(app.should_quit);
        assert!(app.confirmed);
    }

    #[test]
    fn tab_switches_pane() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        assert_eq!(app.active_pane, Pane::Left);
        app.handle_key(KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(app.active_pane, Pane::Right);
        app.handle_key(KeyCode::Tab, KeyModifiers::NONE);
        assert_eq!(app.active_pane, Pane::Left);
    }

    #[test]
    fn switching_file_resets_hunk_and_scroll() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.active_pane = Pane::Right;
        app.navigate_down(); // Move to hunk 1
        assert_eq!(app.hunk_index, 1);
        assert!(app.scroll_offset > 0);

        // Switch back to left pane and navigate to next file.
        app.active_pane = Pane::Left;
        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);
        assert_eq!(app.hunk_index, 0);
        assert_eq!(app.scroll_offset, 0);
    }

    #[test]
    fn empty_files_returns_none() {
        let result = run_hunk_selector(vec![], make_theme()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn ctrl_c_quits() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.handle_key(KeyCode::Char('c'), KeyModifiers::CONTROL);
        assert!(app.should_quit);
        assert!(!app.confirmed);
    }

    #[test]
    fn esc_quits() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.handle_key(KeyCode::Esc, KeyModifiers::NONE);
        assert!(app.should_quit);
        assert!(!app.confirmed);
    }

    #[test]
    fn hunk_origin_preserved_through_toggle() {
        let mut app = HunkSelectorApp::new(make_files(), make_theme());
        app.active_pane = Pane::Right;

        // First hunk is Staged
        assert_eq!(app.files[0].hunks[0].origin, HunkOrigin::Staged);
        app.toggle();
        // Origin unchanged after toggle
        assert_eq!(app.files[0].hunks[0].origin, HunkOrigin::Staged);
        assert!(!app.files[0].hunks[0].selected);
    }

    // -- effective_status tests -----------------------------------------------

    #[test]
    fn effective_status_staged_only_deselect_some() {
        // M  → deselect one of two staged hunks → MM
        let file = FileEntry {
            path: "f.rs".into(),
            hunks: vec![
                HunkEntry {
                    hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                    selected: true,
                    origin: HunkOrigin::Staged,
                },
                HunkEntry {
                    hunk: make_hunk("@@ -10,1 +10,1 @@\n-c\n+d\n"),
                    selected: false, // deselected
                    origin: HunkOrigin::Staged,
                },
            ],
            index_status: 'M',
            worktree_status: ' ',
            binary: false,
        };
        assert_eq!(file.effective_status(), ('M', 'M'));
    }

    #[test]
    fn effective_status_staged_only_deselect_all() {
        // M  → deselect all → _M
        let file = FileEntry {
            path: "f.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                selected: false,
                origin: HunkOrigin::Staged,
            }],
            index_status: 'M',
            worktree_status: ' ',
            binary: false,
        };
        assert_eq!(file.effective_status(), (' ', 'M'));
    }

    #[test]
    fn effective_status_unstaged_only_select_all() {
        // _M → select all → M_
        let file = FileEntry {
            path: "f.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("@@ -1,1 +1,1 @@\n-a\n+b\n"),
                selected: true,
                origin: HunkOrigin::Unstaged,
            }],
            index_status: ' ',
            worktree_status: 'M',
            binary: false,
        };
        assert_eq!(file.effective_status(), ('M', ' '));
    }

    #[test]
    fn effective_status_untracked_select() {
        // ?? → select → A_
        let file = FileEntry {
            path: "new.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("@@ -0,0 +1,1 @@\n+new\n"),
                selected: true,
                origin: HunkOrigin::Unstaged,
            }],
            index_status: '?',
            worktree_status: '?',
            binary: false,
        };
        assert_eq!(file.effective_status(), ('A', ' '));
    }

    #[test]
    fn effective_status_untracked_no_select() {
        // ?? stays ??
        let file = FileEntry {
            path: "new.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("@@ -0,0 +1,1 @@\n+new\n"),
                selected: false,
                origin: HunkOrigin::Unstaged,
            }],
            index_status: '?',
            worktree_status: '?',
            binary: false,
        };
        assert_eq!(file.effective_status(), ('?', '?'));
    }

    #[test]
    fn effective_status_new_file_deselect() {
        // A_ → deselect → ??
        let file = FileEntry {
            path: "new.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("@@ -0,0 +1,1 @@\n+new\n"),
                selected: false,
                origin: HunkOrigin::Staged,
            }],
            index_status: 'A',
            worktree_status: ' ',
            binary: false,
        };
        assert_eq!(file.effective_status(), ('?', '?'));
    }

    #[test]
    fn effective_status_deletion_deselect() {
        // D_ → deselect → _D
        let file = FileEntry {
            path: "old.rs".into(),
            hunks: vec![HunkEntry {
                hunk: make_hunk("(file deleted)"),
                selected: false,
                origin: HunkOrigin::Staged,
            }],
            index_status: 'D',
            worktree_status: ' ',
            binary: false,
        };
        assert_eq!(file.effective_status(), (' ', 'D'));
    }

    // -- tree display tests ---------------------------------------------------

    #[test]
    fn display_rows_root_files_no_headers() {
        let files = make_files();
        let rows = build_display_rows(&files);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0], DisplayRow::File(0));
        assert_eq!(rows[1], DisplayRow::File(1));
    }

    #[test]
    fn display_rows_dir_files_have_header() {
        let files = make_files_in_dir();
        let rows = build_display_rows(&files);
        // directory header + 2 files = 3 rows
        assert_eq!(rows.len(), 3);
        assert_eq!(
            rows[0],
            DisplayRow::Directory {
                dir_start: 0,
                dir_end: 1
            }
        );
        assert_eq!(rows[1], DisplayRow::File(0));
        assert_eq!(rows[2], DisplayRow::File(1));
    }

    #[test]
    fn display_rows_mixed_root_and_dir() {
        let files = make_files_mixed();
        let rows = build_display_rows(&files);
        // README.md (root), then ▼ src header, then src/main.rs, src/lib.rs
        assert_eq!(rows.len(), 4);
        assert_eq!(rows[0], DisplayRow::File(0)); // README.md
        assert_eq!(
            rows[1],
            DisplayRow::Directory {
                dir_start: 1,
                dir_end: 2
            }
        );
        assert_eq!(rows[2], DisplayRow::File(1)); // src/main.rs
        assert_eq!(rows[3], DisplayRow::File(2)); // src/lib.rs
    }

    #[test]
    fn navigate_through_dir_header() {
        let mut app = HunkSelectorApp::new(make_files_in_dir(), make_theme());
        // display_rows: [Dir(0..1), File(0), File(1)]
        assert_eq!(app.cursor_pos, 0);
        assert!(app.current_file_index().is_none()); // on dir header

        app.navigate_down();
        assert_eq!(app.cursor_pos, 1);
        assert_eq!(app.current_file_index(), Some(0)); // on first file

        app.navigate_down();
        assert_eq!(app.cursor_pos, 2);
        assert_eq!(app.current_file_index(), Some(1)); // on second file

        // Can't go past last row.
        app.navigate_down();
        assert_eq!(app.cursor_pos, 2);
    }

    #[test]
    fn toggle_directory_toggles_all_files() {
        let mut app = HunkSelectorApp::new(make_files_in_dir(), make_theme());
        // cursor_pos 0 = dir header
        // File 0: one hunk selected. File 1: one hunk not selected.
        assert!(app.files[0].hunks[0].selected);
        assert!(!app.files[1].hunks[0].selected);

        // Toggle dir: any_selected=true → deselect all.
        app.toggle();
        assert!(!app.files[0].hunks[0].selected);
        assert!(!app.files[1].hunks[0].selected);

        // Toggle again: none selected → select all.
        app.toggle();
        assert!(app.files[0].hunks[0].selected);
        assert!(app.files[1].hunks[0].selected);
    }

    #[test]
    fn right_pane_noop_on_dir_header() {
        let mut app = HunkSelectorApp::new(make_files_in_dir(), make_theme());
        app.active_pane = Pane::Right;

        // On directory header — hunk navigation should be no-op.
        assert_eq!(app.hunk_index, 0);
        app.navigate_down();
        assert_eq!(app.hunk_index, 0);

        // Toggle on dir in right pane should be no-op.
        app.toggle();
        assert!(app.files[0].hunks[0].selected); // unchanged
    }

    #[test]
    fn directory_of_extracts_parent() {
        assert_eq!(directory_of("src/main.rs"), "src");
        assert_eq!(directory_of("a/b/c.rs"), "a/b");
        assert_eq!(directory_of("file.rs"), "");
    }

    #[test]
    fn filename_of_extracts_name() {
        assert_eq!(filename_of("src/main.rs"), "main.rs");
        assert_eq!(filename_of("a/b/c.rs"), "c.rs");
        assert_eq!(filename_of("file.rs"), "file.rs");
    }
}