gitu 0.41.0

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

use crate::item_data::Ref;
use crate::item_data::Rev;

/// Data that can be selected in a picker
#[derive(Debug, Clone, PartialEq)]
pub enum PickerData {
    /// A selected item value
    Item(String),
    /// Custom user input (literal text from input field)
    CustomInput(String),
}

impl PickerData {
    pub fn display(&self) -> &str {
        match self {
            PickerData::Item(s) | PickerData::CustomInput(s) => s,
        }
    }
}

/// An item in the picker list
#[derive(Debug, Clone, PartialEq)]
pub struct PickerItem {
    /// The text to display and match against
    pub display: Cow<'static, str>,
    /// Associated data
    pub data: PickerData,
}

impl PickerItem {
    pub fn new(display: impl Into<Cow<'static, str>>, data: PickerData) -> Self {
        Self {
            display: display.into(),
            data,
        }
    }
}

/// Result of a fuzzy match with score
#[derive(Debug, Clone)]
struct MatchResult {
    index: usize,
    score: i64,
}

/// Picker status
#[derive(Debug, Clone, PartialEq)]
pub enum PickerStatus {
    /// Picker is active
    Active,
    /// User selected an item
    Done,
    /// User cancelled
    Cancelled,
}

/// State of the picker component
pub struct PickerState {
    /// All available items (excluding custom input)
    items: Vec<PickerItem>,
    /// Filtered and sorted indices based on current pattern
    filtered_indices: Vec<usize>,
    /// Current cursor position in filtered results
    cursor: usize,
    /// Current input pattern
    pub input_state: TextState<'static>,
    /// Fuzzy matcher
    matcher: SkimMatcherV2,
    /// Prompt text to display
    pub prompt_text: Cow<'static, str>,
    /// Current status
    status: PickerStatus,
    /// Allow user to input custom value not in the list
    allow_custom_input: bool,
    /// Custom input item (separate from items list)
    custom_input_item: Option<PickerItem>,
}

pub(crate) struct PickerParams<'a> {
    pub(crate) prompt: Cow<'static, str>,
    pub(crate) refs: &'a [Ref],
    pub(crate) exclude_ref: Option<Ref>,
    pub(crate) default: Option<Rev>,
    pub(crate) allow_custom_input: bool,
}

impl PickerState {
    /// Create a new picker with items
    pub fn new(
        prompt: impl Into<Cow<'static, str>>,
        items: Vec<PickerItem>,
        allow_custom_input: bool,
    ) -> Self {
        let mut state = Self {
            items: items.clone(),
            filtered_indices: Vec::new(),
            cursor: 0,
            input_state: TextState::default(),
            matcher: SkimMatcherV2::default(),
            prompt_text: prompt.into(),
            status: PickerStatus::Active,
            allow_custom_input,
            custom_input_item: None,
        };
        state.update_filter();
        state
    }

    /// Create a picker showing only local branches by shorthand name.
    /// The default branch (if any) is listed first. The exclude_ref is omitted.
    pub(crate) fn with_branches(params: PickerParams) -> Self {
        let default_name = params.default.as_ref().map(|r| r.shorthand().to_string());
        let exclude_name = params
            .exclude_ref
            .as_ref()
            .map(|r| r.shorthand().to_string());

        let items = default_name
            .iter()
            .map(|name| PickerItem::new(name.clone(), PickerData::Item(name.clone())))
            .chain(
                params
                    .refs
                    .iter()
                    .filter(|r| matches!(r, Ref::Head(_)))
                    .filter(|r| exclude_name.as_deref().is_none_or(|e| e != r.shorthand()))
                    .filter(|r| default_name.as_deref().is_none_or(|d| d != r.shorthand()))
                    .map(|r| {
                        let name = r.shorthand().to_string();
                        PickerItem::new(name.clone(), PickerData::Item(name))
                    }),
            )
            .collect();

        Self::new(params.prompt, items, params.allow_custom_input)
    }

