textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
1410
1411
1412
1413
1414
1415
1416
use crossterm::event::KeyCode;
use rich_rs::{Console, ConsoleOptions, Renderable, Segment, Segments};

use crate::event::{Event, EventCtx, MouseDownEvent};
use crate::message::*;
use crate::render::{Cell, FrameBuffer};

use super::helpers::{adjust_line_length_no_bg, empty_classes};
use super::option_list::toggle_option::OptionCursorState;
use super::option_list::{OptionItem, OptionList};
use crate::action::ParsedAction;

use super::{BindingDecl, Widget, WidgetStyles};
use crate::compose::ComposeResult;
use crate::reactive::{ReactiveChange, ReactiveCtx, ReactiveFlags, ReactiveWidget};

/// Number of ticks before the type-to-search buffer resets (~500ms at 60Hz).
const SEARCH_RESET_TICKS: u64 = 30;

/// A dropdown select control.
///
/// Shows the current selection (or a placeholder prompt) with a dropdown arrow.
/// On activation (Enter/Space/click), opens an [`OptionList`] overlay for choosing a value.
/// When open, typing characters performs type-to-search (case-insensitive prefix matching).
///
/// Generic over the value type `T`.
pub struct Select<T: Clone + PartialEq + Send + Sync + 'static> {
    options: Vec<(String, T)>,
    cursor: OptionCursorState,
    prompt: String,
    disabled: bool,
    /// When `true`, the selection can be blank (no value). When `false` (default),
    /// the first option is auto-selected and the user cannot clear the selection.
    allow_blank: bool,
    open: bool,
    list: OptionList,
    focused: bool,
    hovered: bool,
    viewport_width: usize,
    viewport_height: usize,
    /// Current tick counter (updated via on_tick).
    current_tick: u64,
    /// Type-to-search buffer (accumulated while dropdown is open).
    search_buffer: String,
    /// Tick when last search character was typed (for timeout reset).
    search_last_tick: u64,
    classes: Vec<String>,
    focused_classes: Vec<String>,
    expanded_classes: Vec<String>,
    focused_expanded_classes: Vec<String>,
    styles: WidgetStyles,
}

