npm-run-scripts 1.0.2

Fast interactive TUI for running npm scripts
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
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
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
//! Application state for the TUI.

use std::collections::HashSet;
use std::path::PathBuf;

use crate::config::{Config, SortMode};
use crate::history::History;
use crate::package::{Runner, Script, Scripts, Workspace};

/// Minimum column width for script items.
const MIN_COLUMN_WIDTH: u16 = 28;

/// Application mode/state.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum AppMode {
    /// Normal navigation mode.
    #[default]
    Normal,
    /// Filter/search mode.
    Filter { query: String },
    /// Multi-select mode.
    MultiSelect { selected: HashSet<usize> },
    /// Help overlay.
    Help,
    /// Error display.
    Error { message: String },
    /// Arguments input mode.
    Args { script_index: usize, input: String },
    /// Workspace selection mode (for monorepos).
    WorkspaceSelect,
}

/// Currently selected workspace context.
#[derive(Debug, Clone, PartialEq)]
pub enum WorkspaceContext {
    /// Root scripts (no specific workspace selected).
    Root,
    /// A specific workspace is selected.
    Workspace(usize),
}

/// Information about a script to run after TUI exits.
#[derive(Debug, Clone)]
pub struct ScriptRun {
    /// The script to run.
    pub script: Script,
    /// Optional arguments to pass to the script.
    pub args: Option<String>,
    /// Workspace name if running from a specific workspace.
    pub workspace: Option<String>,
    /// Workspace path if running from a specific workspace.
    pub workspace_path: Option<PathBuf>,
}

impl std::fmt::Display for ScriptRun {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let prefix = if let Some(ws) = &self.workspace {
            format!("{} > ", ws)
        } else {
            String::new()
        };

        if let Some(args) = &self.args {
            write!(f, "{}{} {}", prefix, self.script.name(), args)
        } else {
            write!(f, "{}{}", prefix, self.script.name())
        }
    }
}

/// Main application state.
pub struct App {
    // Data
    /// All available scripts.
    scripts: Scripts,
    /// Current configuration.
    config: Config,
    /// Execution history.
    history: History,
    /// Detected package manager.
    runner: Runner,
    /// Project name.
    project_name: String,
    /// Project path.
    project_path: PathBuf,

    // Workspace data
    /// Whether this is a monorepo.
    is_monorepo: bool,
    /// Available workspaces (if monorepo).
    workspaces: Vec<Workspace>,
    /// Currently selected workspace context.
    workspace_context: WorkspaceContext,
    /// Selected workspace index (for workspace selector).
    workspace_selected: usize,

    // UI State
    /// Current application mode.
    mode: AppMode,
    /// Currently selected script index (within visible_indices).
    selected: usize,
    /// Scroll offset for the scripts list.
    scroll_offset: usize,
    /// Current filter text.
    filter_text: String,
    /// Current sort mode.
    sort_mode: SortMode,

    // Computed (cached)
    /// Indices of visible scripts (after filtering and sorting).
    visible_indices: Vec<usize>,
    /// Number of columns in the grid.
    columns: usize,
    /// Should the app quit.
    should_quit: bool,
    /// Script to run after exit.
    script_to_run: Option<ScriptRun>,
}

impl App {
    /// Create a new application.
    pub fn new(
        scripts: Scripts,
        config: Config,
        history: History,
        project_name: String,
        project_path: PathBuf,
        runner: Runner,
    ) -> Self {
        Self::with_workspaces(
            scripts,
            config,
            history,
            project_name,
            project_path,
            runner,
            Vec::new(),
        )
    }

    /// Create a new application with workspace support.
    pub fn with_workspaces(
        scripts: Scripts,
        config: Config,
        history: History,
        project_name: String,
        project_path: PathBuf,
        runner: Runner,
        workspaces: Vec<Workspace>,
    ) -> Self {
        let sort_mode = config.general.default_sort;
        let visible_indices: Vec<usize> = (0..scripts.len()).collect();
        let is_monorepo = !workspaces.is_empty();

        // Start in workspace select mode if this is a monorepo with workspaces
        let initial_mode = if is_monorepo {
            AppMode::WorkspaceSelect
        } else {
            AppMode::Normal
        };

        let mut app = Self {
            scripts,
            config,
            history,
            runner,
            project_name,
            project_path,
            is_monorepo,
            workspaces,
            workspace_context: WorkspaceContext::Root,
            workspace_selected: 0,
            mode: initial_mode,
            selected: 0,
            scroll_offset: 0,
            filter_text: String::new(),
            sort_mode,
            visible_indices,
            columns: 1,
            should_quit: false,
            script_to_run: None,
        };

        // Initial sort based on default sort mode
        app.update_visible_scripts();
        app
    }

