insmaller 0.6.2

Config-driven installer: describe install steps in TOML and run them from one binary
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
//! ratatui wizard TUI: a persistent screen with a progress gauge/breadcrumb
//! header, a per-page body, and on-screen [◄ Back] [Next ►] [Quit] buttons —
//! navigable by Tab/←/→ AND shortcut keys (Esc=back, Enter=next, q/Ctrl-C
//! quit). Drives a pure `WizardSession`. Plus an indicatif reporter for the
//! install phase.

use crossterm::{
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    ExecutableCommand,
};
use indicatif::{ProgressBar, ProgressStyle};
use insmaller_core::{Field, FieldType, Reporter, WizardSession};
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, Gauge, List, ListItem, ListState, Paragraph},
    Terminal,
};
use crate::theme::{gradient, Palette};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::io::{self, IsTerminal, Stdout};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Restores the terminal even on panic/early-return.
struct TermGuard;
impl Drop for TermGuard {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = io::stdout().execute(LeaveAlternateScreen);
    }
}

enum Widget {
    Multi {
        choices: Vec<insmaller_core::Choice>,
        on: Vec<bool>,
        groups: Vec<String>,
        collapsed: Vec<bool>,
        cur: usize,
    },
    Single {
        choices: Vec<insmaller_core::Choice>,
        sel: Option<usize>,
        groups: Vec<String>,
        collapsed: Vec<bool>,
        cur: usize,
    },
    Toggle { on: bool },
    Input { buf: String, secret: bool },
    /// A filesystem path. Editable as text; `Ctrl+B` opens an interactive
    /// directory/file browser (`picker = Some`).
    Path { buf: String, picker: Option<Picker> },
}

/// A visible line in a select's collapsible tree: a group `Header` (index into
/// the group list) or an `Item` (index into the choices vec).
#[derive(Clone, Copy, PartialEq, Debug)]
enum Row {
    Header(usize),
    Item(usize),
}

/// Distinct catalog groups in first-appearance order. Ungrouped choices are
/// excluded (they render at the top with no header).
fn group_list(choices: &[insmaller_core::Choice]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for c in choices {
        if let Some(g) = &c.group {
            if !out.iter().any(|x| x == g) {
                out.push(g.clone());
            }
        }
    }
    out
}

/// Choice label without the redundant `[group] ` prefix (the group is shown by
/// its header in the tree).
fn item_label(c: &insmaller_core::Choice) -> &str {
    if let Some(g) = &c.group {
        if let Some(rest) = c.label.strip_prefix(&format!("[{g}] ")) {
            return rest;
        }
    }
    &c.label
}

/// Checkbox glyph for a multiselect group header: all / some / none selected.
fn group_mark_multi(choices: &[insmaller_core::Choice], on: &[bool], group: &str) -> &'static str {
    let idxs: Vec<usize> = (0..choices.len())
        .filter(|&i| choices[i].group.as_deref() == Some(group))
        .collect();
    let sel = idxs.iter().filter(|&&i| on[i]).count();
    if sel == 0 {
        "[ ]"
    } else if sel == idxs.len() {
        "[x]"
    } else {
        "[~]"
    }
}

/// Visible rows for a select: ungrouped items first, then each group header
/// followed by its items unless the group is collapsed. `collapsed` aligns to
/// `groups`. With no groups this is just every item in order (a flat list).
fn visible_rows(
    choices: &[insmaller_core::Choice],
    groups: &[String],
    collapsed: &[bool],
) -> Vec<Row> {
    let mut rows: Vec<Row> = Vec::new();
    for (i, c) in choices.iter().enumerate() {
        if c.group.is_none() {
            rows.push(Row::Item(i));
        }
    }
    for (gi, g) in groups.iter().enumerate() {
        rows.push(Row::Header(gi));
        if !collapsed.get(gi).copied().unwrap_or(false) {
            for (i, c) in choices.iter().enumerate() {
                if c.group.as_deref() == Some(g.as_str()) {
                    rows.push(Row::Item(i));
                }
            }
        }
    }
    rows
}

/// Visible rows of a select widget (`None` for non-selects).
fn tree_rows_of(w: &Widget) -> Option<Vec<Row>> {
    match w {
        Widget::Multi { choices, groups, collapsed, .. }
        | Widget::Single { choices, groups, collapsed, .. } => {
            Some(visible_rows(choices, groups, collapsed))
        }
        _ => None,
    }
}

/// A select's tree cursor (0 otherwise).
fn cur_of(w: &Widget) -> usize {
    match w {
        Widget::Multi { cur, .. } | Widget::Single { cur, .. } => *cur,
        _ => 0,
    }
}

/// The row under the cursor of a select widget.
fn current_row(w: &Widget) -> Option<Row> {
    tree_rows_of(w).and_then(|rows| rows.get(cur_of(w)).copied())
}

/// True for a select that actually has group headers (so ←/→ drive the tree
/// rather than field-focus navigation).
fn widget_has_groups(w: &Widget) -> bool {
    matches!(
        w,
        Widget::Multi { groups, .. } | Widget::Single { groups, .. } if !groups.is_empty()
    )
}

/// Clamp the tree cursor to the current visible-row count (after a collapse
/// shrinks the list).
fn clamp_cur(w: &mut Widget) {
    let max = match tree_rows_of(w) {
        Some(rows) => rows.len().saturating_sub(1),
        None => return,
    };
    if let Widget::Multi { cur, .. } | Widget::Single { cur, .. } = w {
        *cur = (*cur).min(max);
    }
}