impl<T: Clone + PartialEq + Send + Sync + 'static> Select<T> {
    /// Create a new `Select` widget.
    ///
    /// `options` is a list of `(label, value)` pairs.
    /// `prompt` is shown when nothing is selected.
    pub fn new(options: Vec<(String, T)>, prompt: impl Into<String>) -> Self {
        let list_items: Vec<OptionItem> = options
            .iter()
            .map(|(label, _)| OptionItem::new(label.as_str()))
            .collect();
        let mut list = OptionList::with_items(list_items);
        list.set_focus(true);

        // Default allow_blank=false: auto-select first option.
        let mut cursor = OptionCursorState::default();
        if !options.is_empty() {
            cursor.set_selected(Some(0));
            cursor.set_highlighted(Some(0));
            list.set_highlighted(0);
        }

        Self {
            options,
            cursor,
            prompt: prompt.into(),
            disabled: false,
            allow_blank: false,
            open: false,
            list,
            focused: false,
            hovered: false,
            viewport_width: 20,
            viewport_height: 10,
            current_tick: 0,
            search_buffer: String::new(),
            search_last_tick: 0,
            classes: vec!["select".to_string()],
            focused_classes: vec!["select".to_string(), "focused".to_string()],
            expanded_classes: vec!["select".to_string(), "-expanded".to_string()],
            focused_expanded_classes: vec![
                "select".to_string(),
                "focused".to_string(),
                "-expanded".to_string(),
            ],
            styles: WidgetStyles::default(),
        }
    }

    // ── Public API ──────────────────────────────────────────────────

    /// The currently selected value, or `None`.
    pub fn value(&self) -> Option<&T> {
        self.cursor
            .selected()
            .and_then(|i| self.options.get(i).map(|(_, v)| v))
    }

    /// Reactive setter for the selected value. If the value is not found,
    /// selection is cleared. Records the change in the provided [`ReactiveCtx`].
    pub fn set_value(&mut self, value: &T, ctx: &mut ReactiveCtx) {
        let selected = self.options.iter().position(|(_, v)| v == value);
        let old = self.cursor.selected();
        if old != selected {
            self.cursor.set_selected(selected);
            self.cursor.set_highlighted(selected);
            if let Some(index) = selected {
                self.list.set_highlighted(index);
            } else {
                self.list.clear_highlighted();
            }
            ctx.record_change(
                "value",
                ReactiveFlags::reactive(),
                Box::new(old),
                Box::new(selected),
            );
        } else {
            // Even if index matches, still sync UI state.
            self.cursor.set_selected(selected);
            self.cursor.set_highlighted(selected);
            if let Some(index) = selected {
                self.list.set_highlighted(index);
            } else {
                self.list.clear_highlighted();
            }
        }
    }

    /// Clear the current selection (revert to prompt state).
    ///
    /// This is a no-op when `allow_blank` is `false`.
    pub fn clear(&mut self) {
        if !self.allow_blank {
            return;
        }
        self.cursor.clear();
        self.list.clear_highlighted();
    }

    /// Whether the dropdown overlay is currently open.
    pub fn is_open(&self) -> bool {
        self.open
    }

    /// Whether blank (no selection) is allowed.
    pub fn allow_blank(&self) -> bool {
        self.allow_blank
    }

    /// Reactive setter for `allow_blank`. Records the change in the provided
    /// [`ReactiveCtx`].
    ///
    /// When switching from `allow_blank=true` to `false` and no option is
    /// currently selected, the first option is auto-selected.
    pub fn set_allow_blank(&mut self, allow: bool, ctx: &mut ReactiveCtx) {
        if self.allow_blank != allow {
            let old = self.allow_blank;
            self.allow_blank = allow;
            // Auto-select first option when switching to false (also done via watcher).
            if !allow && self.cursor.selected().is_none() && !self.options.is_empty() {
                self.cursor.set_selected(Some(0));
                self.cursor.set_highlighted(Some(0));
                self.list.set_highlighted(0);
            }
            ctx.record_change(
                "allow_blank",
                ReactiveFlags::reactive(),
                Box::new(old),
                Box::new(allow),
            );
        }
    }

    /// Reactive setter for `disabled`. Records the change in the provided
    /// [`ReactiveCtx`].
    pub fn set_disabled(&mut self, value: bool, ctx: &mut ReactiveCtx) {
        if self.disabled != value {
            let old = self.disabled;
            self.disabled = value;
            ctx.record_change(
                "disabled",
                ReactiveFlags::reactive(),
                Box::new(old),
                Box::new(value),
            );
        }
    }

    /// Builder: set whether blank (no selection) is allowed.
    ///
    /// When `true`, the initial state is no selection (placeholder is shown)
    /// and the user can deselect. When `false` (default), the first option
    /// is auto-selected and the user cannot clear the selection.
    pub fn with_allow_blank(mut self, allow: bool) -> Self {
        if allow {
            // Undo the auto-selection from new() — start blank.
            self.allow_blank = true;
            self.cursor.clear();
            self.list.clear_highlighted();
        } else {
            self.allow_blank = false;
            if self.cursor.selected().is_none() && !self.options.is_empty() {
                self.cursor.set_selected(Some(0));
                self.cursor.set_highlighted(Some(0));
                self.list.set_highlighted(0);
            }
        }
        self
    }

    /// Builder: set disabled state for the entire select.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        if disabled {
            self.focused = false;
            self.open = false;
            self.list.set_focus(false);
        }
        self
    }

    /// Reactive setter for `options`. Clears the current selection.
    /// Records the change in the provided [`ReactiveCtx`].
    ///
    /// When `allow_blank` is `false` and new options are non-empty,
    /// the first option is auto-selected.
    pub fn set_options(&mut self, options: Vec<(String, T)>, ctx: &mut ReactiveCtx) {
        let list_items: Vec<OptionItem> = options
            .iter()
            .map(|(label, _)| OptionItem::new(label.as_str()))
            .collect();
        let old_len = self.options.len();
        self.cursor.clear();
        self.list.set_items(list_items);
        self.options = options;
        let new_len = self.options.len();
        if !self.allow_blank && !self.options.is_empty() {
            self.cursor.set_selected(Some(0));
            self.cursor.set_highlighted(Some(0));
            self.list.set_highlighted(0);
        }
        ctx.record_change(
            "options",
            ReactiveFlags::reactive_layout(),
            Box::new(old_len),
            Box::new(new_len),
        );
    }

    // ── Watchers ─────────────────────────────────────────────────────

    fn watch_allow_blank(&mut self, _old: &bool, new: &bool, _ctx: &mut ReactiveCtx) {
        // When switching to allow_blank=false, auto-select first option if nothing selected.
        if !new && self.cursor.selected().is_none() && !self.options.is_empty() {
            self.cursor.set_selected(Some(0));
            self.cursor.set_highlighted(Some(0));
            self.list.set_highlighted(0);
        }
    }

    // ── Internals ───────────────────────────────────────────────────

    fn set_open(&mut self, open: bool, ctx: &mut EventCtx) {
        if self.open == open {
            return;
        }
        self.open = open;
        if self.open {
            // Sync list highlight with current selection.
            if let Some(selected) = self.cursor.selected() {
                self.list.set_highlighted(selected);
                self.cursor.set_highlighted(Some(selected));
            } else if let Some(first) = self.list.first_selectable_index() {
                self.list.set_highlighted(first);
                self.cursor.set_highlighted(Some(first));
            } else {
                self.list.clear_highlighted();
                self.cursor.set_highlighted(None);
            }
            self.list.set_focus(true);
            // Reset search state when opening.
            self.search_buffer.clear();
        } else {
            self.list.set_focus(false);
            self.search_buffer.clear();
        }
        ctx.request_repaint();
    }

    fn apply_selection(&mut self, index: usize, ctx: &mut EventCtx) {
        if index >= self.options.len() {
            return;
        }
        let changed = self.cursor.selected() != Some(index);
        self.cursor.set_selected(Some(index));
        self.cursor.set_highlighted(Some(index));
        self.set_open(false, ctx);
        if changed {
            let label = self.options[index].0.clone();
            ctx.post_message(Message::SelectChanged(SelectChanged { index, label }));
        }
    }

    /// Geometry for the dropdown overlay panel.
    fn dropdown_geometry(&self) -> (usize, usize, usize, usize) {
        let panel_x = 0usize;
        let panel_y = 1usize; // directly below the closed-state line
        let panel_width = self.viewport_width.max(1);
        let available_height = self.viewport_height.saturating_sub(panel_y).max(1);
        let desired = self.options.len().max(1);
        let panel_height = desired.min(available_height).min(12).max(1);
        (panel_x, panel_y, panel_width, panel_height)
    }

    /// Render the closed state: "  Selected Label   ▼" or "  Prompt...   ▼".
    fn render_closed(&self, options: &ConsoleOptions) -> Segments {
        let width = options.size.0.max(1);
        let mut classes = vec!["select--current-value"];
        if self.focused {
            classes.push("-focus");
        }
        if self.hovered {
            classes.push("-hover");
        }
        let label_style = crate::css::resolve_component_style(self, &classes)
            .to_rich()
            .unwrap_or_else(rich_rs::Style::new);

        let arrow_classes = if self.open {
            vec!["select--arrow", "-open"]
        } else {
            vec!["select--arrow"]
        };
        let arrow_style = crate::css::resolve_component_style(self, &arrow_classes)
            .to_rich()
            .unwrap_or(label_style);

        let label_text = if let Some(index) = self.cursor.selected() {
            self.options[index].0.as_str()
        } else {
            &self.prompt
        };

        let arrow = if self.open { "" } else { "" };
        // Reserve 2 cells for the arrow (space + arrow char).
        let label_width = width.saturating_sub(2).max(1);
        let label_seg = Segment::styled(
            rich_rs::set_cell_size(&format!(" {label_text}"), label_width),
            label_style,
        );
        let arrow_seg = Segment::styled(format!(" {arrow}"), arrow_style);

        let line = adjust_line_length_no_bg(&[label_seg, arrow_seg], width);
        let mut out = Segments::new();
        out.extend(line);
        out
    }

    /// Handle a character typed for type-to-search when the dropdown is open.
    /// Appends to the search buffer and highlights the first matching option.
    fn handle_search_char(&mut self, ch: char, tick: u64) {
        // Reset buffer if timeout expired.
        if tick.saturating_sub(self.search_last_tick) > SEARCH_RESET_TICKS {
            self.search_buffer.clear();
        }
        self.search_buffer.push(ch);
        self.search_last_tick = tick;

        // Find first option whose label starts with the search buffer (case-insensitive).
        let query = self.search_buffer.to_lowercase();
        if let Some(index) = self
            .options
            .iter()
            .position(|(label, _)| label.to_lowercase().starts_with(&query))
        {
            self.list.set_highlighted(index);
            self.cursor.set_highlighted(Some(index));
        }
    }
}