    // ==================== Getters ====================

    /// Get the current mode.
    pub fn mode(&self) -> &AppMode {
        &self.mode
    }

    /// Check if the app should quit.
    pub fn should_quit(&self) -> bool {
        self.should_quit
    }

    /// Get the script to run after exit.
    pub fn script_to_run(&self) -> Option<&ScriptRun> {
        self.script_to_run.as_ref()
    }

    /// Get the project name.
    pub fn project_name(&self) -> &str {
        &self.project_name
    }

    /// Get the project path.
    pub fn project_path(&self) -> &PathBuf {
        &self.project_path
    }

    /// Get the runner.
    pub fn runner(&self) -> Runner {
        self.runner
    }

    /// Get all scripts.
    pub fn scripts(&self) -> &Scripts {
        &self.scripts
    }

    /// Get the current filter text.
    pub fn filter_text(&self) -> &str {
        &self.filter_text
    }

    /// Get the current sort mode.
    pub fn sort_mode(&self) -> SortMode {
        self.sort_mode
    }

    /// Get the number of columns.
    pub fn columns(&self) -> usize {
        self.columns
    }

    /// Get the selected index.
    pub fn selected_index(&self) -> usize {
        self.selected
    }

    /// Get the scroll offset.
    pub fn scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    /// Get the number of visible scripts.
    pub fn visible_count(&self) -> usize {
        self.visible_indices.len()
    }

    /// Get the config.
    pub fn config(&self) -> &Config {
        &self.config
    }

    // ==================== Workspace Getters ====================

    /// Check if this is a monorepo.
    pub fn is_monorepo(&self) -> bool {
        self.is_monorepo
    }

    /// Get the available workspaces.
    pub fn workspaces(&self) -> &[Workspace] {
        &self.workspaces
    }

    /// Get the current workspace context.
    pub fn workspace_context(&self) -> &WorkspaceContext {
        &self.workspace_context
    }

    /// Get the selected workspace index in the workspace selector.
    pub fn workspace_selected(&self) -> usize {
        self.workspace_selected
    }

    /// Get the currently selected workspace (if any).
    pub fn current_workspace(&self) -> Option<&Workspace> {
        match &self.workspace_context {
            WorkspaceContext::Root => None,
            WorkspaceContext::Workspace(idx) => self.workspaces.get(*idx),
        }
    }

    /// Get the breadcrumb path for display.
    /// Returns something like "monorepo > packages/web > scripts"
    pub fn breadcrumb(&self) -> String {
        match &self.workspace_context {
            WorkspaceContext::Root => self.project_name.clone(),
            WorkspaceContext::Workspace(idx) => {
                if let Some(ws) = self.workspaces.get(*idx) {
                    format!("{} > {}", self.project_name, ws.name())
                } else {
                    self.project_name.clone()
                }
            }
        }
    }

    // ==================== Script Access ====================

    /// Get visible scripts after filtering and sorting.
    pub fn visible_scripts(&self) -> Vec<&Script> {
        self.visible_indices
            .iter()
            .filter_map(|&i| self.scripts.iter().nth(i))
            .collect()
    }

    /// Get the currently selected script.
    pub fn selected_script(&self) -> Option<&Script> {
        self.visible_indices
            .get(self.selected)
            .and_then(|&i| self.scripts.iter().nth(i))
    }

    /// Get a visible script by its display index (0-based).
    pub fn get_visible_script(&self, index: usize) -> Option<&Script> {
        self.visible_indices
            .get(index)
            .and_then(|&i| self.scripts.iter().nth(i))
    }

    // ==================== Mode Management ====================

    /// Set the application mode.
    pub fn set_mode(&mut self, mode: AppMode) {
        self.mode = mode;
    }

    /// Toggle filter mode.
    pub fn toggle_filter_mode(&mut self) {
        match &self.mode {
            AppMode::Filter { .. } => {
                self.mode = AppMode::Normal;
                self.filter_text.clear();
                self.update_visible_scripts();
            }
            AppMode::Normal => {
                self.mode = AppMode::Filter {
                    query: String::new(),
                };
            }
            _ => {}
        }
    }

    /// Enter args input mode for the selected script.
    pub fn enter_args_mode(&mut self) {
        if self.selected < self.visible_indices.len() {
            self.mode = AppMode::Args {
                script_index: self.selected,
                input: String::new(),
            };
        }
    }

    /// Toggle multi-select mode.
    pub fn toggle_multi_select(&mut self) {
        match &self.mode {
            AppMode::MultiSelect { .. } => {
                self.mode = AppMode::Normal;
            }
            AppMode::Normal => {
                self.mode = AppMode::MultiSelect {
                    selected: HashSet::new(),
                };
            }
            _ => {}
        }
    }