/// Move the cursor onto the header of `item`'s group (← from an item).
fn cursor_to_header_of(w: &mut Widget, item: usize) {
    let rows = match tree_rows_of(w) {
        Some(r) => r,
        None => return,
    };
    let gi = match &*w {
        Widget::Multi { choices, groups, .. } | Widget::Single { choices, groups, .. } => choices
            .get(item)
            .and_then(|c| c.group.as_ref())
            .and_then(|g| groups.iter().position(|x| x == g)),
        _ => None,
    };
    let Some(gi) = gi else { return };
    let Some(pos) = rows.iter().position(|r| *r == Row::Header(gi)) else {
        return;
    };
    if let Widget::Multi { cur, .. } | Widget::Single { cur, .. } = w {
        *cur = pos;
    }
}

/// One row in the file browser.
struct Entry {
    name: String,
    is_dir: bool,
}

/// Interactive directory/file browser overlaid on a `Path` field.
struct Picker {
    cwd: PathBuf,
    entries: Vec<Entry>,
    /// false ⇒ `cwd` could not be read (permissions, gone). `entries` then
    /// holds only `..`; the modal shows the state so the user isn't left
    /// staring at a silently-empty list.
    readable: bool,
    cursor: usize,
}

/// Available drive roots on Windows (`C:`, `D:`, …) from the `GetLogicalDrives`
/// bitmask — dependency-free and, crucially, it never touches the filesystem.
/// Stat-probing each letter (the obvious approach) would block for seconds on a
/// disconnected network-mapped drive; the bitmask just reports which letters
/// are in use. Only the drive-selector pseudo-level calls this.
#[cfg(windows)]
fn windows_drives() -> Vec<Entry> {
    #[link(name = "kernel32")]
    extern "system" {
        fn GetLogicalDrives() -> u32;
    }
    let mask = unsafe { GetLogicalDrives() };
    ('A'..='Z')
        .enumerate()
        .filter(|(i, _)| mask & (1 << i) != 0)
        .map(|(_, d)| Entry { name: format!("{d}:"), is_dir: true })
        .collect()
}

/// Directory listing for the browser: `.` (pick this folder) first, then `..`
/// (parent, unless at a root), then directories before files, each group
/// case-insensitively sorted. Returns `(entries, readable)` — `readable` is
/// false when the dir can't be opened, so callers can distinguish "empty" from
/// "denied". On Windows the empty path is the drive selector (lists drive
/// roots), and a drive root still offers `..` (up to that selector). Pure given
/// the filesystem — unit-testable against a tempdir.
fn list_dir(p: &Path) -> (Vec<Entry>, bool) {
    // Windows drive selector: empty path ⇒ list the drive roots, nothing else.
    #[cfg(windows)]
    if p.as_os_str().is_empty() {
        return (windows_drives(), true);
    }
    let mut entries: Vec<Entry> = Vec::new();
    // `.` always selects the current directory as the value.
    entries.push(Entry { name: ".".into(), is_dir: true });
    // `..` ascends to the parent — or, at a Windows drive root (no parent), up
    // to the drive selector. On Unix the single `/` root has no `..`.
    let has_parent = p.parent().is_some();
    if has_parent || cfg!(windows) {
        entries.push(Entry { name: "..".into(), is_dir: true });
    }
    match std::fs::read_dir(p) {
        Ok(rd) => {
            let mut items: Vec<Entry> = rd
                .flatten()
                .map(|d| Entry {
                    name: d.file_name().to_string_lossy().into_owned(),
                    is_dir: d.file_type().map(|t| t.is_dir()).unwrap_or(false),
                })
                .collect();
            items.sort_by(|a, b| {
                b.is_dir
                    .cmp(&a.is_dir)
                    .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
            });
            entries.extend(items);
            (entries, true)
        }
        Err(_) => (entries, false),
    }
}

impl Picker {
    /// Seed the browser at `buf`'s directory (or its parent if `buf` names a
    /// file), falling back to the home dir.
    fn open(buf: &str) -> Picker {
        let mut p = Picker {
            cwd: PathBuf::new(),
            entries: Vec::new(),
            readable: true,
            cursor: 0,
        };
        p.set_dir(Self::seed_dir(buf));
        p
    }

    /// Move to `dir`: relist, reset the cursor, record readability.
    fn set_dir(&mut self, dir: PathBuf) {
        let (entries, readable) = list_dir(&dir);
        self.cwd = dir;
        self.entries = entries;
        self.readable = readable;
        self.cursor = 0;
    }

    fn seed_dir(buf: &str) -> PathBuf {
        let home = || dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
        if buf.is_empty() {
            return home();
        }
        let p = PathBuf::from(buf);
        if p.is_dir() {
            return p;
        }
        match p.parent() {
            Some(parent) if parent.is_dir() => parent.to_path_buf(),
            _ => home(),
        }
    }