impl<T: Clone + PartialEq + Send + Sync + 'static> Widget for Select<T> {
    /// Declare children for tree-based mounting.
    ///
    /// Select's inner OptionList is managed internally (not a mountable child),
    /// so compose returns an empty list.
    fn compose(&self) -> ComposeResult {
        Vec::new()
    }

    fn take_composed_children(&mut self) -> Vec<Box<dyn Widget>> {
        Vec::new()
    }

    fn focusable(&self) -> bool {
        !self.disabled
    }

    fn set_focus(&mut self, focused: bool) {
        self.focused = focused && !self.disabled;
        if !focused && self.open {
            // Close dropdown when focus is lost.
            self.open = false;
            self.list.set_focus(false);
            self.search_buffer.clear();
        }
    }

    fn has_focus(&self) -> bool {
        self.focused
    }

    fn is_disabled(&self) -> bool {
        self.disabled
    }

    fn set_disabled_state(&mut self, disabled: bool) {
        self.disabled = disabled;
        if disabled {
            self.open = false;
            self.search_buffer.clear();
        }
    }

    fn is_hovered(&self) -> bool {
        self.hovered
    }

    fn set_hovered(&mut self, hovered: bool) {
        self.hovered = hovered;
    }

    fn on_layout(&mut self, width: u16, height: u16) {
        self.viewport_width = usize::from(width).max(1);
        self.viewport_height = usize::from(height).max(1);
        if self.open {
            let (_, _, pw, ph) = self.dropdown_geometry();
            self.list.on_layout(pw as u16, ph as u16);
        }
    }

    fn on_tick(&mut self, tick: u64) {
        self.current_tick = tick;
        // Reset search buffer after timeout.
        if self.open
            && !self.search_buffer.is_empty()
            && tick.saturating_sub(self.search_last_tick) > SEARCH_RESET_TICKS
        {
            self.search_buffer.clear();
        }
    }

    fn action_namespace(&self) -> &str {
        "select"
    }

    fn bindings(&self) -> Vec<BindingDecl> {
        vec![
            BindingDecl::new("enter,space,down,up", "show_overlay", "Show select options"),
            BindingDecl::new("escape", "dismiss_overlay", "Dismiss select options").hidden(),
        ]
    }

    fn execute_action(&mut self, action: &ParsedAction, ctx: &mut EventCtx) -> bool {
        if self.disabled {
            return false;
        }
        match action.name.as_str() {
            "show_overlay" => {
                if !self.open {
                    self.set_open(true, ctx);
                    ctx.set_handled();
                    true
                } else {
                    false
                }
            }
            "dismiss_overlay" => {
                if self.open {
                    if self.allow_blank {
                        self.cursor.clear();
                        self.list.clear_highlighted();
                    }
                    self.set_open(false, ctx);
                    ctx.set_handled();
                    true
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
        if self.disabled {
            return;
        }
        if self.open {
            // When the overlay is open, handle its events first.
            match event {
                Event::Key(key) => match key.code {
                    KeyCode::Esc => {
                        if self.allow_blank {
                            // Deselect: revert to blank/placeholder state.
                            self.cursor.clear();
                            self.list.clear_highlighted();
                        }
                        self.set_open(false, ctx);
                        ctx.set_handled();
                        return;
                    }
                    KeyCode::Enter => {
                        if self.list.highlighted().is_none() {
                            self.set_open(false, ctx);
                        } else {
                            // Route selection through OptionList message flow.
                            self.list.on_event(event, ctx);
                            self.cursor.set_highlighted(self.list.highlighted());
                        }
                        ctx.set_handled();
                        return;
                    }
                    KeyCode::Char(ch) => {
                        // Type-to-search: printable chars that aren't space (space toggles).
                        if ch != ' ' {
                            self.handle_search_char(ch, self.current_tick);
                            ctx.request_repaint();
                            ctx.set_handled();
                            return;
                        }
                    }
                    _ => {}
                },
                Event::MouseDown(mouse) => {
                    if mouse.target != self.node_id() {
                        // Click outside the Select widget — close dropdown.
                        self.set_open(false, ctx);
                        ctx.set_handled();
                        return;
                    }
                    // Click within Select — check if it's in the dropdown area.
                    let (_, panel_y, _, panel_h) = self.dropdown_geometry();
                    let click_y = mouse.y as usize;
                    if click_y >= panel_y && click_y < panel_y + panel_h {
                        // Forward click to the inner OptionList, preserving the raw y
                        // coordinate so the list's offset-based index calculation works.
                        self.list.on_event(
                            &Event::MouseDown(MouseDownEvent {
                                target: self.node_id(),
                                screen_x: mouse.screen_x,
                                screen_y: mouse.screen_y,
                                x: mouse.x,
                                y: mouse.y,
                            }),
                            ctx,
                        );
                        self.cursor.set_highlighted(self.list.highlighted());
                    } else {
                        // Click on the closed-state bar area — toggle closed.
                        self.set_open(false, ctx);
                    }
                    ctx.set_handled();
                    return;
                }
                _ => {}
            }
            // Delegate navigation keys to the inner OptionList.
            self.list.on_event(event, ctx);
            self.cursor.set_highlighted(self.list.highlighted());
            if !ctx.handled() {
                // Absorb all events when overlay is open.
                ctx.set_handled();
            }
        } else {
            // Closed state: open on Enter/Space/click.
            match event {
                Event::Key(key) if self.focused => match key.code {
                    KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Down | KeyCode::Up => {
                        self.set_open(true, ctx);
                        ctx.set_handled();
                    }
                    _ => {}
                },
                Event::MouseDown(mouse) if mouse.target == self.node_id() => {
                    self.set_open(true, ctx);
                    ctx.set_handled();
                }
                _ => {}
            }
        }
    }

    fn on_message(&mut self, message: &MessageEvent, ctx: &mut EventCtx) {
        // Handle OptionSelected from inner list.
        if message.sender == self.node_id() {
            if let Message::OptionSelected(OptionSelected { index }) = &message.message {
                self.apply_selection(*index, ctx);
                ctx.set_handled();
                return;
            }
        }
    }

    fn on_mouse_move(&mut self, x: u16, y: u16) -> bool {
        if self.disabled {
            return false;
        }
        if self.open {
            // Forward to the list if the mouse is within the dropdown area.
            let (_, panel_y, _, panel_h) = self.dropdown_geometry();
            let y_usize = y as usize;
            if y_usize >= panel_y && y_usize < panel_y + panel_h {
                return self.list.on_mouse_move(x, (y_usize - panel_y) as u16);
            }
        }
        false
    }

    fn on_mouse_scroll(&mut self, delta_x: i32, delta_y: i32, ctx: &mut EventCtx) {
        if self.disabled {
            return;
        }
        if self.open {
            self.list.on_mouse_scroll(delta_x, delta_y, ctx);
            if !ctx.handled() {
                ctx.set_handled();
            }
        }
    }

    fn render(&self, console: &Console, options: &ConsoleOptions) -> Segments {
        if !self.open {
            return self.render_closed(options);
        }

        // Open state: render closed bar + dropdown overlay below it.
        let (width, height) = options.size;
        let width = width.max(1);
        let height = height.max(1);

        // Render the closed-state line into the top row of a full-height buffer.
        let mut closed_options = options.clone();
        closed_options.size = (width, 1);
        closed_options.max_width = width;
        closed_options.max_height = 1;
        let closed_segments = self.render_closed(&closed_options);
        let closed_lines =
            Segment::split_and_crop_lines(closed_segments, width, None, false, false);
        let closed_buf = FrameBuffer::from_lines(&closed_lines, width, 1, None);
        let mut merged = FrameBuffer::new(width, height, None);
        for x in 0..width.min(closed_buf.width) {
            merged.set_cell(x, 0, closed_buf.get(x, 0).clone());
        }

        // Render the dropdown OptionList.
        let (panel_x, panel_y, panel_width, panel_height) = self.dropdown_geometry();
        let panel_width = panel_width.min(width);
        let panel_height = panel_height.min(height.saturating_sub(panel_y));
        if panel_height == 0 {
            return merged.to_segments();
        }

        let panel_style = crate::css::resolve_component_style(self, &["select--dropdown"])
            .to_rich()
            .unwrap_or_else(rich_rs::Style::new);

        // Clear the dropdown area.
        for y in panel_y..panel_y.saturating_add(panel_height).min(height) {
            for x in panel_x..panel_x.saturating_add(panel_width).min(width) {
                merged.set_cell(x, y, Cell::blank(Some(panel_style)));
            }
        }

        // Render the OptionList into a sub-buffer.
        let mut list_options = options.clone();
        list_options.size = (panel_width, panel_height);
        list_options.max_width = panel_width;
        list_options.max_height = panel_height;
        let list_buffer = FrameBuffer::from_renderable(console, &list_options, &self.list, None);

        for sy in 0..list_buffer.height.min(panel_height) {
            let ty = panel_y.saturating_add(sy);
            if ty >= height {
                break;
            }
            for sx in 0..list_buffer.width.min(panel_width) {
                let tx = panel_x.saturating_add(sx);
                if tx >= width {
                    break;
                }
                merged.set_cell(tx, ty, list_buffer.get(sx, sy).clone());
            }
        }

        merged.to_segments()
    }

    fn layout_height(&self) -> Option<usize> {
        // When closed, 1 line. When open, 1 + dropdown height.
        if self.open {
            let (_, _, _, ph) = self.dropdown_geometry();
            Some(1 + ph)
        } else {
            Some(1)
        }
    }

    fn content_width(&self) -> Option<usize> {
        let label_width = self
            .options
            .iter()
            .map(|(label, _)| rich_rs::cell_len(label))
            .max()
            .unwrap_or(0)
            .max(rich_rs::cell_len(&self.prompt));
        // label + space padding + arrow
        let meta = crate::css::selector_meta_generic(self);
        let resolved = crate::css::resolve_style(self, &meta);
        let padding = resolved.effective_padding();
        let (_, _, border_left, border_right) =
            super::helpers::border_spacing_from_style(&resolved);
        let chrome_lr =
            usize::from(padding.left.saturating_add(padding.right)) + border_left + border_right;
        Some(
            label_width
                .saturating_add(3)
                .saturating_add(chrome_lr)
                .max(1),
        )
    }

    fn style_classes(&self) -> &[String] {
        match (self.focused, self.open) {
            (true, true) => &self.focused_expanded_classes,
            (true, false) => &self.focused_classes,
            (false, true) => &self.expanded_classes,
            (false, false) => {
                if self.classes.is_empty() {
                    empty_classes()
                } else {
                    &self.classes
                }
            }
        }
    }

    fn style_type(&self) -> &'static str {
        "Select"
    }

    fn styles(&self) -> Option<&WidgetStyles> {
        Some(&self.styles)
    }

    fn styles_mut(&mut self) -> Option<&mut WidgetStyles> {
        Some(&mut self.styles)
    }

    // NOTE: Select intentionally does NOT implement visit_children_mut.
    // The inner OptionList is a private implementation detail and should not
    // appear in the global focus traversal — Select manages it internally.
}

impl<T: Clone + PartialEq + Send + Sync + 'static> Renderable for Select<T> {
    fn render(&self, console: &Console, options: &ConsoleOptions) -> Segments {
        Widget::render(self, console, options)
    }
}