    /// Toggle help overlay.
    pub fn toggle_help(&mut self) {
        match self.mode {
            AppMode::Help => {
                self.mode = AppMode::Normal;
            }
            _ => {
                self.mode = AppMode::Help;
            }
        }
    }

    // ==================== Workspace Management ====================

    /// Enter workspace selection mode.
    pub fn enter_workspace_select(&mut self) {
        if self.is_monorepo {
            self.mode = AppMode::WorkspaceSelect;
            self.workspace_selected = 0;
        }
    }

    /// Exit workspace selection and go to scripts.
    pub fn exit_workspace_select(&mut self) {
        self.mode = AppMode::Normal;
        self.selected = 0;
        self.update_visible_scripts();
    }

    /// Select a workspace and show its scripts.
    pub fn select_workspace(&mut self, index: usize) {
        // Index 0 is "root", indices 1+ are workspaces
        if index == 0 {
            self.workspace_context = WorkspaceContext::Root;
            // Keep root scripts
        } else if let Some(workspace) = self.workspaces.get(index - 1) {
            self.workspace_context = WorkspaceContext::Workspace(index - 1);
            // Load workspace scripts
            self.scripts = Scripts::from_vec(workspace.scripts().to_vec());
        }

        self.selected = 0;
        self.mode = AppMode::Normal;
        self.update_visible_scripts();
    }

    /// Select the currently highlighted workspace.
    pub fn select_current_workspace(&mut self) {
        self.select_workspace(self.workspace_selected);
    }

    /// Go back to workspace selection from script view.
    pub fn back_to_workspace_select(&mut self) {
        if self.is_monorepo {
            self.mode = AppMode::WorkspaceSelect;
        }
    }

    /// Move workspace selection up.
    pub fn workspace_move_up(&mut self) {
        if self.workspace_selected > 0 {
            self.workspace_selected -= 1;
        }
    }

    /// Move workspace selection down.
    pub fn workspace_move_down(&mut self) {
        // +1 for the "root" option
        let max_index = self.workspaces.len();
        if self.workspace_selected < max_index {
            self.workspace_selected += 1;
        }
    }

    /// Move workspace selection left (in grid).
    pub fn workspace_move_left(&mut self) {
        if self.workspace_selected > 0 {
            self.workspace_selected -= 1;
        }
    }

    /// Move workspace selection right (in grid).
    pub fn workspace_move_right(&mut self) {
        let max_index = self.workspaces.len();
        if self.workspace_selected < max_index {
            self.workspace_selected += 1;
        }
    }

    /// Select workspace by number (1-9).
    pub fn select_workspace_by_number(&mut self, num: usize) {
        // num 1 = root (index 0), num 2 = first workspace (index 1), etc.
        if num > 0 && num <= self.workspaces.len() + 1 {
            self.select_workspace(num - 1);
        }
    }

    /// Get the count of items in workspace selector (root + workspaces).
    pub fn workspace_count(&self) -> usize {
        self.workspaces.len() + 1 // +1 for root
    }

    // ==================== Filter Management ====================

    /// Set the filter text.
    pub fn set_filter(&mut self, text: String) {
        self.filter_text = text.clone();
        self.mode = AppMode::Filter { query: text };
        self.update_visible_scripts();
    }

    /// Append a character to the filter text.
    pub fn push_filter_char(&mut self, c: char) {
        self.filter_text.push(c);
        self.update_visible_scripts();
    }

    /// Remove the last character from the filter text.
    pub fn pop_filter_char(&mut self) {
        self.filter_text.pop();
        self.update_visible_scripts();
    }

    /// Clear the filter text.
    pub fn clear_filter(&mut self) {
        self.filter_text.clear();
        self.update_visible_scripts();
    }

    // ==================== Sort Management ====================

    /// Cycle through sort modes: Recent -> Alphabetical -> Category -> Recent.
    pub fn cycle_sort_mode(&mut self) {
        self.sort_mode = match self.sort_mode {
            SortMode::Recent => SortMode::Alpha,
            SortMode::Alpha => SortMode::Category,
            SortMode::Category => SortMode::Recent,
        };
        self.update_visible_scripts();
    }

    /// Set the sort mode.
    pub fn set_sort_mode(&mut self, mode: SortMode) {
        self.sort_mode = mode;
        self.update_visible_scripts();
    }

    // ==================== Visibility Update ====================