    fn up(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    fn down(&mut self) {
        if self.cursor + 1 < self.entries.len() {
            self.cursor += 1;
        }
    }

    /// At the Windows drive selector (the empty-path pseudo-level). On Unix the
    /// cwd is never empty, so this is always false there. One predicate owns the
    /// sentinel so it can't be re-spelled (or leak) inconsistently.
    fn at_drive_selector(&self) -> bool {
        self.cwd.as_os_str().is_empty()
    }

    fn ascend(&mut self) {
        if let Some(parent) = self.cwd.parent().map(Path::to_path_buf) {
            self.set_dir(parent);
        } else {
            // No parent: a Windows drive root goes up to the drive selector;
            // the Unix `/` root (and the selector itself) stay put.
            self.goto_drives();
        }
    }

    /// Jump straight to the Windows drive selector from anywhere (`d`
    /// shortcut). No-op on Unix, and when already at the selector.
    fn goto_drives(&mut self) {
        if cfg!(windows) && !self.at_drive_selector() {
            self.set_dir(PathBuf::new());
        }
    }

    /// Enter/→ on the cursor: descend into a directory (or `..`) and return
    /// `None`; on a file, return its full path (caller closes the picker).
    fn activate(&mut self) -> Option<String> {
        let entry = self.entries.get(self.cursor)?;
        if entry.name == "." {
            return self.select_cwd();
        }
        if entry.name == ".." {
            self.ascend();
            return None;
        }
        // From the drive selector (empty cwd) a `C:` entry must become `C:\`,
        // not the relative `C:`; elsewhere a plain join is the child path.
        let target = if self.at_drive_selector() {
            PathBuf::from(format!("{}\\", entry.name))
        } else {
            self.cwd.join(&entry.name)
        };
        if entry.is_dir {
            self.set_dir(target);
            None
        } else {
            Some(target.to_string_lossy().into_owned())
        }
    }

    /// The current directory itself, as the selected value — `None` at the
    /// drive selector, which has no folder to pick (guards `s`/`.` from
    /// silently returning the empty sentinel path).
    fn select_cwd(&self) -> Option<String> {
        if self.at_drive_selector() {
            None
        } else {
            Some(self.cwd.to_string_lossy().into_owned())
        }
    }
}

/// Per-group initial collapse policy: a baseline plus name overrides.
/// `expanded` wins over `collapsed`, both win over the baseline.
#[derive(Default, Clone)]
pub struct GroupDefaults {
    pub collapsed_default: bool,
    pub collapsed: Vec<String>,
    pub expanded: Vec<String>,
}

impl GroupDefaults {
    fn is_collapsed(&self, group: &str) -> bool {
        if self.expanded.iter().any(|g| g == group) {
            false
        } else if self.collapsed.iter().any(|g| g == group) {
            true
        } else {
            self.collapsed_default
        }
    }
    /// Initial collapse per group: a prior user choice in `cache` (keyed by
    /// field id + group) wins, else the configured default. Lets expand/collapse
    /// survive leaving and re-entering a wizard page.
    fn for_groups(&self, field_id: &str, groups: &[String], cache: &HashMap<String, bool>) -> Vec<bool> {
        groups
            .iter()
            .map(|g| {
                cache
                    .get(&collapse_key(field_id, g))
                    .copied()
                    .unwrap_or_else(|| self.is_collapsed(g))
            })
            .collect()
    }
}

/// Cache key for a group's collapse state (NUL separates id from group so they
/// can't collide).
fn collapse_key(field_id: &str, group: &str) -> String {
    format!("{field_id}\u{0}{group}")
}

fn init_widget(
    f: &Field,
    s: &WizardSession,
    gd: &GroupDefaults,
    collapse: &HashMap<String, bool>,
) -> Widget {
    let prior = s.answer_for(&f.id).cloned();
    match f.field_type {
        FieldType::Multiselect => {
            let choices = s.choices(f);
            let on = choices
                .iter()
                .map(|c| match &prior {
                    Some(Value::Array(a)) => a.iter().any(|v| v.as_str() == Some(&c.value)),
                    _ => c.default,
                })
                .collect();
            let groups = group_list(&choices);
            let collapsed = gd.for_groups(&f.id, &groups, collapse);
            Widget::Multi { choices, on, groups, collapsed, cur: 0 }
        }
        FieldType::SingleSelect => {
            let choices = s.choices(f);
            let sel = match &prior {
                Some(Value::String(v)) => choices.iter().position(|c| &c.value == v),
                _ => None,
            };
            let groups = group_list(&choices);
            let collapsed = gd.for_groups(&f.id, &groups, collapse);
            Widget::Single { choices, sel, groups, collapsed, cur: 0 }
        }
        FieldType::Toggle => Widget::Toggle {
            on: matches!(prior, Some(Value::Bool(true))),
        },
        FieldType::Path => Widget::Path {
            buf: match prior {
                Some(Value::String(s)) => s,
                _ => f.default.clone().unwrap_or_default(),
            },
            picker: None,
        },
        _ => Widget::Input {
            buf: match prior {
                Some(Value::String(s)) => s,
                _ => f.default.clone().unwrap_or_default(),
            },
            secret: f.field_type == FieldType::Secret,
        },
    }
}

fn widget_value(w: &Widget) -> Value {
    match w {
        Widget::Multi { choices, on, .. } => Value::Array(
            choices
                .iter()
                .zip(on)
                .filter(|(_, &o)| o)
                .map(|(c, _)| Value::String(c.value.clone()))
                .collect(),
        ),
        Widget::Single { choices, sel, .. } => Value::String(
            sel.and_then(|i| choices.get(i)).map(|c| c.value.clone()).unwrap_or_default(),
        ),
        Widget::Toggle { on } => Value::Bool(*on),
        Widget::Input { buf, .. } => Value::String(buf.clone()),
        Widget::Path { buf, .. } => Value::String(buf.clone()),
    }
}

/// Vertical (↑/↓) navigation. Within a select's choices while there's room to
/// move; otherwise fall through to field navigation. `len` is the focused
/// select's choice count (0 for Input/Toggle/edge-less widgets, which always
/// move focus). Returns `(new_cur, new_focus)`; `new_cur` is only meaningful
/// for selects. Focus is clamped to `0..=n+1` (fields, then Back, then Next).
fn vert_nav(cur: usize, len: usize, down: bool, focus: usize, n: usize) -> (usize, usize) {
    if down {
        if len > 0 && cur + 1 < len {
            (cur + 1, focus)
        } else {
            (cur, (focus + 1).min(n + 1))
        }
    } else if len > 0 && cur > 0 {
        (cur - 1, focus)
    } else {
        (cur, focus.saturating_sub(1))
    }
}

/// A rectangle centered in `area`, `percent_x` × `percent_y` of its size.
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let v = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(v[1])[1]
}