    /// Create a picker from refs. Tags are prefixed with "tag: " in display.
    /// The default ref (if any) is listed first. The exclude_ref is omitted.
    pub(crate) fn with_refs(params: PickerParams) -> Self {
        let ref_to_item = |r: &Ref| {
            let (display, refname) = match r {
                Ref::Tag(name) => (format!("tag: {}", name), r.to_full_refname()),
                _ => (r.shorthand().to_string(), r.shorthand().to_string()),
            };
            PickerItem::new(display, PickerData::Item(refname))
        };

        let default_item = params.default.as_ref().map(|default| match default {
            Rev::Ref(r) => ref_to_item(r),
            Rev::Commit(c) => PickerItem::new(c.clone(), PickerData::Item(c.clone())),
        });

        let items = default_item
            .into_iter()
            .chain(
                params
                    .refs
                    .iter()
                    .filter(|r| {
                        params.exclude_ref.as_ref().is_none_or(|e| e != *r)
                            && params.default.as_ref().is_none_or(|d| match d {
                                Rev::Ref(d) => d != *r,
                                _ => true,
                            })
                    })
                    .map(ref_to_item),
            )
            .collect();

        Self::new(params.prompt, items, params.allow_custom_input)
    }

    /// Get current input pattern
    pub fn pattern(&self) -> &str {
        self.input_state.value()
    }

    /// Update the filter based on current input pattern
    pub fn update_filter(&mut self) {
        let pattern = self.pattern().to_string();

        if pattern.is_empty() {
            // Show all items when no pattern
            self.filtered_indices = (0..self.items.len()).collect();
            self.custom_input_item = None;
        } else {
            // Fuzzy match and sort by score
            let mut matches: Vec<MatchResult> = self
                .items
                .iter()
                .enumerate()
                .filter_map(|(i, item)| {
                    self.matcher
                        .fuzzy_match(&item.display, &pattern)
                        .map(|score| MatchResult { index: i, score })
                })
                .collect();

            // Sort by score (higher is better)
            matches.sort_by(|a, b| b.score.cmp(&a.score));

            self.filtered_indices = matches.into_iter().map(|m| m.index).collect();

            // Create custom input item if enabled
            if self.allow_custom_input {
                self.custom_input_item = Some(PickerItem::new(
                    pattern.clone(),
                    PickerData::CustomInput(pattern),
                ));
            } else {
                self.custom_input_item = None;
            }
        }

        // Reset cursor if out of bounds
        let total_count = self.filtered_indices.len()
            + if self.custom_input_item.is_some() {
                1
            } else {
                0
            };
        if self.cursor >= total_count {
            self.cursor = 0;
        }
    }

    /// Get the currently selected item, if any
    pub fn selected(&self) -> Option<&PickerItem> {
        // Check if cursor is on custom input item (always at the end)
        if self.cursor == self.filtered_indices.len() {
            return self.custom_input_item.as_ref();
        }

        self.filtered_indices
            .get(self.cursor)
            .and_then(|&i| self.items.get(i))
    }

    /// Get all filtered items with their original indices
    /// Custom input item (if present) is always last with index usize::MAX
    pub fn filtered_items(&self) -> impl Iterator<Item = (usize, &PickerItem)> {
        self.filtered_indices
            .iter()
            .filter_map(|&i| self.items.get(i).map(|item| (i, item)))
            .chain(
                self.custom_input_item
                    .as_ref()
                    .map(|item| (usize::MAX, item)),
            )
    }

    /// Move cursor to next item
    pub fn next(&mut self) {
        let total_count = self.filtered_indices.len()
            + if self.custom_input_item.is_some() {
                1
            } else {
                0
            };
        if total_count > 0 {
            self.cursor = (self.cursor + 1) % total_count;
        }
    }

    /// Move cursor to previous item
    pub fn previous(&mut self) {
        let total_count = self.filtered_indices.len()
            + if self.custom_input_item.is_some() {
                1
            } else {
                0
            };
        if total_count > 0 {
            self.cursor = if self.cursor == 0 {
                total_count - 1
            } else {
                self.cursor - 1
            };
        }
    }

    /// Get current cursor position
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Get total number of items
    pub fn total_items(&self) -> usize {
        self.items.len()
    }

    /// Get number of filtered items
    pub fn filtered_count(&self) -> usize {
        self.filtered_indices.len()
    }