    /// Update the visible scripts based on current filter and sort mode.
    pub fn update_visible_scripts(&mut self) {
        // Step 1: Filter
        let filtered_indices: Vec<usize> = if self.filter_text.is_empty() {
            (0..self.scripts.len()).collect()
        } else {
            // Use the optimized filter_scripts that returns (index, score) pairs
            let matches = crate::filter::filter_scripts(
                &self.filter_text,
                self.scripts.as_slice(),
                self.config.filter.search_descriptions,
            );

            matches.into_iter().map(|(idx, _score)| idx).collect()
        };

        // Step 2: Sort
        self.visible_indices = self.sort_indices(filtered_indices);

        // Adjust selection if needed
        if self.selected >= self.visible_indices.len() {
            self.selected = self.visible_indices.len().saturating_sub(1);
        }
    }

    /// Sort indices based on current sort mode.
    fn sort_indices(&self, mut indices: Vec<usize>) -> Vec<usize> {
        match self.sort_mode {
            SortMode::Recent => {
                // Sort by history score (recent/frequent first)
                // Clone scripts so we can pass them to get_sorted_by_recent
                let scripts_owned: Vec<Script> = indices
                    .iter()
                    .filter_map(|&i| self.scripts.iter().nth(i).cloned())
                    .collect();

                let sorted = self
                    .history
                    .get_sorted_by_recent(&self.project_path, &scripts_owned);

                // Map back to indices
                sorted
                    .iter()
                    .filter_map(|s| {
                        self.scripts
                            .iter()
                            .position(|script| script.name() == s.name())
                    })
                    .filter(|i| indices.contains(i))
                    .collect()
            }
            SortMode::Alpha => {
                // Sort alphabetically by name
                indices.sort_by(|&a, &b| {
                    let name_a = self.scripts.iter().nth(a).map(|s| s.name()).unwrap_or("");
                    let name_b = self.scripts.iter().nth(b).map(|s| s.name()).unwrap_or("");
                    name_a.cmp(name_b)
                });
                indices
            }
            SortMode::Category => {
                // Sort by category (prefix before colon) then alphabetically
                indices.sort_by(|&a, &b| {
                    let name_a = self.scripts.iter().nth(a).map(|s| s.name()).unwrap_or("");
                    let name_b = self.scripts.iter().nth(b).map(|s| s.name()).unwrap_or("");

                    let category_a = name_a.split(':').next().unwrap_or(name_a);
                    let category_b = name_b.split(':').next().unwrap_or(name_b);

                    category_a.cmp(category_b).then_with(|| name_a.cmp(name_b))
                });
                indices
            }
        }
    }

    // ==================== Column Management ====================

    /// Update the number of columns based on terminal width.
    pub fn update_columns(&mut self, width: u16) {
        self.columns = calculate_columns(width);
    }

    // ==================== Navigation ====================

    /// Calculate the number of rows based on visible items and columns.
    fn row_count(&self) -> usize {
        let count = self.visible_indices.len();
        if count == 0 || self.columns == 0 {
            return 0;
        }
        (count + self.columns - 1) / self.columns
    }

    /// Get the current row and column from the selected index.
    fn current_position(&self) -> (usize, usize) {
        let row = self.selected / self.columns;
        let col = self.selected % self.columns;
        (row, col)
    }

    /// Move selection up by one row.
    pub fn move_up(&mut self) {
        if self.visible_indices.is_empty() || self.columns == 0 {
            return;
        }

        let (row, col) = self.current_position();
        if row > 0 {
            let new_index = (row - 1) * self.columns + col;
            if new_index < self.visible_indices.len() {
                self.selected = new_index;
            }
        }
    }

    /// Move selection down by one row.
    pub fn move_down(&mut self) {
        if self.visible_indices.is_empty() || self.columns == 0 {
            return;
        }

        let (row, col) = self.current_position();
        let new_index = (row + 1) * self.columns + col;

        if new_index < self.visible_indices.len() {
            self.selected = new_index;
        } else {
            // Try to go to last row, same column or last item
            let last_row = self.row_count().saturating_sub(1);
            if row < last_row {
                // Go to last item if the target column doesn't exist in last row
                self.selected = self.visible_indices.len().saturating_sub(1);
            }
        }
    }