/// A titled panel. Under a colored theme it gets rounded corners and a border
/// tinted by focus (bright `border_focus` when active, dim `border` idle —
/// the focus glow). Under mono/`NO_COLOR` it stays the plain square box, so
/// nothing changes there.
fn panel<'a>(title: impl Into<Line<'a>>, focused: bool, pal: &Palette) -> Block<'a> {
    let mut b = Block::default().borders(Borders::ALL).title(title);
    if pal.colored() {
        let bc = if focused { pal.border_focus } else { pal.border };
        b = b
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(bc));
    }
    b
}

/// Run the wizard interactively. Returns true if completed, false if quit.
pub fn run_wizard_tui(
    session: &mut WizardSession,
    pal: Palette,
    gd: &GroupDefaults,
) -> anyhow::Result<bool> {
    enable_raw_mode()?;
    io::stdout().execute(EnterAlternateScreen)?;
    let _g = TermGuard;
    let mut term: Terminal<CrosstermBackend<Stdout>> =
        Terminal::new(CrosstermBackend::new(io::stdout()))?;

    // Group collapse state, keyed by field id + group, persisted across page
    // re-entries (the per-page widgets are rebuilt each time).
    let mut collapse: HashMap<String, bool> = HashMap::new();

    // Animate only on a colored interactive terminal: under NO_COLOR/mono or
    // when piped/redirected we keep the blocking, zero-wakeup event loop.
    let animate = pal.colored() && io::stdout().is_terminal();
    let mut frame: u64 = 0;
    // Header gradient cached by width: accent→accent2 is invariant for the
    // session, only the animation `phase` rotates, so we rebuild the Vec only
    // on a resize, not every frame.
    let mut grad_cache: (usize, Vec<ratatui::style::Color>) = (0, Vec::new());

    while !session.is_done() {
        let fields: Vec<Field> = session.fields();
        let mut widgets: Vec<Widget> =
            fields.iter().map(|f| init_widget(f, session, gd, &collapse)).collect();
        // focus targets: 0..fields = field i; fields = Back; fields+1 = Next
        let n = fields.len();
        let mut focus = 0usize;
        let mut err: Option<String> = None;
        let (title, desc) = session
            .current()
            .map(|p| (p.title.clone(), p.description.clone()))
            .unwrap_or_default();
        let (step, total) = session.progress();

        loop {
            term.draw(|fr| {
                let rows = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints([
                        Constraint::Length(4),
                        Constraint::Min(3),
                        Constraint::Length(3),
                    ])
                    .split(fr.area());

                let ratio = (step as f64 / total as f64).clamp(0.0, 1.0);
                let htitle = format!(" insmaller setup — {title}  (step {step}/{total}) ");
                if pal.colored() {
                    // Custom gradient progress bar: accent→accent2 flowing left
                    // to right, with the filled portion lit and the remainder
                    // dimmed. `frame` rotates the gradient for a subtle sheen.
                    let block = panel(htitle, false, &pal);
                    let inner = block.inner(rows[0]);
                    fr.render_widget(block, rows[0]);
                    let w = inner.width.max(1) as usize;
                    let filled = (ratio * w as f64).round() as usize;
                    if grad_cache.0 != w {
                        grad_cache = (w, gradient(pal.accent, pal.accent2, w));
                    }
                    let cols = &grad_cache.1;
                    let phase = (frame as usize) % w;
                    let bar: Vec<Span> = (0..w)
                        .map(|i| {
                            let col = cols[(i + phase) % w];
                            if i < filled {
                                Span::styled("", Style::default().fg(col))
                            } else {
                                Span::styled("", Style::default().fg(pal.border))
                            }
                        })
                        .collect();
                    let lines = vec![
                        Line::from(bar),
                        Line::from(Span::styled(desc.clone(), Style::default().fg(pal.muted))),
                    ];
                    fr.render_widget(Paragraph::new(lines), inner);
                } else {
                    let g = Gauge::default()
                        .block(Block::default().borders(Borders::ALL).title(htitle))
                        .gauge_style(Style::default().fg(pal.accent))
                        .ratio(ratio)
                        .label(desc.clone());
                    fr.render_widget(g, rows[0]);
                }

                let mut items: Vec<ListItem> = Vec::new();
                for (i, f) in fields.iter().enumerate() {
                    let focused = focus == i;
                    let head = format!(
                        "{} {}",
                        if focused { "" } else { " " },
                        f.prompt.as_deref().unwrap_or(&f.id)
                    );
                    items.push(ListItem::new(Span::styled(
                        head,
                        Style::default().add_modifier(Modifier::BOLD),
                    )));
                    match &widgets[i] {
                        Widget::Multi { choices, on, groups, collapsed, cur } => {
                            for (pos, row) in
                                visible_rows(choices, groups, collapsed).iter().enumerate()
                            {
                                let p = if focused && *cur == pos { ">" } else { " " };
                                match row {
                                    Row::Header(gi) => {
                                        let g = &groups[*gi];
                                        let tri = if collapsed[*gi] { "" } else { "" };
                                        let mark = group_mark_multi(choices, on, g);
                                        items.push(ListItem::new(format!(
                                            "   {p}{tri} {mark} {g}"
                                        )));
                                    }
                                    Row::Item(i) => {
                                        let mark = if on[*i] { "[x]" } else { "[ ]" };
                                        let indent =
                                            if choices[*i].group.is_some() { "     " } else { "   " };
                                        items.push(ListItem::new(format!(
                                            "{indent}{p}{mark} {}",
                                            item_label(&choices[*i])
                                        )));
                                    }
                                }
                            }
                        }
                        Widget::Single { choices, sel, groups, collapsed, cur } => {
                            for (pos, row) in
                                visible_rows(choices, groups, collapsed).iter().enumerate()
                            {
                                let p = if focused && *cur == pos { ">" } else { " " };
                                match row {
                                    Row::Header(gi) => {
                                        // No radio mark on a single-select header
                                        // — a group isn't itself selectable.
                                        let g = &groups[*gi];
                                        let tri = if collapsed[*gi] { "" } else { "" };
                                        items.push(ListItem::new(format!("   {p}{tri} {g}")));
                                    }
                                    Row::Item(i) => {
                                        let mark = if *sel == Some(*i) { "(o)" } else { "( )" };
                                        let indent =
                                            if choices[*i].group.is_some() { "     " } else { "   " };
                                        items.push(ListItem::new(format!(
                                            "{indent}{p}{mark} {}",
                                            item_label(&choices[*i])
                                        )));
                                    }
                                }
                            }
                        }
                        Widget::Toggle { on } => items.push(ListItem::new(format!(
                            "   [{}] (space toggles)",
                            if *on { "x" } else { " " }
                        ))),
                        Widget::Input { buf, secret } => {
                            let shown = if *secret {
                                "*".repeat(buf.chars().count())
                            } else {
                                buf.clone()
                            };
                            items.push(ListItem::new(format!(
                                "   {}{}",
                                shown,
                                if focused { "_" } else { "" }
                            )));
                        }
                        Widget::Path { buf, .. } => {
                            items.push(ListItem::new(format!(
                                "   {}{}",
                                buf,
                                if focused { "_   [Ctrl+B browse]" } else { "" }
                            )));
                        }
                    }
                }
                let body = List::new(items).block(panel(" fields ", focus < n, &pal));
                fr.render_widget(body, rows[1]);

                // Path browser overlay (captures all keys while open).
                if let Some(Widget::Path { picker: Some(p), .. }) = widgets.get(focus) {
                    let area = centered_rect(70, 70, fr.area());
                    let rows_p: Vec<ListItem> = p
                        .entries
                        .iter()
                        .map(|e| {
                            let name = match e.name.as_str() {
                                "." => ".    (select this folder)".to_string(),
                                ".." => "..   (parent folder)".to_string(),
                                _ if e.is_dir => format!("{}/", e.name),
                                _ => e.name.clone(),
                            };
                            ListItem::new(name)
                        })
                        .collect();
                    let state = if p.readable { "" } else { "  [unreadable]" };
                    let loc = if p.at_drive_selector() {
                        "Drives".to_string()
                    } else {
                        p.cwd.display().to_string()
                    };
                    let drives_hint = if cfg!(windows) { " · d drives" } else { "" };
                    let title = format!(
                        " {loc}{state}  (↑↓ move · ↵ open/select · ← up{drives_hint} · Esc cancel) "
                    );
                    let list = List::new(rows_p)
                        .block(panel(title, true, &pal))
                        .highlight_style(
                            Style::default()
                                .fg(pal.accent_fg)
                                .bg(pal.accent)
                                .add_modifier(Modifier::BOLD),
                        )
                        .highlight_symbol("> ");
                    let mut st = ListState::default();
                    st.select(Some(p.cursor));
                    // Drop shadow: a dark rect offset +1/+1, drawn before Clear
                    // so the L-shaped sliver outside `area` stays shadowed.
                    if pal.colored() {
                        let fa = fr.area();
                        let sx = area.x + 1;
                        let sy = area.y + 1;
                        let shadow = Rect {
                            x: sx,
                            y: sy,
                            width: area.width.min(fa.width.saturating_sub(sx)),
                            height: area.height.min(fa.height.saturating_sub(sy)),
                        };
                        fr.render_widget(
                            Block::default().style(Style::default().bg(pal.shadow)),
                            shadow,
                        );
                    }
                    fr.render_widget(Clear, area);
                    fr.render_stateful_widget(list, area, &mut st);
                }

                let btn = |label: &str, idx: usize, enabled: bool| {
                    let st = if !enabled {
                        Style::default().fg(pal.muted)
                    } else if focus == idx {
                        Style::default()
                            .fg(pal.accent_fg)
                            .bg(pal.accent)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default().fg(pal.accent)
                    };
                    Span::styled(format!(" {label} "), st)
                };
                let foot = Line::from(vec![
                    btn("◄ Back", n, session.can_back()),
                    Span::raw("  "),
                    btn("Next ►", n + 1, true),
                    Span::raw("   "),
                    Span::styled(
                        err.clone().unwrap_or_else(|| {
                            "Tab focus · ↑↓ move · ←→ expand/collapse · Space toggle · Enter next · Esc back · q quit".into()
                        }),
                        Style::default().fg(if err.is_some() { pal.error } else { pal.muted }),
                    ),
                ]);
                fr.render_widget(
                    Paragraph::new(foot).block(panel("", focus >= n, &pal)),
                    rows[2],
                );
            })?;

            // Animated themes poll on a tick so the gradient sheen advances
            // while idle; otherwise block (no idle wakeups under CI/piped/mono).
            if animate && !event::poll(Duration::from_millis(80))? {
                frame = frame.wrapping_add(1);
                continue;
            }
            let Event::Key(k) = event::read()? else { continue };
            if k.kind != KeyEventKind::Press {
                continue;
            }

            // Ctrl+C always quits, even with the browser open.
            if k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL) {
                return Ok(false);
            }

            // An open path browser owns every key until it closes.
            if matches!(widgets.get(focus), Some(Widget::Path { picker: Some(_), .. })) {
                if let Some(Widget::Path { buf, picker }) = widgets.get_mut(focus) {
                    let p = picker.as_mut().expect("picker is Some");
                    match k.code {
                        KeyCode::Up => p.up(),
                        KeyCode::Down => p.down(),
                        KeyCode::Left | KeyCode::Backspace => p.ascend(),
                        KeyCode::Enter | KeyCode::Right => {
                            if let Some(path) = p.activate() {
                                *buf = path;
                                *picker = None;
                            }
                        }
                        KeyCode::Char('s') => {
                            // No-op at the drive selector (no folder to take).
                            if let Some(path) = p.select_cwd() {
                                *buf = path;
                                *picker = None;
                            }
                        }
                        KeyCode::Char('d') => p.goto_drives(),
                        KeyCode::Esc => *picker = None,
                        _ => {}
                    }
                }
                continue;
            }

            // Ctrl+B opens the browser on a focused path field.
            if k.code == KeyCode::Char('b') && k.modifiers.contains(KeyModifiers::CONTROL) {
                if let Some(Widget::Path { buf, picker }) = widgets.get_mut(focus) {
                    *picker = Some(Picker::open(buf));
                }
                continue;
            }

            let editing = matches!(
                widgets.get(focus),
                Some(Widget::Input { .. }) | Some(Widget::Path { .. })
            );
            // quit
            if k.code == KeyCode::Char('q') && !editing {
                return Ok(false);
            }

            let commit = |ws: &[Widget], fs: &[Field]| -> Map<String, Value> {
                let mut m = Map::new();
                for (w, f) in ws.iter().zip(fs) {
                    m.insert(f.id.clone(), widget_value(w));
                }
                m
            };

            match k.code {
                // On a grouped select, →/← drive expand/collapse instead of
                // field focus (focus still moves via Tab / ↑↓).
                KeyCode::Right if focus < n && widget_has_groups(&widgets[focus]) => {
                    if let Some(Row::Header(gi)) = current_row(&widgets[focus]) {
                        if let Widget::Multi { collapsed, .. }
                        | Widget::Single { collapsed, .. } = &mut widgets[focus]
                        {
                            collapsed[gi] = false;
                        }
                    }
                }
                KeyCode::Left if focus < n && widget_has_groups(&widgets[focus]) => {
                    match current_row(&widgets[focus]) {
                        Some(Row::Header(gi)) => {
                            if let Widget::Multi { collapsed, .. }
                            | Widget::Single { collapsed, .. } = &mut widgets[focus]
                            {
                                collapsed[gi] = true;
                            }
                            clamp_cur(&mut widgets[focus]);
                        }
                        Some(Row::Item(i)) => cursor_to_header_of(&mut widgets[focus], i),
                        None => {}
                    }
                }
                KeyCode::Tab | KeyCode::Right if !editing => focus = (focus + 1) % (n + 2),
                KeyCode::BackTab | KeyCode::Left if !editing => {
                    focus = (focus + n + 1) % (n + 2)
                }
                KeyCode::Esc => {
                    let m = commit(&widgets, &fields);
                    session.store(m);
                    if session.back() {
                        break;
                    }
                }
                KeyCode::Up | KeyCode::Down if focus < n => {
                    let down = k.code == KeyCode::Down;
                    // For selects, the cursor ranges over visible tree rows
                    // (headers + items), not the raw choices.
                    let len = tree_rows_of(&widgets[focus]).map_or(0, |r| r.len());
                    let cur = cur_of(&widgets[focus]);
                    let (new_cur, new_focus) = vert_nav(cur, len, down, focus, n);
                    if let Widget::Multi { cur, .. } | Widget::Single { cur, .. } =
                        &mut widgets[focus]
                    {
                        *cur = new_cur;
                    }
                    focus = new_focus;
                }
                KeyCode::Char(' ') if focus < n => {
                    let row = current_row(&widgets[focus]);
                    match &mut widgets[focus] {
                        Widget::Multi { on, collapsed, .. } => match row {
                            Some(Row::Item(i)) => on[i] = !on[i],
                            Some(Row::Header(gi)) => collapsed[gi] = !collapsed[gi],
                            None => {}
                        },
                        Widget::Single { sel, collapsed, .. } => match row {
                            Some(Row::Item(i)) => *sel = Some(i),
                            Some(Row::Header(gi)) => collapsed[gi] = !collapsed[gi],
                            None => {}
                        },
                        Widget::Toggle { on } => *on = !*on,
                        Widget::Input { buf, .. } | Widget::Path { buf, .. } => buf.push(' '),
                    }
                    clamp_cur(&mut widgets[focus]);
                }
                KeyCode::Char(ch) if editing => {
                    if let Widget::Input { buf, .. } | Widget::Path { buf, .. } =
                        &mut widgets[focus]
                    {
                        buf.push(ch);
                    }
                }
                KeyCode::Backspace if editing => {
                    if let Widget::Input { buf, .. } | Widget::Path { buf, .. } =
                        &mut widgets[focus]
                    {
                        buf.pop();
                    }
                }
                KeyCode::Enter => {
                    if focus == n {
                        // Back button
                        let m = commit(&widgets, &fields);
                        session.store(m);
                        if session.back() {
                            break;
                        }
                    } else {
                        // Next (or any field) → submit page
                        let m = commit(&widgets, &fields);
                        match session.submit(m) {
                            Ok(()) => break,
                            Err(e) => err = Some(format!("{e}")),
                        }
                    }
                }
                _ => {}
            }
        }
        // Persist this page's group collapse state so it survives Back/Next.
        for (w, f) in widgets.iter().zip(&fields) {
            if let Widget::Multi { groups, collapsed, .. }
            | Widget::Single { groups, collapsed, .. } = w
            {
                for (g, c) in groups.iter().zip(collapsed) {
                    collapse.insert(collapse_key(&f.id, g), *c);
                }
            }
        }
    }
    Ok(true)
}