impl<T: Clone + PartialEq + Send + Sync + 'static> ReactiveWidget for Select<T> {
    fn reactive_dispatch(&mut self, changes: &[ReactiveChange], ctx: &mut ReactiveCtx) {
        for change in changes {
            match change.field_name {
                "allow_blank" => {
                    if let (Some(old), Some(new)) = (
                        change.old_value.downcast_ref::<bool>(),
                        change.new_value.downcast_ref::<bool>(),
                    ) {
                        self.watch_allow_blank(old, new, ctx);
                    }
                }
                _ => {}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{Event, EventCtx, MouseDownEvent};
    use crate::keys::KeyEventData;
    use crate::message::Message;
    use crate::node_id::NodeId;
    use crate::node_id::node_id_from_ffi;
    use crate::reactive::ReactiveCtx;
    use slotmap::SlotMap;

    fn make_node_id() -> NodeId {
        let mut sm: SlotMap<NodeId, ()> = SlotMap::new();
        sm.insert(())
    }

    /// Derive a test-only NodeId from a widget's pointer address.
    fn widget_node_id(w: &dyn Widget) -> crate::node_id::NodeId {
        let ptr = (w as *const dyn Widget).cast::<()>() as u64;
        node_id_from_ffi(ptr)
    }
    use crate::message::MessageEvent;
    use crossterm::event::{KeyEvent, KeyModifiers};

    fn make_select() -> Select<i32> {
        Select::new(
            vec![
                ("Alpha".to_string(), 1),
                ("Beta".to_string(), 2),
                ("Gamma".to_string(), 3),
            ],
            "Pick one...",
        )
    }

    fn make_select_blank() -> Select<i32> {
        make_select().with_allow_blank(true)
    }

    fn dispatch_messages(sel: &mut Select<i32>, ctx: &mut EventCtx) -> Vec<MessageEvent> {
        let mut delivered = Vec::new();
        loop {
            let batch = ctx.take_messages();
            if batch.is_empty() {
                break;
            }
            delivered.extend(batch.clone());
            for message in batch {
                sel.on_message(&message, ctx);
            }
        }
        delivered
    }

    #[test]
    fn select_starts_closed_with_first_selected() {
        // Default allow_blank=false auto-selects the first option.
        let sel = make_select();
        assert!(!sel.is_open());
        assert_eq!(sel.value(), Some(&1)); // Alpha
    }

    #[test]
    fn select_opens_on_enter() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let key = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(key), &mut ctx);
        assert!(sel.is_open());
        assert!(ctx.handled());
    }

    #[test]
    fn select_closes_on_escape() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let key = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(key), &mut ctx);
        assert!(sel.is_open());

        // Close
        let esc = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(esc), &mut ctx2);
        assert!(!sel.is_open());
    }

    #[test]
    fn select_enter_selects_highlighted_option() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter.clone()), &mut ctx);
        assert!(sel.is_open());

        // Move down once
        let down = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(down), &mut ctx2);

        // Confirm with Enter
        let mut ctx3 = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx3);
        let delivered = dispatch_messages(&mut sel, &mut ctx3);
        assert!(!sel.is_open());
        assert_eq!(sel.value(), Some(&2)); // Beta

        let option_selected_pos = delivered.iter().position(|m| {
            matches!(
                m.message,
                Message::OptionSelected(OptionSelected { index: 1 })
            )
        });
        let select_changed_pos = delivered.iter().position(|m| {
            matches!(
                m.message,
                Message::SelectChanged(SelectChanged { index: 1, label: _ })
            )
        });
        assert!(
            option_selected_pos.is_some()
                && select_changed_pos.is_some()
                && option_selected_pos < select_changed_pos
        );
    }

    #[test]
    fn select_mouse_click_inside_dropdown_selects_item() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let open_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut open_ctx = EventCtx::default();
        sel.on_event(&Event::Key(open_key), &mut open_ctx);
        assert!(sel.is_open());

        let mut click_ctx = EventCtx::default();
        sel.on_event(
            &Event::MouseDown(MouseDownEvent {
                target: NodeId::default(),
                screen_x: 1,
                screen_y: 2,
                x: 1,
                y: 1,
            }),
            &mut click_ctx,
        );
        let delivered = dispatch_messages(&mut sel, &mut click_ctx);

        assert!(!sel.is_open());
        assert_eq!(sel.value(), Some(&2));
        assert!(click_ctx.handled());
        let option_selected_pos = delivered.iter().position(|m| {
            matches!(
                m.message,
                Message::OptionSelected(OptionSelected { index: 1 })
            )
        });
        let select_changed_pos = delivered.iter().position(|m| {
            matches!(
                m.message,
                Message::SelectChanged(SelectChanged { index: 1, label: _ })
            )
        });
        assert!(
            option_selected_pos.is_some()
                && select_changed_pos.is_some()
                && option_selected_pos < select_changed_pos
        );
    }

    #[test]
    fn select_set_value_programmatic() {
        let mut sel = make_select();
        let mut ctx = ReactiveCtx::new(make_node_id());
        sel.set_value(&3, &mut ctx);
        assert_eq!(sel.value(), Some(&3));
    }

    #[test]
    fn select_clear_resets_when_allow_blank() {
        let mut sel = make_select_blank();
        let mut ctx = ReactiveCtx::new(make_node_id());
        sel.set_value(&2, &mut ctx);
        sel.clear();
        assert!(sel.value().is_none());
    }

    #[test]
    fn select_clear_then_reopen_highlights_first_selectable() {
        let mut sel = make_select_blank();
        let mut ctx = ReactiveCtx::new(make_node_id());
        sel.set_value(&3, &mut ctx);
        sel.clear();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let open = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(open), &mut ctx);

        assert!(sel.is_open());
        assert_eq!(sel.list.highlighted(), Some(0));
    }

    #[test]
    fn select_ignores_disabled_option_click() {
        let mut sel = Select::new(
            vec![("Alpha".to_string(), 1), ("Beta".to_string(), 2)],
            "Pick one...",
        );
        sel.list
            .set_items(vec![OptionItem::new("Alpha"), OptionItem::disabled("Beta")]);
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let open = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut open_ctx = EventCtx::default();
        sel.on_event(&Event::Key(open), &mut open_ctx);
        assert!(sel.is_open());

        let mut click_ctx = EventCtx::default();
        sel.on_event(
            &Event::MouseDown(MouseDownEvent {
                target: NodeId::default(),
                screen_x: 1,
                screen_y: 2,
                x: 1,
                y: 1,
            }),
            &mut click_ctx,
        );

        // Value unchanged — still Alpha (auto-selected, disabled Beta ignored).
        assert_eq!(sel.value(), Some(&1));
        assert!(sel.is_open());
    }

    #[test]
    fn select_disabled_ignores_open_input() {
        let mut sel = make_select().disabled(true);
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let key = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut key_ctx = EventCtx::default();
        sel.on_event(&Event::Key(key), &mut key_ctx);
        assert!(!sel.is_open());
        assert!(!key_ctx.handled());

        let mut click_ctx = EventCtx::default();
        sel.on_event(
            &Event::MouseDown(MouseDownEvent {
                target: widget_node_id(&sel),
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
            &mut click_ctx,
        );
        assert!(!sel.is_open());
        assert!(!click_ctx.handled());
        assert!(!sel.focusable());
    }

    #[test]
    fn select_type_to_search_highlights_matching_option() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);
        assert!(sel.is_open());

        // Advance tick so type-to-search has a time reference.
        sel.on_tick(10);

        // Type 'g' — should highlight "Gamma" (index 2).
        let g_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(g_key), &mut ctx2);

        assert_eq!(sel.list.highlighted(), Some(2));
        assert!(ctx2.handled());
    }

    #[test]
    fn select_type_to_search_accumulates_chars() {
        let mut sel = Select::new(
            vec![
                ("Apple".to_string(), 1),
                ("Apricot".to_string(), 2),
                ("Banana".to_string(), 3),
            ],
            "Pick one...",
        );
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);
        assert!(sel.is_open());

        // Type 'a' at tick 10 — should match "Apple" (index 0).
        sel.on_tick(10);
        let a_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(a_key), &mut ctx2);
        assert_eq!(sel.list.highlighted(), Some(0));

        // Type 'p' at tick 11 — buffer is "ap", matches "Apple" (index 0).
        sel.on_tick(11);
        let p_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE));
        let mut ctx3 = EventCtx::default();
        sel.on_event(&Event::Key(p_key), &mut ctx3);
        assert_eq!(sel.list.highlighted(), Some(0));

        // Type 'r' at tick 12 — buffer is "apr", matches "Apricot" (index 1).
        sel.on_tick(12);
        let r_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE));
        let mut ctx4 = EventCtx::default();
        sel.on_event(&Event::Key(r_key), &mut ctx4);
        assert_eq!(sel.list.highlighted(), Some(1));
    }

    #[test]
    fn select_type_to_search_resets_on_timeout() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);

        // Type 'b' at tick 10 — highlights "Beta" (index 1).
        sel.on_tick(10);
        let b_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(b_key), &mut ctx2);
        assert_eq!(sel.list.highlighted(), Some(1));

        // Simulate timeout via on_tick.
        sel.on_tick(50);
        assert!(sel.search_buffer.is_empty());

        // Type 'a' after timeout — fresh search, highlights "Alpha" (index 0).
        let a_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        let mut ctx3 = EventCtx::default();
        sel.on_event(&Event::Key(a_key), &mut ctx3);
        assert_eq!(sel.list.highlighted(), Some(0));
    }

    // ── allow_blank tests ─────────────────────────────────────────────

    #[test]
    fn allow_blank_true_starts_with_no_selection() {
        let sel = make_select_blank();
        assert!(sel.allow_blank());
        assert!(sel.value().is_none());
    }

    #[test]
    fn allow_blank_false_auto_selects_first() {
        let sel = make_select();
        assert!(!sel.allow_blank());
        assert_eq!(sel.value(), Some(&1)); // Alpha
    }

    #[test]
    fn allow_blank_true_escape_clears_selection() {
        let mut sel = make_select_blank();
        let mut rctx = ReactiveCtx::new(make_node_id());
        sel.set_value(&2, &mut rctx); // Beta
        assert_eq!(sel.value(), Some(&2));
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);
        assert!(sel.is_open());

        // Escape — should clear selection (allow_blank=true)
        let esc = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(esc), &mut ctx2);
        assert!(!sel.is_open());
        assert!(sel.value().is_none());
    }

    #[test]
    fn allow_blank_false_escape_keeps_selection() {
        let mut sel = make_select();
        let mut rctx = ReactiveCtx::new(make_node_id());
        sel.set_value(&2, &mut rctx); // Beta
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);
        assert!(sel.is_open());

        // Escape — should NOT clear (allow_blank=false)
        let esc = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        let mut ctx2 = EventCtx::default();
        sel.on_event(&Event::Key(esc), &mut ctx2);
        assert!(!sel.is_open());
        assert_eq!(sel.value(), Some(&2)); // Still Beta
    }

    #[test]
    fn allow_blank_false_clear_is_noop() {
        let mut sel = make_select();
        assert_eq!(sel.value(), Some(&1)); // Alpha auto-selected
        sel.clear();
        assert_eq!(sel.value(), Some(&1)); // Still Alpha — clear is a no-op
    }

    #[test]
    fn with_allow_blank_builder() {
        let sel = make_select().with_allow_blank(true);
        assert!(sel.allow_blank());
        assert!(sel.value().is_none());

        let sel2 = make_select().with_allow_blank(false);
        assert!(!sel2.allow_blank());
        assert_eq!(sel2.value(), Some(&1)); // Alpha
    }

    #[test]
    fn set_allow_blank_auto_selects_when_switching_to_false() {
        let mut sel = make_select_blank();
        let mut ctx = ReactiveCtx::new(make_node_id());
        assert!(sel.value().is_none());
        sel.set_allow_blank(false, &mut ctx);
        assert!(!sel.allow_blank());
        assert_eq!(sel.value(), Some(&1)); // Alpha auto-selected
    }

    #[test]
    fn set_options_auto_selects_when_not_allow_blank() {
        let mut sel = make_select();
        let mut ctx = ReactiveCtx::new(make_node_id());
        sel.set_options(
            vec![("Delta".to_string(), 10), ("Echo".to_string(), 20)],
            &mut ctx,
        );
        assert_eq!(sel.value(), Some(&10)); // Delta auto-selected
    }

    #[test]
    fn set_options_does_not_auto_select_when_allow_blank() {
        let mut sel = make_select_blank();
        let mut ctx = ReactiveCtx::new(make_node_id());
        sel.set_options(
            vec![("Delta".to_string(), 10), ("Echo".to_string(), 20)],
            &mut ctx,
        );
        assert!(sel.value().is_none());
    }

    #[test]
    fn bindings_are_declared() {
        let sel = make_select();
        let bindings = sel.bindings();
        assert!(!bindings.is_empty());
        assert!(bindings.iter().any(|b| b.action == "show_overlay"));
        assert!(bindings.iter().any(|b| b.action == "dismiss_overlay"));
    }

    // ── compose() / take_composed_children() tests ────────────────

    #[test]
    fn compose_returns_empty() {
        let sel = make_select();
        let result = sel.compose();
        assert!(result.is_empty());
    }

    #[test]
    fn take_composed_children_returns_empty() {
        let mut sel = make_select();
        let children = sel.take_composed_children();
        assert!(children.is_empty());
    }

    #[test]
    fn compose_stable_across_state_changes() {
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        // Open the dropdown
        let enter = KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut ctx = EventCtx::default();
        sel.on_event(&Event::Key(enter), &mut ctx);
        assert!(sel.is_open());

        // compose() should still return empty even when open
        assert!(sel.compose().is_empty());
        assert!(sel.take_composed_children().is_empty());
    }

    #[test]
    fn execute_action_handles_show_overlay() {
        use crate::action::ParsedAction;
        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(20, 10);
        let mut ctx = EventCtx::default();
        let action = ParsedAction {
            namespace: None,
            name: "show_overlay".to_string(),
            arguments: vec![],
        };
        assert!(!sel.is_open());
        assert!(sel.execute_action(&action, &mut ctx));
        assert!(sel.is_open());
    }

    // ── P1-14 dispatch-context regression tests ─────────────────────────

    #[test]
    fn mouse_click_with_dispatch_context_opens_select() {
        use crate::runtime::dispatch_ctx::set_dispatch_recipient;

        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let id = make_node_id();
        let _guard = set_dispatch_recipient(id);

        let mut ctx = EventCtx::default();
        sel.on_event(
            &Event::MouseDown(MouseDownEvent {
                target: id,
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
            &mut ctx,
        );
        assert!(ctx.handled());
        assert!(sel.is_open());
    }

    #[test]
    fn mouse_click_with_wrong_target_closes_open_select() {
        use crate::runtime::dispatch_ctx::set_dispatch_recipient;
        use slotmap::SlotMap;

        let mut sel = make_select();
        sel.set_focus(true);
        sel.on_layout(30, 20);

        let mut sm: SlotMap<NodeId, ()> = SlotMap::new();
        let my_id = sm.insert(());
        let other_id = sm.insert(());
        let _guard = set_dispatch_recipient(my_id);

        // Open via keyboard first.
        let open_key =
            KeyEventData::from_crossterm(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        let mut open_ctx = EventCtx::default();
        sel.on_event(&Event::Key(open_key), &mut open_ctx);
        assert!(sel.is_open());

        // Click with a different target (outside) — should close dropdown.
        let mut ctx = EventCtx::default();
        sel.on_event(
            &Event::MouseDown(MouseDownEvent {
                target: other_id,
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
            &mut ctx,
        );
        assert!(ctx.handled());
        assert!(!sel.is_open());
    }
}