    /// Move selection left by one column.
    pub fn move_left(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    /// Move selection right by one column.
    pub fn move_right(&mut self) {
        if self.selected < self.visible_indices.len().saturating_sub(1) {
            self.selected += 1;
        }
    }

    /// Move selection to the first item.
    pub fn move_to_first(&mut self) {
        self.selected = 0;
    }

    /// Move selection to the last item.
    pub fn move_to_last(&mut self) {
        self.selected = self.visible_indices.len().saturating_sub(1);
    }

    /// Select a script by number (1-9).
    pub fn select_by_number(&mut self, num: usize) {
        if num > 0 && num <= self.visible_indices.len() {
            self.selected = num - 1;
        }
    }

    // ==================== Navigation Aliases (for compatibility) ====================

    /// Move selection up (alias for move_up).
    pub fn select_prev(&mut self) {
        self.move_up();
    }

    /// Move selection down (alias for move_down).
    pub fn select_next(&mut self) {
        self.move_down();
    }

    /// Move to first item (alias for move_to_first).
    pub fn select_first(&mut self) {
        self.move_to_first();
    }

    /// Move to last item (alias for move_to_last).
    pub fn select_last(&mut self) {
        self.move_to_last();
    }

    // ==================== Actions ====================

    /// Request the app to quit.
    pub fn quit(&mut self) {
        self.should_quit = true;
    }

    /// Run the currently selected script.
    pub fn run_selected(&mut self) -> Option<ScriptRun> {
        if let Some(script) = self.selected_script() {
            let (workspace, workspace_path) = self.get_workspace_info();
            let run = ScriptRun {
                script: script.clone(),
                args: None,
                workspace,
                workspace_path,
            };
            self.script_to_run = Some(run.clone());
            self.should_quit = true;
            Some(run)
        } else {
            None
        }
    }

    /// Get workspace info for script execution.
    fn get_workspace_info(&self) -> (Option<String>, Option<PathBuf>) {
        match &self.workspace_context {
            WorkspaceContext::Root => (None, None),
            WorkspaceContext::Workspace(idx) => {
                if let Some(ws) = self.workspaces.get(*idx) {
                    (Some(ws.name().to_string()), Some(ws.path().to_path_buf()))
                } else {
                    (None, None)
                }
            }
        }
    }

    /// Run a script by number (1-9).
    pub fn run_numbered(&mut self, num: usize) -> Option<ScriptRun> {
        if num > 0 && num <= self.visible_indices.len() {
            self.selected = num - 1;
            self.run_selected()
        } else {
            None
        }
    }

    /// Run a script by number (alias for run_numbered, for compatibility).
    pub fn run_by_number(&mut self, num: usize) {
        self.run_numbered(num);
    }

    /// Run the selected script with arguments.
    pub fn run_with_args(&mut self, args: String) -> Option<ScriptRun> {
        if let Some(script) = self.selected_script() {
            let (workspace, workspace_path) = self.get_workspace_info();
            let run = ScriptRun {
                script: script.clone(),
                args: if args.is_empty() { None } else { Some(args) },
                workspace,
                workspace_path,
            };
            self.script_to_run = Some(run.clone());
            self.should_quit = true;
            Some(run)
        } else {
            None
        }
    }

    /// Toggle selection of current item in multi-select mode.
    pub fn toggle_current_selection(&mut self) {
        if let AppMode::MultiSelect { ref mut selected } = self.mode {
            if selected.contains(&self.selected) {
                selected.remove(&self.selected);
            } else {
                selected.insert(self.selected);
            }
        }
    }

    /// Get selected indices in multi-select mode.
    pub fn multi_selected_indices(&self) -> Option<&HashSet<usize>> {
        if let AppMode::MultiSelect { ref selected } = self.mode {
            Some(selected)
        } else {
            None
        }
    }

    /// Run all selected scripts in multi-select mode.
    pub fn run_multi_selected(&mut self) -> Vec<ScriptRun> {
        let (workspace, workspace_path) = self.get_workspace_info();
        let runs: Vec<ScriptRun> = if let AppMode::MultiSelect { ref selected } = self.mode {
            selected
                .iter()
                .filter_map(|&idx| {
                    self.get_visible_script(idx).map(|script| ScriptRun {
                        script: script.clone(),
                        args: None,
                        workspace: workspace.clone(),
                        workspace_path: workspace_path.clone(),
                    })
                })
                .collect()
        } else {
            vec![]
        };

        if !runs.is_empty() {
            // Set first script to run, the rest would need to be handled by the caller
            self.script_to_run = runs.first().cloned();
            self.should_quit = true;
        }

        runs
    }
}

/// Calculate grid columns based on terminal width.
pub fn calculate_columns(width: u16) -> usize {
    if width < 60 {
        1
    } else if width < 90 {
        2
    } else if width < 120 {
        3
    } else if width < 160 {
        4
    } else {
        5
    }
}

/// Calculate column width for the scripts grid.
pub fn calculate_column_width(total_width: u16, columns: usize) -> u16 {
    if columns == 0 {
        return total_width;
    }
    let padding = 2; // Left and right padding
    let available = total_width.saturating_sub(padding * 2);
    (available / columns as u16).max(MIN_COLUMN_WIDTH)
}

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