/// indicatif spinner reporter for the install phase.
pub struct BarReporter {
    bar: ProgressBar,
}
impl BarReporter {
    // indicatif's template color is a static token (no arbitrary RGB), so the
    // spinner only honors the colored/mono distinction, not custom hex.
    pub fn new(pal: Palette) -> Self {
        let bar = ProgressBar::new_spinner();
        let tmpl = if pal.colored() {
            "{spinner:.cyan} {wide_msg}"
        } else {
            "{spinner} {wide_msg}"
        };
        bar.set_style(
            ProgressStyle::with_template(tmpl)
                .unwrap_or_else(|_| ProgressStyle::default_spinner()),
        );
        bar.enable_steady_tick(std::time::Duration::from_millis(120));
        Self { bar }
    }
    pub fn finish(&self) {
        self.bar.finish_and_clear();
    }
}
impl Reporter for BarReporter {
    fn step_start(&self, key: &str, step_type: &str) {
        self.bar.set_message(format!("{key} · {step_type}"));
    }
    fn step_end(&self, key: &str, step_type: &str, ok: bool) {
        if !ok {
            self.bar
                .println(format!("{key} · {step_type}"));
        }
    }
    fn log(&self, msg: &str) {
        self.bar.println(msg);
    }
}

#[cfg(test)]
mod tests {
    use super::{
        group_list, group_mark_multi, item_label, list_dir, vert_nav, visible_rows, GroupDefaults,
        Picker, Row,
    };
    use insmaller_core::Choice;