    /// Get the fuzzy match positions for a given item (for highlighting)
    pub fn match_indices(&self, item_index: usize) -> Option<Vec<usize>> {
        let pattern = self.pattern();
        if pattern.is_empty() {
            return None;
        }

        // Don't highlight custom input items (marked with usize::MAX)
        if item_index == usize::MAX {
            return None;
        }

        self.items
            .get(item_index)
            .and_then(|item| self.matcher.fuzzy_indices(&item.display, pattern))
            .map(|(_, indices)| indices)
    }

    /// Get current status
    pub fn status(&self) -> &PickerStatus {
        &self.status
    }

    /// Mark picker as done (user selected an item)
    pub fn done(&mut self) {
        self.status = PickerStatus::Done;
    }

    /// Mark picker as cancelled (user cancelled)
    pub fn cancel(&mut self) {
        self.status = PickerStatus::Cancelled;
    }

    /// Check if picker is done
    pub fn is_done(&self) -> bool {
        self.status == PickerStatus::Done
    }

    /// Check if picker is cancelled
    pub fn is_cancelled(&self) -> bool {
        self.status == PickerStatus::Cancelled
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn create_test_items() -> Vec<PickerItem> {
        vec![
            PickerItem::new("main", PickerData::Item("main".to_string())),
            PickerItem::new("develop", PickerData::Item("develop".to_string())),
            PickerItem::new("feature/test", PickerData::Item("feature/test".to_string())),
            PickerItem::new("feature/new", PickerData::Item("feature/new".to_string())),
            PickerItem::new("bugfix/123", PickerData::Item("bugfix/123".to_string())),
        ]
    }

    #[test]
    fn test_picker_data_display() {
        let revision = PickerData::Item("main".to_string());
        assert_eq!(revision.display(), "main");

        let custom = PickerData::CustomInput("custom".to_string());
        assert_eq!(custom.display(), "custom");
    }

    #[test]
    fn test_picker_item_new() {
        let item = PickerItem::new("main", PickerData::Item("main".to_string()));
        assert_eq!(item.display.as_ref(), "main");
        assert_eq!(item.data.display(), "main");
    }

    #[test]
    fn test_picker_state_new_without_custom_input() {
        let items = create_test_items();
        let state = PickerState::new("Select branch", items.clone(), false);

        assert_eq!(state.prompt_text.as_ref(), "Select branch");
        assert_eq!(state.total_items(), 5);
        assert_eq!(state.filtered_count(), 5);
        assert_eq!(state.cursor(), 0);
        assert_eq!(state.pattern(), "");
        assert_eq!(state.status(), &PickerStatus::Active);
        assert!(!state.allow_custom_input);
    }

    #[test]
    fn test_picker_state_new_with_custom_input() {
        let items = create_test_items();
        let state = PickerState::new("Select branch", items, true);

        assert!(state.allow_custom_input);
        assert_eq!(state.custom_input_item, None); // No custom item when pattern is empty
    }

    #[test]
    fn test_empty_pattern_shows_all_items() {
        let items = create_test_items();
        let state = PickerState::new("Select", items, false);

        assert_eq!(state.filtered_count(), 5);
        assert_eq!(state.filtered_indices, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_fuzzy_filtering() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state.update_filter();

        // Should match "feature/test", "feature/new", and "bugfix/123" (fuzzy match)
        assert_eq!(state.filtered_count(), 3);

        let filtered: Vec<_> = state.filtered_items().collect();
        assert!(
            filtered
                .iter()
                .any(|(_, item)| item.display == "feature/test")
        );
        assert!(
            filtered
                .iter()
                .any(|(_, item)| item.display == "feature/new")
        );
        assert!(
            filtered
                .iter()
                .any(|(_, item)| item.display == "bugfix/123")
        );
    }

    #[test]
    fn test_fuzzy_filtering_sorts_by_score() {
        // Create items with varying match quality for pattern "feat"
        let items = vec![
            PickerItem::new("feat", PickerData::Item("feat".to_string())), // Exact match
            PickerItem::new("feature", PickerData::Item("feature".to_string())), // Prefix match
            PickerItem::new("feature/test", PickerData::Item("feature/test".to_string())), // Prefix with more chars
            PickerItem::new("fix-eat-bug", PickerData::Item("fix-eat-bug".to_string())), // Scattered match
        ];
        let mut state = PickerState::new("Select", items, false);

        // Type "feat" pattern
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::empty()));
        state.update_filter();

        // All should match
        assert_eq!(state.filtered_count(), 4);

        // Verify sorted by score: exact match > prefix match > scattered match
        let filtered: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // "feat" (exact) should be first, "fix-eat-bug" (scattered) should be last
        assert_eq!(filtered[0], "feat");
        assert_eq!(filtered[filtered.len() - 1], "fix-eat-bug");
    }