    fn create_test_scripts() -> Scripts {
        let mut scripts = Scripts::new();
        scripts.add(Script::new("dev", "vite"));
        scripts.add(Script::new("build", "vite build"));
        scripts.add(Script::new("test", "vitest"));
        scripts.add(Script::new("lint", "eslint ."));
        scripts.add(Script::new("format", "prettier --write ."));
        scripts.add(Script::new("typecheck", "tsc --noEmit"));
        scripts.add(Script::new("build:prod", "vite build --mode production"));
        scripts.add(Script::new("build:dev", "vite build --mode development"));
        scripts.add(Script::new("test:unit", "vitest unit"));
        scripts
    }

    fn create_test_app() -> App {
        let scripts = create_test_scripts();
        let config = Config::default();
        let history = History::new();
        App::new(
            scripts,
            config,
            history,
            "test-project".to_string(),
            PathBuf::from("/test/project"),
            Runner::Npm,
        )
    }

    // ==================== Basic Tests ====================

    #[test]
    fn test_app_new() {
        let app = create_test_app();
        assert_eq!(app.project_name(), "test-project");
        assert_eq!(app.runner(), Runner::Npm);
        assert!(!app.should_quit());
        assert!(app.script_to_run().is_none());
        assert_eq!(app.mode(), &AppMode::Normal);
    }

    #[test]
    fn test_visible_scripts() {
        let app = create_test_app();
        let visible = app.visible_scripts();
        assert_eq!(visible.len(), 9);
    }