    fn ch(value: &str, group: Option<&str>) -> Choice {
        Choice {
            value: value.into(),
            label: value.into(),
            default: false,
            group: group.map(str::to_string),
        }
    }

    // 2 fields (n=2): focus 0,1 = fields; 2 = Back; 3 = Next.
    #[test]
    fn down_within_select_then_to_next_field() {
        // field 0 is a 3-choice select at cursor 0
        assert_eq!(vert_nav(0, 3, true, 0, 2), (1, 0));
        assert_eq!(vert_nav(1, 3, true, 0, 2), (2, 0));
        // at the last choice, Down advances focus to field 1
        assert_eq!(vert_nav(2, 3, true, 0, 2), (2, 1));
    }

    #[test]
    fn up_within_select_then_to_prev_field() {
        // field 1 select at cursor 2 → cursor 1 → cursor 0 → prev field
        assert_eq!(vert_nav(2, 3, false, 1, 2), (1, 1));
        assert_eq!(vert_nav(1, 3, false, 1, 2), (0, 1));
        assert_eq!(vert_nav(0, 3, false, 1, 2), (0, 0));
    }

    #[test]
    fn fieldless_widget_moves_focus_both_ways() {
        // len 0 (Input/Toggle): arrows move focus immediately
        assert_eq!(vert_nav(0, 0, true, 0, 2), (0, 1));
        assert_eq!(vert_nav(0, 0, false, 1, 2), (0, 0));
    }