    #[test]
    fn test_case_insensitive_matching() {
        let items = vec![
            PickerItem::new("Feature", PickerData::Item("Feature".to_string())),
            PickerItem::new("feature", PickerData::Item("feature".to_string())),
            PickerItem::new("FEATURE", PickerData::Item("FEATURE".to_string())),
        ];

        let mut state = PickerState::new("Select item", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        // fuzzy-matcher is case-insensitive by default
        assert_eq!(state.filtered_count(), 3);
    }

    #[test]
    fn test_no_matches() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::empty()));
        state.update_filter();

        assert_eq!(state.filtered_count(), 0);
        assert!(state.selected().is_none());
    }

    #[test]
    fn test_custom_input_creation() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        // Use pattern "fea" which matches feature/test and feature/new
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        // Custom input item should be created
        assert!(state.custom_input_item.is_some());

        // Should have multiple regular matches + custom input
        let filtered: Vec<_> = state.filtered_items().collect();
        assert!(filtered.len() >= 3); // At least 2 feature items + bugfix + custom input

        // Custom input should be last in filtered items
        let last = filtered.last().unwrap();
        assert_eq!(last.0, usize::MAX);
        assert_eq!(last.1.display.as_ref(), "fea");
    }

    #[test]
    fn test_custom_input_not_created_when_disabled() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state.update_filter();

        assert!(state.custom_input_item.is_none());
    }

    #[test]
    fn test_custom_input_not_created_on_empty_pattern() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        // Start with no input
        assert!(state.custom_input_item.is_none());

        // Add then remove input
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();
        assert!(state.custom_input_item.is_some());

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::empty()));
        state.update_filter();
        assert!(state.custom_input_item.is_none());
    }

    #[test]
    fn test_cursor_next() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        assert_eq!(state.cursor(), 0);

        state.next();
        assert_eq!(state.cursor(), 1);

        state.next();
        assert_eq!(state.cursor(), 2);
    }

    #[test]
    fn test_cursor_next_wraps_around() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        // Move to end
        for _ in 0..5 {
            state.next();
        }

        // Should wrap to 0
        assert_eq!(state.cursor(), 0);
    }

    #[test]
    fn test_cursor_previous() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state.next();
        state.next();
        assert_eq!(state.cursor(), 2);

        state.previous();
        assert_eq!(state.cursor(), 1);

        state.previous();
        assert_eq!(state.cursor(), 0);
    }

    #[test]
    fn test_cursor_previous_wraps_around() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        assert_eq!(state.cursor(), 0);

        state.previous();
        // Should wrap to last item
        assert_eq!(state.cursor(), 4);
    }

    #[test]
    fn test_cursor_with_custom_input() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state.update_filter();

        // 3 matched items (feature/test, feature/new, bugfix/123) + 1 custom input = 4 total
        assert_eq!(state.cursor(), 0);

        state.next();
        assert_eq!(state.cursor(), 1);

        state.next();
        assert_eq!(state.cursor(), 2);

        state.next();
        assert_eq!(state.cursor(), 3); // Custom input position

        state.next();
        assert_eq!(state.cursor(), 0); // Wrapped around forward

        state.previous();
        assert_eq!(state.cursor(), 3); // Wrapped around backward to custom input
    }

    #[test]
    fn test_navigation_with_custom_input_at_end() {
        let items = vec![
            PickerItem::new("feature/a", PickerData::Item("feature/a".to_string())),
            PickerItem::new("feature/b", PickerData::Item("feature/b".to_string())),
        ];

        let mut state = PickerState::new("Select", items, true);

        // Type "feat" to get matches + custom input
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::empty()));
        state.update_filter();

        // Should have 2 matches + custom input = 3 total
        assert_eq!(state.filtered_count(), 2);
        assert_eq!(state.cursor(), 0);

        // Navigate to first match
        let selected = state.selected().unwrap();
        match &selected.data {
            PickerData::Item(_) => {}
            _ => panic!("Expected first item to be a revision"),
        }

        // Navigate to second match
        state.next();
        assert_eq!(state.cursor(), 1);

        // Navigate to custom input (last item)
        state.next();
        assert_eq!(state.cursor(), 2);
        let selected = state.selected().unwrap();
        match &selected.data {
            PickerData::CustomInput(s) => assert_eq!(s, "feat"),
            _ => panic!("Expected custom input at end"),
        }

        // Wrap around to first
        state.next();
        assert_eq!(state.cursor(), 0);
    }

    #[test]
    fn test_cursor_resets_when_filter_reduces_items() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        // Move cursor to position 4
        for _ in 0..4 {
            state.next();
        }
        assert_eq!(state.cursor(), 4);

        // Filter to only 2 items
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state.update_filter();

        // Cursor should reset to 0
        assert_eq!(state.cursor(), 0);
    }

    #[test]
    fn test_scroll_through_many_items() {
        // Create 20 items to test scrolling behavior
        let items: Vec<_> = (0..20)
            .map(|i| {
                PickerItem::new(
                    format!("branch-{:02}", i),
                    PickerData::Item(format!("branch-{:02}", i)),
                )
            })
            .collect();

        let mut state = PickerState::new("Select", items, false);

        // Start at first item
        assert_eq!(state.cursor(), 0);

        // Navigate to middle item
        for _ in 0..10 {
            state.next();
        }
        assert_eq!(state.cursor(), 10);

        // Navigate to last item
        for _ in 0..9 {
            state.next();
        }
        assert_eq!(state.cursor(), 19);

        // Wrap around to first
        state.next();
        assert_eq!(state.cursor(), 0);

        // Navigate backwards
        state.previous();
        assert_eq!(state.cursor(), 19);
    }

    #[test]
    fn test_navigation_after_filtering() {
        let items = vec![
            PickerItem::new("feature/a", PickerData::Item("feature/a".to_string())),
            PickerItem::new("feature/b", PickerData::Item("feature/b".to_string())),
            PickerItem::new("main", PickerData::Item("main".to_string())),
            PickerItem::new("develop", PickerData::Item("develop".to_string())),
        ];

        let mut state = PickerState::new("Select", items, false);

        // Filter to get only feature/* branches
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        // Should have 2 filtered items
        assert_eq!(state.filtered_count(), 2);
        assert_eq!(state.cursor(), 0);

        // Navigate through filtered items
        state.next();
        assert_eq!(state.cursor(), 1);

        // Wrap around
        state.next();
        assert_eq!(state.cursor(), 0);

        // Go backwards
        state.previous();
        assert_eq!(state.cursor(), 1);
    }

    #[test]
    fn test_selected_returns_correct_item() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        let selected = state.selected().unwrap();
        assert_eq!(selected.display.as_ref(), "main");

        state.next();
        state.next();
        let selected = state.selected().unwrap();
        assert_eq!(selected.display.as_ref(), "feature/test");
    }

    #[test]
    fn test_selected_with_filter() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::empty()));
        state.update_filter();

        // Should match "bugfix/123"
        let selected = state.selected().unwrap();
        assert_eq!(selected.display.as_ref(), "bugfix/123");
    }

    #[test]
    fn test_selected_returns_custom_input() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        // Use a pattern that doesn't match any items
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::empty()));
        state.update_filter();

        // No matches, only custom input at cursor 0
        assert_eq!(state.cursor(), 0);
        assert_eq!(state.selected().unwrap().display.as_ref(), "qq");
    }

    #[test]
    fn test_select_custom_input() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        // Type a pattern that doesn't match anything
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::empty()));
        state.update_filter();

        // Should have no matches but custom input
        assert_eq!(state.filtered_count(), 0);
        assert!(state.custom_input_item.is_some());

        // Cursor should be at custom input (position 0 since no other items)
        assert_eq!(state.cursor(), 0);

        // Selected item should be the custom input
        let selected = state.selected().unwrap();
        assert_eq!(selected.display, "xyz");
        match &selected.data {
            PickerData::CustomInput(s) => assert_eq!(s, "xyz"),
            _ => panic!("Expected CustomInput"),
        }

        // Mark as done
        state.done();
        assert!(state.is_done());
        assert_eq!(state.status(), &PickerStatus::Done);
    }

    #[test]
    fn test_filtered_items_order() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::empty()));
        state.update_filter();

        let indices: Vec<_> = state.filtered_items().map(|(idx, _)| idx).collect();

        // Verify normal item indices followed by custom input
        assert_eq!(indices[0], 2); // feature/test
        assert_eq!(indices[1], 3); // feature/new
        assert_eq!(indices[2], 4); // bugfix/123
        assert_eq!(indices[3], usize::MAX); // custom input
    }

    #[test]
    fn test_match_indices_with_pattern() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::empty()));
        state.update_filter();

        // Get the index of "main" in original items
        let indices = state.match_indices(0);
        assert!(indices.is_some());

        let indices = indices.unwrap();
        assert_eq!(indices.len(), 3); // 'm', 'a', 'i' should match
    }

    #[test]
    fn test_match_indices_empty_pattern() {
        let items = create_test_items();
        let state = PickerState::new("Select", items, false);

        let indices = state.match_indices(0);
        assert!(indices.is_none());
    }

    #[test]
    fn test_match_indices_custom_input_returns_none() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, true);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::empty()));
        state.update_filter();

        // usize::MAX is used for custom input items
        let indices = state.match_indices(usize::MAX);
        assert!(indices.is_none());
    }

    #[test]
    fn test_status_transitions() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        assert_eq!(state.status(), &PickerStatus::Active);
        assert!(!state.is_done());
        assert!(!state.is_cancelled());

        state.done();
        assert_eq!(state.status(), &PickerStatus::Done);
        assert!(state.is_done());
        assert!(!state.is_cancelled());
    }

    #[test]
    fn test_status_cancelled() {
        let items = create_test_items();
        let mut state = PickerState::new("Select", items, false);

        state.cancel();
        assert_eq!(state.status(), &PickerStatus::Cancelled);
        assert!(!state.is_done());
        assert!(state.is_cancelled());
    }

    #[test]
    fn test_empty_items_list() {
        let state = PickerState::new("Select", vec![], false);

        assert_eq!(state.total_items(), 0);
        assert_eq!(state.filtered_count(), 0);
        assert_eq!(state.cursor(), 0);
        assert!(state.selected().is_none());
    }

    #[test]
    fn test_empty_items_with_custom_input() {
        let mut state = PickerState::new("Select", vec![], true);

        state
            .input_state
            .handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::empty()));
        state.update_filter();

        assert_eq!(state.total_items(), 0);
        assert_eq!(state.filtered_count(), 0);
        assert!(state.custom_input_item.is_some());

        assert_eq!(state.selected().unwrap().display.as_ref(), "a");
    }

    #[test]
    fn test_cursor_navigation_empty_list() {
        let mut state = PickerState::new("Select", vec![], false);

        state.next();
        assert_eq!(state.cursor(), 0);

        state.previous();
        assert_eq!(state.cursor(), 0);
    }

    #[test]
    fn test_single_item_navigation() {
        let items = vec![PickerItem::new(
            "only",
            PickerData::Item("only".to_string()),
        )];
        let mut state = PickerState::new("Select", items, false);

        assert_eq!(state.cursor(), 0);

        state.next();
        assert_eq!(state.cursor(), 0); // Wraps to same item

        state.previous();
        assert_eq!(state.cursor(), 0); // Wraps to same item
    }

    #[test]
    fn test_with_refs_basic_sorting() {
        // Test that items are sorted as: default -> branches -> tags -> remotes
        let refs = &[
            Ref::Tag("v1.0.0".to_string()),
            Ref::Remote("origin/main".to_string()),
            Ref::Head("feature".to_string()),
            Ref::Head("main".to_string()),
            Ref::Tag("v2.0.0".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default: None,
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // Order is preserved from input
        assert_eq!(
            items,
            &[
                "tag: v1.0.0",
                "origin/main",
                "feature",
                "main",
                "tag: v2.0.0"
            ]
        )
    }

    #[test]
    fn test_with_refs_empty_list() {
        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs: &[],
            exclude_ref: None,
            default: None,
            allow_custom_input: false,
        });

        assert_eq!(state.total_items(), 0);
        assert_eq!(state.filtered_count(), 0);
        assert!(state.selected().is_none());
    }

    #[test]
    fn test_with_refs_with_default() {
        // Test that default ref is shown first
        let refs = &[
            Ref::Head("feature".to_string()),
            Ref::Head("main".to_string()),
            Ref::Tag("v1.0.0".to_string()),
        ];

        let default = Some(Rev::Ref(Ref::Head("main".to_string())));
        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default,
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // Default should be first, then remaining in input order
        assert_eq!(&items, &["main", "feature", "tag: v1.0.0"]);
    }

    #[test]
    fn test_with_refs_exclude_ref() {
        // Test that excluded ref is not shown
        let refs = &[
            Ref::Head("feature".to_string()),
            Ref::Head("main".to_string()),
            Ref::Tag("v1.0.0".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: Some(Ref::Head("main".to_string())),
            default: None,
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // main should be excluded
        assert_eq!(&items, &["feature", "tag: v1.0.0"])
    }

    #[test]
    fn test_with_refs_duplicate_names() {
        // Tag and branch with same name are disambiguated by "tag: " prefix
        let refs = &[
            Ref::Head("v1.0.0".to_string()),
            Ref::Tag("v1.0.0".to_string()),
            Ref::Head("main".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default: None,
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        assert_eq!(&items, &["v1.0.0", "tag: v1.0.0", "main"])
    }

    #[test]
    fn test_with_refs_duplicate_with_default() {
        // Tag default shown with "tag: " prefix
        let refs = &[
            Ref::Head("v1.0.0".to_string()),
            Ref::Tag("v1.0.0".to_string()),
            Ref::Head("main".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default: Some(Rev::Ref(Ref::Tag("v1.0.0".to_string()))),
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        assert_eq!(items, &["tag: v1.0.0", "v1.0.0", "main"])
    }

    #[test]
    fn test_with_refs_exclude_and_default_same() {
        // Test when exclude and default are the same
        // The implementation adds default first, then filters exclude from remaining items
        // So if default == exclude, default is still added, then exclude filters it from the rest
        let refs = &[
            Ref::Head("feature".to_string()),
            Ref::Head("main".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: Some(Ref::Head("main".to_string())),
            default: Some(Rev::Ref(Ref::Head("main".to_string()))),
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // Default is added first, then exclude filters remaining items
        // So we get: main (default) + feature (not excluded)
        assert_eq!(&items, &["main", "feature"])
    }

    #[test]
    fn test_with_refs_with_custom_input() {
        let refs = &[
            Ref::Head("main".to_string()),
            Ref::Tag("v1.0.0".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default: None,
            allow_custom_input: true,
        });

        // Custom input should be allowed
        assert!(state.allow_custom_input);

        // With empty pattern, no custom input item
        assert!(state.custom_input_item.is_none());
    }

    #[test]
    fn test_with_refs_exclude_tag_sibling() {
        // If branch is excluded, remaining tag still shows "tag: " prefix
        let refs = &[
            Ref::Head("v1.0.0".to_string()),
            Ref::Tag("v1.0.0".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: Some(Ref::Head("v1.0.0".to_string())),
            default: None,
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        assert_eq!(&items, &["tag: v1.0.0"]);
    }

    #[test]
    fn test_with_refs_remote_tracking_default() {
        let refs = &[
            Ref::Head("main".to_string()),
            Ref::Remote("origin/main".to_string()),
            Ref::Remote("origin/feature".to_string()),
        ];

        let state = PickerState::with_refs(PickerParams {
            prompt: "Select".into(),
            refs,
            exclude_ref: None,
            default: Some(Rev::Ref(Ref::Remote("origin/main".to_string()))),
            allow_custom_input: false,
        });

        let items: Vec<_> = state
            .filtered_items()
            .map(|(_, item)| item.display.as_ref())
            .collect();

        // Default remote-tracking branch shown first as shorthand, then remaining
        assert_eq!(&items, &["origin/main", "main", "origin/feature"]);
    }
}