    #[test]
    fn test_selected_script() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha); // Ensure predictable order
        let script = app.selected_script().unwrap();
        // First alphabetically should be "build"
        assert_eq!(script.name(), "build");
    }

    // ==================== Navigation Tests ====================

    #[test]
    fn test_move_left_right() {
        let mut app = create_test_app();
        app.update_columns(100); // 3 columns
        app.set_sort_mode(SortMode::Alpha);

        assert_eq!(app.selected_index(), 0);

        app.move_right();
        assert_eq!(app.selected_index(), 1);

        app.move_right();
        assert_eq!(app.selected_index(), 2);

        app.move_left();
        assert_eq!(app.selected_index(), 1);

        app.move_left();
        assert_eq!(app.selected_index(), 0);

        // Should not go below 0
        app.move_left();
        assert_eq!(app.selected_index(), 0);
    }

    #[test]
    fn test_move_up_down_single_column() {
        let mut app = create_test_app();
        app.update_columns(50); // 1 column
        app.set_sort_mode(SortMode::Alpha);

        assert_eq!(app.selected_index(), 0);

        app.move_down();
        assert_eq!(app.selected_index(), 1);

        app.move_down();
        assert_eq!(app.selected_index(), 2);

        app.move_up();
        assert_eq!(app.selected_index(), 1);

        app.move_up();
        assert_eq!(app.selected_index(), 0);

        // Should not go above 0
        app.move_up();
        assert_eq!(app.selected_index(), 0);
    }

    #[test]
    fn test_move_up_down_multi_column() {
        let mut app = create_test_app();
        app.update_columns(100); // 3 columns
        app.set_sort_mode(SortMode::Alpha);

        // Grid layout (9 items, 3 columns):
        // 0 1 2
        // 3 4 5
        // 6 7 8

        assert_eq!(app.selected_index(), 0);

        app.move_down(); // 0 -> 3
        assert_eq!(app.selected_index(), 3);

        app.move_down(); // 3 -> 6
        assert_eq!(app.selected_index(), 6);

        app.move_right(); // 6 -> 7
        assert_eq!(app.selected_index(), 7);

        app.move_up(); // 7 -> 4
        assert_eq!(app.selected_index(), 4);

        app.move_up(); // 4 -> 1
        assert_eq!(app.selected_index(), 1);
    }

    #[test]
    fn test_move_to_first_last() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        app.move_to_last();
        assert_eq!(app.selected_index(), 8); // 9 items, 0-indexed

        app.move_to_first();
        assert_eq!(app.selected_index(), 0);
    }

    #[test]
    fn test_select_by_number() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        app.select_by_number(5);
        assert_eq!(app.selected_index(), 4); // 5 -> index 4

        app.select_by_number(1);
        assert_eq!(app.selected_index(), 0);

        app.select_by_number(9);
        assert_eq!(app.selected_index(), 8);

        // Invalid numbers should not change selection
        app.select_by_number(0);
        assert_eq!(app.selected_index(), 8);

        app.select_by_number(100);
        assert_eq!(app.selected_index(), 8);
    }

    // ==================== Filter Tests ====================

    #[test]
    fn test_filter_updates_visible() {
        let mut app = create_test_app();

        app.set_filter("build".to_string());
        let visible = app.visible_scripts();

        // Should match: build, build:prod, build:dev
        assert_eq!(visible.len(), 3);
        assert!(visible.iter().all(|s| s.name().contains("build")));
    }

    #[test]
    fn test_filter_adjusts_selection() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        // Select last item
        app.move_to_last();
        assert_eq!(app.selected_index(), 8);

        // Filter to fewer items
        app.set_filter("test".to_string());

        // Selection should be adjusted to be within bounds
        assert!(app.selected_index() < app.visible_count());
    }

    #[test]
    fn test_filter_clear() {
        let mut app = create_test_app();

        app.set_filter("dev".to_string());
        assert!(app.visible_count() < 9);

        app.clear_filter();
        assert_eq!(app.visible_count(), 9);
    }

    #[test]
    fn test_filter_char_operations() {
        let mut app = create_test_app();

        app.push_filter_char('t');
        assert_eq!(app.filter_text(), "t");

        app.push_filter_char('e');
        assert_eq!(app.filter_text(), "te");

        app.pop_filter_char();
        assert_eq!(app.filter_text(), "t");

        app.pop_filter_char();
        assert_eq!(app.filter_text(), "");
    }

    // ==================== Sort Mode Tests ====================

    #[test]
    fn test_cycle_sort_mode() {
        let mut app = create_test_app();

        assert_eq!(app.sort_mode(), SortMode::Recent); // Default

        app.cycle_sort_mode();
        assert_eq!(app.sort_mode(), SortMode::Alpha);

        app.cycle_sort_mode();
        assert_eq!(app.sort_mode(), SortMode::Category);

        app.cycle_sort_mode();
        assert_eq!(app.sort_mode(), SortMode::Recent);
    }

    #[test]
    fn test_sort_mode_alpha() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        let visible = app.visible_scripts();
        let names: Vec<&str> = visible.iter().map(|s| s.name()).collect();

        // Should be alphabetically sorted
        let mut sorted_names = names.clone();
        sorted_names.sort();
        assert_eq!(names, sorted_names);
    }

    #[test]
    fn test_sort_mode_category() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Category);

        let visible = app.visible_scripts();
        let names: Vec<&str> = visible.iter().map(|s| s.name()).collect();

        // Scripts with "build" prefix should be together
        let build_indices: Vec<usize> = names
            .iter()
            .enumerate()
            .filter(|(_, n)| n.starts_with("build"))
            .map(|(i, _)| i)
            .collect();

        // Build scripts should be consecutive
        if build_indices.len() > 1 {
            for i in 1..build_indices.len() {
                assert!(build_indices[i] - build_indices[i - 1] <= 1);
            }
        }
    }

    // ==================== Action Tests ====================

    #[test]
    fn test_run_selected() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        let run = app.run_selected();
        assert!(run.is_some());

        let run = run.unwrap();
        assert_eq!(run.script.name(), "build"); // First alphabetically
        assert!(run.args.is_none());
        assert!(app.should_quit());
    }

    #[test]
    fn test_run_numbered() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        let run = app.run_numbered(3);
        assert!(run.is_some());

        // Verify the run was successful
        assert!(run.unwrap().script.name().len() > 0);
        assert_eq!(app.selected_index(), 2);
        assert!(app.should_quit());
    }

    #[test]
    fn test_run_with_args() {
        let mut app = create_test_app();
        app.set_sort_mode(SortMode::Alpha);

        let run = app.run_with_args("--watch".to_string());
        assert!(run.is_some());

        let run = run.unwrap();
        assert_eq!(run.args, Some("--watch".to_string()));
        assert!(app.should_quit());
    }

    #[test]
    fn test_quit() {
        let mut app = create_test_app();
        assert!(!app.should_quit());

        app.quit();
        assert!(app.should_quit());
    }

    // ==================== Mode Tests ====================

    #[test]
    fn test_toggle_filter_mode() {
        let mut app = create_test_app();
        assert_eq!(app.mode(), &AppMode::Normal);

        app.toggle_filter_mode();
        assert!(matches!(app.mode(), &AppMode::Filter { .. }));

        app.toggle_filter_mode();
        assert_eq!(app.mode(), &AppMode::Normal);
    }

    #[test]
    fn test_toggle_multi_select() {
        let mut app = create_test_app();
        assert_eq!(app.mode(), &AppMode::Normal);

        app.toggle_multi_select();
        assert!(matches!(app.mode(), &AppMode::MultiSelect { .. }));

        app.toggle_multi_select();
        assert_eq!(app.mode(), &AppMode::Normal);
    }

    #[test]
    fn test_toggle_help() {
        let mut app = create_test_app();
        assert_eq!(app.mode(), &AppMode::Normal);

        app.toggle_help();
        assert_eq!(app.mode(), &AppMode::Help);

        app.toggle_help();
        assert_eq!(app.mode(), &AppMode::Normal);
    }

    #[test]
    fn test_enter_args_mode() {
        let mut app = create_test_app();
        app.enter_args_mode();

        assert!(matches!(
            app.mode(),
            &AppMode::Args {
                script_index: 0,
                ..
            }
        ));
    }

    #[test]
    fn test_multi_select_toggle_selection() {
        let mut app = create_test_app();
        app.toggle_multi_select();

        app.toggle_current_selection();
        let selected = app.multi_selected_indices().unwrap();
        assert!(selected.contains(&0));

        app.move_right();
        app.toggle_current_selection();
        let selected = app.multi_selected_indices().unwrap();
        assert!(selected.contains(&0));
        assert!(selected.contains(&1));

        // Toggle off
        app.toggle_current_selection();
        let selected = app.multi_selected_indices().unwrap();
        assert!(!selected.contains(&1));
    }

    // ==================== Column Tests ====================

    #[test]
    fn test_calculate_columns() {
        assert_eq!(calculate_columns(50), 1);
        assert_eq!(calculate_columns(59), 1);
        assert_eq!(calculate_columns(60), 2);
        assert_eq!(calculate_columns(89), 2);
        assert_eq!(calculate_columns(90), 3);
        assert_eq!(calculate_columns(119), 3);
        assert_eq!(calculate_columns(120), 4);
        assert_eq!(calculate_columns(159), 4);
        assert_eq!(calculate_columns(160), 5);
        assert_eq!(calculate_columns(200), 5);
    }

    #[test]
    fn test_update_columns() {
        let mut app = create_test_app();

        app.update_columns(100);
        assert_eq!(app.columns(), 3);

        app.update_columns(50);
        assert_eq!(app.columns(), 1);

        app.update_columns(160);
        assert_eq!(app.columns(), 5);
    }

    #[test]
    fn test_calculate_column_width() {
        assert_eq!(calculate_column_width(100, 3), 32);
        assert_eq!(calculate_column_width(80, 2), 38);
        assert_eq!(calculate_column_width(60, 1), 56);
        assert_eq!(calculate_column_width(50, 0), 50); // Edge case
    }

    // ==================== Edge Case Tests ====================

    #[test]
    fn test_empty_scripts() {
        let scripts = Scripts::new();
        let config = Config::default();
        let history = History::new();
        let app = App::new(
            scripts,
            config,
            history,
            "empty-project".to_string(),
            PathBuf::from("/test/empty"),
            Runner::Npm,
        );

        assert_eq!(app.visible_count(), 0);
        assert!(app.selected_script().is_none());
    }

    #[test]
    fn test_navigation_with_empty_scripts() {
        let scripts = Scripts::new();
        let config = Config::default();
        let history = History::new();
        let mut app = App::new(
            scripts,
            config,
            history,
            "empty-project".to_string(),
            PathBuf::from("/test/empty"),
            Runner::Npm,
        );

        // These should not panic
        app.move_up();
        app.move_down();
        app.move_left();
        app.move_right();
        app.move_to_first();
        app.move_to_last();

        assert_eq!(app.selected_index(), 0);
    }

    #[test]
    fn test_filter_no_matches() {
        let mut app = create_test_app();

        app.set_filter("nonexistent_script_xyz".to_string());
        assert_eq!(app.visible_count(), 0);
        assert!(app.selected_script().is_none());
    }

    #[test]
    fn test_navigation_last_row_partial() {
        // Test navigation when last row has fewer items than columns
        let mut scripts = Scripts::new();
        for i in 0..7 {
            scripts.add(Script::new(format!("script{}", i), format!("cmd{}", i)));
        }

        let config = Config::default();
        let history = History::new();
        let mut app = App::new(
            scripts,
            config,
            history,
            "test".to_string(),
            PathBuf::from("/test"),
            Runner::Npm,
        );

        app.update_columns(100); // 3 columns
        app.set_sort_mode(SortMode::Alpha);

        // Grid layout (7 items, 3 columns):
        // 0 1 2
        // 3 4 5
        // 6

        // Navigate to position 2 (top right)
        app.select_by_number(3);
        assert_eq!(app.selected_index(), 2);

        // Move down should go to 5
        app.move_down();
        assert_eq!(app.selected_index(), 5);

        // Move down again - should go to last item (6) since column 2 doesn't exist in row 2
        app.move_down();
        assert_eq!(app.selected_index(), 6);
    }
}