    #[test]
    fn focus_clamps_at_edges() {
        // Down past the last field lands on Back (n) then Next (n+1), no further
        assert_eq!(vert_nav(0, 0, true, 2, 2), (0, 3));
        assert_eq!(vert_nav(0, 0, true, 3, 2), (0, 3));
        // Up from field 0 stays at 0
        assert_eq!(vert_nav(0, 0, false, 0, 2), (0, 0));
    }

    #[test]
    fn list_dir_dot_dotdot_then_dirs_before_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("zdir")).unwrap();
        std::fs::write(dir.path().join("afile.txt"), b"x").unwrap();
        let (entries, readable) = list_dir(dir.path());
        assert!(readable);
        // "." (select this folder) first, then ".." (parent)
        assert_eq!(entries[0].name, ".");
        assert_eq!(entries[1].name, "..");
        // directory sorts before the file despite "zdir" > "afile"
        assert_eq!(entries[2].name, "zdir");
        assert!(entries[2].is_dir);
        assert_eq!(entries[3].name, "afile.txt");
        assert!(!entries[3].is_dir);
    }

    #[test]
    fn list_dir_reports_unreadable() {
        // A path that is not a directory cannot be listed → readable=false,
        // and only the synthetic "." and ".." entries are present.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("not_a_dir.txt");
        std::fs::write(&file, b"x").unwrap();
        let (entries, readable) = list_dir(&file);
        assert!(!readable);
        assert_eq!(
            entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
            vec![".", ".."]
        );
    }

    #[test]
    fn picker_descends_ascends_and_selects_file() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("sub");
        std::fs::create_dir(&sub).unwrap();
        std::fs::write(sub.join("f.txt"), b"x").unwrap();

        let mut p = Picker::open(&dir.path().to_string_lossy());
        // [., .., sub]; cursor 0 is "." which selects this very folder
        assert_eq!(p.entries[p.cursor].name, ".");
        assert_eq!(
            p.activate().map(std::path::PathBuf::from),
            Some(dir.path().to_path_buf()),
            "'.' selects the current folder"
        );

        // move onto "sub" (skip ., ..) and descend
        p.down();
        p.down();
        assert_eq!(p.entries[p.cursor].name, "sub");
        assert_eq!(p.activate(), None);
        assert_eq!(p.cwd, sub);

        // now [., .., f.txt]; selecting the file returns its full path
        p.down();
        p.down();
        assert_eq!(p.entries[p.cursor].name, "f.txt");
        let got = p.activate().expect("file selection returns a path");
        assert_eq!(std::path::PathBuf::from(got), sub.join("f.txt"));

        // activating ".." ascends back to the parent
        let mut q = Picker::open(&sub.to_string_lossy());
        q.down(); // onto ".."
        assert_eq!(q.entries[q.cursor].name, "..");
        assert_eq!(q.activate(), None);
        assert_eq!(q.cwd, dir.path());
    }

    #[cfg(windows)]
    #[test]
    fn drive_root_offers_dotdot_to_selector() {
        // At a drive root, `..` is present and ascending lands on the empty
        // drive-selector path (it can't escape past it).
        let (entries, readable) = list_dir(std::path::Path::new("C:\\"));
        assert!(readable);
        assert!(entries.iter().any(|e| e.name == ".."));

        let mut p = Picker::open("C:\\");
        assert_eq!(p.cwd, std::path::PathBuf::from("C:\\"));
        p.ascend();
        assert!(p.cwd.as_os_str().is_empty(), "ascends to the drive selector");
        // Already at the selector: a further ascend is a no-op.
        p.ascend();
        assert!(p.cwd.as_os_str().is_empty());
    }

    #[cfg(windows)]
    #[test]
    fn selector_lists_drives_and_activate_descends() {
        let (drives, readable) = list_dir(&std::path::PathBuf::new());
        assert!(readable);
        assert!(!drives.is_empty(), "at least the system drive is present");
        assert!(drives.iter().all(|e| e.is_dir));

        let mut p = Picker::open("C:\\");
        p.set_dir(std::path::PathBuf::new()); // jump to the selector
        // Activate the first drive → cwd becomes its root with a trailing sep.
        assert_eq!(p.activate(), None);
        assert!(!p.cwd.as_os_str().is_empty());
        let s = p.cwd.to_string_lossy();
        assert!(s.ends_with('\\'), "drive root keeps a trailing separator: {s}");
    }

    #[cfg(windows)]
    #[test]
    fn d_shortcut_jumps_to_selector_from_any_depth() {
        // From a normal directory, `d` jumps straight to the drive selector
        // without walking parents; on the selector it's a no-op.
        let dir = tempfile::tempdir().unwrap();
        let mut p = Picker::open(&dir.path().to_string_lossy());
        assert!(!p.cwd.as_os_str().is_empty());
        p.goto_drives();
        assert!(p.cwd.as_os_str().is_empty(), "d jumps to the drive selector");
        p.goto_drives();
        assert!(p.cwd.as_os_str().is_empty(), "no-op once already there");
    }

    #[cfg(windows)]
    #[test]
    fn select_at_drive_selector_yields_no_value() {
        // 's' / '.' must not return the empty sentinel as a chosen path.
        let mut p = Picker::open("C:\\");
        p.goto_drives();
        assert!(p.at_drive_selector());
        assert_eq!(p.select_cwd(), None, "no folder to take at the drive list");
    }

    #[test]
    fn group_list_first_appearance_order_excludes_ungrouped() {
        let choices = vec![
            ch("a", None),
            ch("bun", Some("runtime")),
            ch("node", Some("runtime")),
            ch("claude", Some("ai")),
        ];
        assert_eq!(group_list(&choices), vec!["runtime".to_string(), "ai".to_string()]);
    }

    #[test]
    fn visible_rows_ungrouped_first_then_headers_and_collapse() {
        let choices = vec![
            ch("a", None),
            ch("bun", Some("runtime")),
            ch("node", Some("runtime")),
            ch("claude", Some("ai")),
        ];
        let groups = group_list(&choices);
        let rows = visible_rows(&choices, &groups, &[false, false]);
        assert_eq!(
            rows,
            vec![
                Row::Item(0),
                Row::Header(0),
                Row::Item(1),
                Row::Item(2),
                Row::Header(1),
                Row::Item(3),
            ]
        );
        // collapsing "runtime" hides its two items but keeps the header
        let rows = visible_rows(&choices, &groups, &[true, false]);
        assert_eq!(
            rows,
            vec![Row::Item(0), Row::Header(0), Row::Header(1), Row::Item(3)]
        );
    }

    #[test]
    fn no_groups_renders_flat() {
        let choices = vec![ch("a", None), ch("b", None)];
        let groups = group_list(&choices);
        assert!(groups.is_empty());
        assert_eq!(
            visible_rows(&choices, &groups, &[]),
            vec![Row::Item(0), Row::Item(1)]
        );
    }

    #[test]
    fn group_mark_all_some_none() {
        let choices = vec![ch("bun", Some("runtime")), ch("node", Some("runtime"))];
        assert_eq!(group_mark_multi(&choices, &[false, false], "runtime"), "[ ]");
        assert_eq!(group_mark_multi(&choices, &[true, false], "runtime"), "[~]");
        assert_eq!(group_mark_multi(&choices, &[true, true], "runtime"), "[x]");
    }

    #[test]
    fn item_label_strips_group_prefix() {
        let c = Choice {
            value: "bun".into(),
            label: "[runtime] bun — fast".into(),
            default: false,
            group: Some("runtime".into()),
        };
        assert_eq!(item_label(&c), "bun — fast");
        assert_eq!(item_label(&ch("x", None)), "x");
    }

    #[test]
    fn group_defaults_precedence() {
        let gd = GroupDefaults {
            collapsed_default: true,
            collapsed: vec!["x".into()],
            expanded: vec!["y".into()],
        };
        // baseline applies when not named
        assert!(gd.is_collapsed("other"));
        // expanded wins even over the collapsed baseline / collapsed list
        assert!(!gd.is_collapsed("y"));
        assert!(gd.is_collapsed("x"));

        let open = GroupDefaults {
            collapsed_default: false,
            collapsed: vec!["git".into()],
            expanded: vec![],
        };
        assert!(!open.is_collapsed("runtime"));
        assert!(open.is_collapsed("git"));
        let empty = std::collections::HashMap::new();
        assert_eq!(
            open.for_groups("f", &["runtime".into(), "git".into()], &empty),
            vec![false, true]
        );
        // a cached prior choice overrides the default
        let mut cache = std::collections::HashMap::new();
        cache.insert(super::collapse_key("f", "git"), false);
        assert_eq!(
            open.for_groups("f", &["runtime".into(), "git".into()], &cache),
            vec![false, false],
            "cached expand of git overrides collapsed_groups default"
        );
    }
}