charmed-bubbles 0.2.0

Common TUI components for bubbletea applications
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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
//! Feature-rich list component with filtering and pagination.
//!
//! This module provides a list widget with optional filtering, pagination,
//! help display, status messages, and spinner for TUI applications.
//!
//! # Example
//!
//! ```rust
//! use bubbles::list::{List, Item, DefaultDelegate};
//!
//! #[derive(Clone)]
//! struct MyItem {
//!     title: String,
//!     description: String,
//! }
//!
//! impl Item for MyItem {
//!     fn filter_value(&self) -> &str {
//!         &self.title
//!     }
//!
//!     fn title(&self) -> &str {
//!         &self.title
//!     }
//!
//!     fn description(&self) -> &str {
//!         &self.description
//!     }
//! }
//!
//! let items = vec![
//!     MyItem { title: "Apple".into(), description: "A fruit".into() },
//!     MyItem { title: "Banana".into(), description: "Another fruit".into() },
//! ];
//!
//! let list = List::new(items, DefaultDelegate::new(), 80, 24);
//! ```

use crate::help::Help;
use crate::key::{Binding, matches};
use crate::paginator::{Paginator, Type as PaginatorType};
use crate::spinner::{SpinnerModel, TickMsg};
use crate::textinput::TextInput;
use bubbletea::{Cmd, KeyMsg, Message, Model, MouseAction, MouseButton, MouseMsg};
use lipgloss::{Color, Style, height as lipgloss_height};
use std::time::Duration;

/// Trait for items that can be displayed in a list.
pub trait Item: Clone + Send + 'static {
    /// Returns the value used for filtering.
    fn filter_value(&self) -> &str;

    /// Returns the item's title (used by the default delegate).
    ///
    /// Matches Go bubbles list semantics where filtering is usually based on the title.
    fn title(&self) -> &str {
        self.filter_value()
    }

    /// Returns the item's description (used by the default delegate).
    ///
    /// Default is empty, which renders as a two-line item with a blank second line
    /// when the default delegate is configured to show descriptions.
    fn description(&self) -> &str {
        ""
    }
}

/// Trait for rendering list items.
pub trait ItemDelegate<I: Item>: Clone + Send + 'static {
    /// Returns the height of each item in lines.
    fn height(&self) -> usize;

    /// Returns the spacing between items.
    fn spacing(&self) -> usize;

    /// Renders an item.
    fn render(&self, item: &I, index: usize, selected: bool, width: usize) -> String;

    /// Updates the delegate (optional).
    fn update(&mut self, _msg: &Message, _item: &mut I) -> Option<Cmd> {
        None
    }
}

/// Default delegate for simple item rendering.
#[derive(Debug, Clone)]
pub struct DefaultDelegate {
    /// Whether to show item descriptions (two-line items).
    pub show_description: bool,
    /// Style for normal items.
    pub normal_style: Style,
    /// Style for selected items.
    pub selected_style: Style,
    /// Height of each item.
    pub item_height: usize,
    /// Spacing between items.
    pub item_spacing: usize,
}

impl Default for DefaultDelegate {
    fn default() -> Self {
        Self::new()
    }
}

impl DefaultDelegate {
    /// Creates a new default delegate.
    #[must_use]
    pub fn new() -> Self {
        Self {
            show_description: true,
            normal_style: Style::new(),
            selected_style: Style::new().foreground_color(Color::from("212")).bold(),
            // Match Go bubbles list.NewDefaultDelegate defaults (height=2, spacing=1).
            item_height: 2,
            item_spacing: 1,
        }
    }

    /// Sets the item height.
    #[must_use]
    pub fn with_height(mut self, h: usize) -> Self {
        self.item_height = h;
        self
    }

    /// Sets the item spacing.
    #[must_use]
    pub fn with_spacing(mut self, s: usize) -> Self {
        self.item_spacing = s;
        self
    }

    /// Sets whether to show descriptions (two-line items).
    #[must_use]
    pub fn with_show_description(mut self, v: bool) -> Self {
        self.show_description = v;
        self
    }
}

impl<I: Item> ItemDelegate<I> for DefaultDelegate {
    fn height(&self) -> usize {
        if !self.show_description {
            return 1;
        }
        self.item_height
    }

    fn spacing(&self) -> usize {
        self.item_spacing
    }

    fn render(&self, item: &I, _index: usize, selected: bool, width: usize) -> String {
        let title = item.title();
        let desc = item.description();

        // Truncate based on display width
        let truncate = |value: &str| {
            use unicode_width::UnicodeWidthStr;
            if UnicodeWidthStr::width(value) <= width {
                value.to_string()
            } else if width == 0 {
                String::new()
            } else {
                let target_width = width.saturating_sub(1);
                let mut current_width = 0;
                let mut result = String::new();

                for c in value.chars() {
                    let w = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                    if current_width + w > target_width {
                        break;
                    }
                    result.push(c);
                    current_width += w;
                }
                format!("{}", result)
            }
        };

        let title_trunc = truncate(title);
        let desc_trunc = truncate(desc);

        if selected {
            if self.show_description {
                format!(
                    "{}\n{}",
                    self.selected_style.render(&title_trunc),
                    self.selected_style.render(&desc_trunc)
                )
            } else {
                self.selected_style.render(&title_trunc)
            }
        } else {
            if self.show_description {
                format!(
                    "{}\n{}",
                    self.normal_style.render(&title_trunc),
                    self.normal_style.render(&desc_trunc)
                )
            } else {
                self.normal_style.render(&title_trunc)
            }
        }
    }
}

/// Represents a match rank from filtering.
#[derive(Debug, Clone)]
pub struct Rank {
    /// Index of the item in the original list.
    pub index: usize,
    /// Indices of matched characters.
    pub matched_indices: Vec<usize>,
}

/// Filter state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterState {
    /// No filter applied.
    Unfiltered,
    /// User is actively filtering.
    Filtering,
    /// Filter has been applied.
    FilterApplied,
}

impl std::fmt::Display for FilterState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unfiltered => write!(f, "unfiltered"),
            Self::Filtering => write!(f, "filtering"),
            Self::FilterApplied => write!(f, "filter applied"),
        }
    }
}

/// Type alias for filter functions.
pub type FilterFn = Box<dyn Fn(&str, &[String]) -> Vec<Rank> + Send + Sync>;

/// Default filter using simple substring matching.
pub fn default_filter(term: &str, targets: &[String]) -> Vec<Rank> {
    let term_lower = term.to_lowercase();
    targets
        .iter()
        .enumerate()
        .filter(|(_, target)| target.to_lowercase().contains(&term_lower))
        .map(|(index, target)| {
            // Find match indices
            let target_lower = target.to_lowercase();
            let start = target_lower.find(&term_lower).unwrap_or(0);
            let matched_indices: Vec<usize> = (start..start + term.len()).collect();
            Rank {
                index,
                matched_indices,
            }
        })
        .collect()
}

/// Key bindings for list navigation.
#[derive(Debug, Clone)]
pub struct KeyMap {
    /// Move cursor up.
    pub cursor_up: Binding,
    /// Move cursor down.
    pub cursor_down: Binding,
    /// Next page.
    pub next_page: Binding,
    /// Previous page.
    pub prev_page: Binding,
    /// Go to start.
    pub goto_start: Binding,
    /// Go to end.
    pub goto_end: Binding,
    /// Start filtering.
    pub filter: Binding,
    /// Clear filter.
    pub clear_filter: Binding,
    /// Cancel filtering.
    pub cancel_while_filtering: Binding,
    /// Accept filter.
    pub accept_while_filtering: Binding,
    /// Show full help.
    pub show_full_help: Binding,
    /// Close full help.
    pub close_full_help: Binding,
    /// Quit.
    pub quit: Binding,
    /// Force quit.
    pub force_quit: Binding,
}

impl Default for KeyMap {
    fn default() -> Self {
        Self {
            cursor_up: Binding::new().keys(&["up", "k"]).help("↑/k", "up"),
            cursor_down: Binding::new().keys(&["down", "j"]).help("↓/j", "down"),
            next_page: Binding::new()
                .keys(&["right", "l", "pgdown"])
                .help("→/l", "next page"),
            prev_page: Binding::new()
                .keys(&["left", "h", "pgup"])
                .help("←/h", "prev page"),
            goto_start: Binding::new().keys(&["home", "g"]).help("g/home", "start"),
            goto_end: Binding::new().keys(&["end", "G"]).help("G/end", "end"),
            filter: Binding::new().keys(&["/"]).help("/", "filter"),
            clear_filter: Binding::new().keys(&["esc"]).help("esc", "clear filter"),
            cancel_while_filtering: Binding::new().keys(&["esc"]).help("esc", "cancel"),
            accept_while_filtering: Binding::new()
                .keys(&["enter"])
                .help("enter", "apply filter"),
            show_full_help: Binding::new().keys(&["?"]).help("?", "help"),
            close_full_help: Binding::new()
                .keys(&["esc", "?"])
                .help("?/esc", "close help"),
            quit: Binding::new().keys(&["q"]).help("q", "quit"),
            force_quit: Binding::new()
                .keys(&["ctrl+c"])
                .help("ctrl+c", "force quit"),
        }
    }
}

/// Styles for the list.
#[derive(Debug, Clone)]
pub struct Styles {
    /// Title style.
    pub title: Style,
    /// Title bar style.
    pub title_bar: Style,
    /// Filter prompt style.
    pub filter_prompt: Style,
    /// Filter cursor style.
    pub filter_cursor: Style,
    /// Status bar style.
    pub status_bar: Style,
    /// Status empty style.
    pub status_empty: Style,
    /// No items style.
    pub no_items: Style,
    /// Pagination style.
    pub pagination: Style,
    /// Help style.
    pub help: Style,
    /// Active pagination dot.
    pub active_pagination_dot: Style,
    /// Inactive pagination dot.
    pub inactive_pagination_dot: Style,
    /// Divider dot.
    pub divider_dot: Style,
}

impl Default for Styles {
    fn default() -> Self {
        // Match Go bubbles list.DefaultStyles() as closely as we can.
        Self {
            title_bar: Style::new().padding((0u16, 0u16, 1u16, 2u16)),
            title: Style::new()
                .background_color(Color::from("62"))
                .foreground_color(Color::from("230"))
                .padding((0u16, 1u16)),
            filter_prompt: Style::new().foreground_color(Color::from("#ECFD65")),
            filter_cursor: Style::new().foreground_color(Color::from("#EE6FF8")),
            status_bar: Style::new()
                .foreground_color(Color::from("240"))
                .padding((0u16, 0u16, 1u16, 2u16)),
            status_empty: Style::new().foreground_color(Color::from("240")),
            no_items: Style::new().foreground_color(Color::from("240")),
            pagination: Style::new().padding_left(2),
            help: Style::new()
                .foreground_color(Color::from("240"))
                .padding((1u16, 0u16, 0u16, 2u16)),
            active_pagination_dot: Style::new()
                .foreground_color(Color::from("240"))
                .set_string(""),
            inactive_pagination_dot: Style::new()
                .foreground_color(Color::from("240"))
                .set_string(""),
            divider_dot: Style::new()
                .foreground_color(Color::from("240"))
                .set_string(""),
        }
    }
}

/// Message for filter matches.
#[derive(Debug, Clone)]
pub struct FilterMatchesMsg(pub Vec<Rank>);

/// Message for status message timeout.
#[derive(Debug, Clone, Copy)]
pub struct StatusMessageTimeoutMsg;

/// List model with filtering, pagination, and more.
#[derive(Clone)]
pub struct List<I: Item, D: ItemDelegate<I>> {
    /// Title of the list.
    pub title: String,
    /// Whether to show the title.
    pub show_title: bool,
    /// Whether to show the filter input.
    pub show_filter: bool,
    /// Whether to show the status bar.
    pub show_status_bar: bool,
    /// Whether to show pagination.
    pub show_pagination: bool,
    /// Whether to show help.
    pub show_help: bool,
    /// Whether filtering is enabled.
    pub filtering_enabled: bool,
    /// Whether infinite scrolling is enabled.
    pub infinite_scrolling: bool,
    /// Singular name for items.
    pub item_name_singular: String,
    /// Plural name for items.
    pub item_name_plural: String,
    /// Key bindings.
    pub key_map: KeyMap,
    /// Styles.
    pub styles: Styles,
    /// Status message lifetime.
    pub status_message_lifetime: Duration,
    /// Whether mouse wheel scrolling is enabled.
    pub mouse_wheel_enabled: bool,
    /// Number of items to scroll per mouse wheel tick.
    pub mouse_wheel_delta: usize,
    /// Whether mouse click selection is enabled.
    pub mouse_click_enabled: bool,

    // Components
    /// Spinner for loading state.
    spinner: SpinnerModel,
    /// Paginator.
    paginator: Paginator,
    /// Help view.
    help: Help,
    /// Filter input.
    filter_input: TextInput,

    // State
    items: Vec<I>,
    filtered_indices: Vec<usize>,
    delegate: D,
    width: usize,
    height: usize,
    cursor: usize,
    filter_state: FilterState,
    show_spinner: bool,
    status_message: Option<String>,
}

impl<I: Item, D: ItemDelegate<I>> List<I, D> {
    /// Creates a new list with the given items and delegate.
    #[must_use]
    pub fn new(items: Vec<I>, delegate: D, width: usize, height: usize) -> Self {
        let items_len = items.len();
        let filtered_indices: Vec<usize> = (0..items_len).collect();

        let mut filter_input = TextInput::new();
        filter_input.prompt = "Filter: ".to_string();
        // In Go, the filter input is focused by default (even when not shown).
        filter_input.focus();

        let mut list = Self {
            // Match Go's default title.
            title: "List".to_string(),
            show_title: true,
            show_filter: true,
            show_status_bar: true,
            show_pagination: true,
            show_help: true,
            filtering_enabled: true,
            infinite_scrolling: false,
            item_name_singular: "item".to_string(),
            item_name_plural: "items".to_string(),
            key_map: KeyMap::default(),
            styles: Styles::default(),
            status_message_lifetime: Duration::from_secs(1),
            mouse_wheel_enabled: true,
            mouse_wheel_delta: 1,
            mouse_click_enabled: true,
            spinner: SpinnerModel::new(),
            paginator: Paginator::new().display_type(PaginatorType::Dots),
            help: Help::new(),
            filter_input,
            items,
            filtered_indices,
            delegate,
            width,
            height,
            cursor: 0,
            filter_state: FilterState::Unfiltered,
            show_spinner: false,
            status_message: None,
        };

        // Ensure pagination is consistent with the initial chrome configuration.
        list.update_pagination();
        list
    }

    /// Sets the title.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Enables or disables mouse wheel scrolling (builder pattern).
    #[must_use]
    pub fn mouse_wheel(mut self, enabled: bool) -> Self {
        self.mouse_wheel_enabled = enabled;
        self
    }

    /// Sets the number of items to scroll per mouse wheel tick (builder pattern).
    #[must_use]
    pub fn mouse_wheel_delta(mut self, delta: usize) -> Self {
        self.mouse_wheel_delta = delta;
        self
    }

    /// Enables or disables mouse click item selection (builder pattern).
    #[must_use]
    pub fn mouse_click(mut self, enabled: bool) -> Self {
        self.mouse_click_enabled = enabled;
        self
    }

    /// Sets the items.
    pub fn set_items(&mut self, items: Vec<I>) {
        let len = items.len();
        self.items = items;
        self.filtered_indices = (0..len).collect();
        self.paginator.set_total_pages_from_items(len);
        self.paginator.set_page(0);
        self.cursor = 0;
    }

    /// Returns the items.
    #[must_use]
    pub fn items(&self) -> &[I] {
        &self.items
    }

    /// Returns visible items based on current filter.
    #[must_use]
    pub fn visible_items(&self) -> Vec<&I> {
        self.filtered_indices
            .iter()
            .filter_map(|&i| self.items.get(i))
            .collect()
    }

    /// Returns the current cursor index in the filtered list.
    #[must_use]
    pub fn index(&self) -> usize {
        self.cursor
    }

    /// Returns the currently selected item.
    #[must_use]
    pub fn selected_item(&self) -> Option<&I> {
        self.filtered_indices
            .get(self.cursor)
            .and_then(|&i| self.items.get(i))
    }

    /// Selects an item by index.
    pub fn select(&mut self, index: usize) {
        self.cursor = index.min(self.filtered_indices.len().saturating_sub(1));
    }

    /// Moves the cursor up.
    pub fn cursor_up(&mut self) {
        if self.filtered_indices.is_empty() {
            return;
        }
        if self.cursor == 0 {
            if self.infinite_scrolling {
                self.cursor = self.filtered_indices.len() - 1;
            }
        } else {
            self.cursor -= 1;
        }
    }

    /// Moves the cursor down.
    pub fn cursor_down(&mut self) {
        if self.filtered_indices.is_empty() {
            return;
        }
        if self.cursor >= self.filtered_indices.len() - 1 {
            if self.infinite_scrolling {
                self.cursor = 0;
            }
        } else {
            self.cursor += 1;
        }
    }

    /// Returns the filter state.
    #[must_use]
    pub fn filter_state(&self) -> FilterState {
        self.filter_state
    }

    /// Returns the current filter value.
    #[must_use]
    pub fn filter_value(&self) -> String {
        self.filter_input.value()
    }

    /// Sets the filter value.
    pub fn set_filter_value(&mut self, value: &str) {
        self.filter_input.set_value(value);
        self.apply_filter();
    }

    /// Resets the filter.
    pub fn reset_filter(&mut self) {
        self.filter_input.reset();
        self.filter_state = FilterState::Unfiltered;
        self.filtered_indices = (0..self.items.len()).collect();
        self.paginator.set_total_pages_from_items(self.items.len());
        self.paginator.set_page(0);
        self.cursor = 0;
        self.update_pagination();
    }

    /// Applies the current filter.
    fn apply_filter(&mut self) {
        let term = self.filter_input.value();
        if term.is_empty() {
            self.reset_filter();
            return;
        }

        let targets: Vec<String> = self
            .items
            .iter()
            .map(|i| i.filter_value().to_string())
            .collect();
        let ranks = default_filter(&term, &targets);

        self.filtered_indices = ranks.iter().map(|r| r.index).collect();
        self.paginator
            .set_total_pages_from_items(self.filtered_indices.len());
        self.paginator.set_page(0);
        self.cursor = 0;
        self.filter_state = FilterState::FilterApplied;
        self.update_pagination();
    }

    /// Starts the spinner.
    /// Returns a message that should be passed to update to start the animation.
    pub fn start_spinner(&mut self) -> Option<Message> {
        self.show_spinner = true;
        self.update_pagination();
        Some(self.spinner.tick())
    }

    /// Stops the spinner.
    pub fn stop_spinner(&mut self) {
        self.show_spinner = false;
        self.update_pagination();
    }

    /// Returns whether the spinner is visible.
    #[must_use]
    pub fn spinner_visible(&self) -> bool {
        self.show_spinner
    }

    /// Sets a new status message.
    pub fn new_status_message(&mut self, msg: impl Into<String>) -> Option<Cmd> {
        self.status_message = Some(msg.into());
        let lifetime = self.status_message_lifetime;
        Some(Cmd::new(move || {
            std::thread::sleep(lifetime);
            Message::new(StatusMessageTimeoutMsg)
        }))
    }

    /// Returns the current status message.
    #[must_use]
    pub fn status_message(&self) -> Option<&str> {
        self.status_message.as_deref()
    }

    /// Sets the width.
    pub fn set_width(&mut self, w: usize) {
        self.width = w;
        self.help.width = w;
    }

    /// Sets the height.
    pub fn set_height(&mut self, h: usize) {
        self.height = h;
        self.update_pagination();
    }

    /// Returns the width.
    #[must_use]
    pub fn width(&self) -> usize {
        self.width
    }

    /// Returns the height.
    #[must_use]
    pub fn height(&self) -> usize {
        self.height
    }

    /// Returns a reference to the paginator.
    #[must_use]
    pub fn paginator(&self) -> &Paginator {
        &self.paginator
    }

    /// Updates pagination to match the Go bubbles list Model.updatePagination logic.
    fn update_pagination(&mut self) {
        let items_len = self.filtered_indices.len();
        let item_height = (self.delegate.height() + self.delegate.spacing()).max(1);

        // Compute available height by subtracting heights of chrome sections.
        // Note: lipgloss height of "" is 1 (matches Go lipgloss), and the Go list
        // includes sections even when they render empty strings.
        let mut avail_height = self.height;

        if self.show_title || (self.show_filter && self.filtering_enabled) {
            avail_height = avail_height.saturating_sub(lipgloss_height(&self.title_view()));
        }
        if self.show_status_bar {
            avail_height = avail_height.saturating_sub(lipgloss_height(&self.status_view()));
        }
        if self.show_pagination {
            avail_height = avail_height.saturating_sub(lipgloss_height(&self.pagination_view()));
        }
        if self.show_help {
            avail_height = avail_height.saturating_sub(lipgloss_height(&self.help_view()));
        }

        let per_page = (avail_height / item_height).max(1);

        let current_page = self.paginator.page();
        let mut paginator = self.paginator.clone().per_page(per_page);
        paginator.set_total_pages_from_items(items_len);
        let max_page = paginator.get_total_pages().saturating_sub(1);
        paginator.set_page(current_page.min(max_page));
        self.paginator = paginator;
    }

    /// Updates the list based on messages.
    pub fn update(&mut self, msg: Message) -> Option<Cmd> {
        // Handle status message timeout
        if msg.is::<StatusMessageTimeoutMsg>() {
            self.status_message = None;
            return None;
        }

        // Handle spinner updates - check for tick message first
        if self.show_spinner && msg.is::<TickMsg>() {
            return self.spinner.update(msg);
        }

        // Handle key messages
        if let Some(key) = msg.downcast_ref::<KeyMsg>() {
            let key_str = key.to_string();

            // Handle filtering state
            if self.filter_state == FilterState::Filtering {
                if matches(&key_str, &[&self.key_map.cancel_while_filtering]) {
                    self.reset_filter();
                    return None;
                }
                if matches(&key_str, &[&self.key_map.accept_while_filtering]) {
                    self.apply_filter();
                    self.filter_state = FilterState::FilterApplied;
                    self.filter_input.blur();
                    return None;
                }

                // Pass to filter input
                return self.filter_input.update(msg);
            }

            // Normal navigation
            if matches(&key_str, &[&self.key_map.cursor_up]) {
                self.cursor_up();
            } else if matches(&key_str, &[&self.key_map.cursor_down]) {
                self.cursor_down();
            } else if matches(&key_str, &[&self.key_map.next_page]) {
                self.paginator.next_page();
                // Move cursor to first item of new page
                let start = self.paginator.page() * self.paginator.get_per_page();
                self.cursor = if self.filtered_indices.is_empty() {
                    0
                } else {
                    start.min(self.filtered_indices.len() - 1)
                };
            } else if matches(&key_str, &[&self.key_map.prev_page]) {
                self.paginator.prev_page();
                let start = self.paginator.page() * self.paginator.get_per_page();
                self.cursor = if self.filtered_indices.is_empty() {
                    0
                } else {
                    start.min(self.filtered_indices.len() - 1)
                };
            } else if matches(&key_str, &[&self.key_map.goto_start]) {
                self.cursor = 0;
                self.paginator.set_page(0);
            } else if matches(&key_str, &[&self.key_map.goto_end]) {
                self.cursor = self.filtered_indices.len().saturating_sub(1);
                self.paginator
                    .set_page(self.paginator.get_total_pages().saturating_sub(1));
            } else if matches(&key_str, &[&self.key_map.filter]) && self.filtering_enabled {
                self.filter_state = FilterState::Filtering;
                self.filter_input.focus();
                self.update_pagination();
            } else if matches(&key_str, &[&self.key_map.clear_filter]) {
                self.reset_filter();
            } else if matches(&key_str, &[&self.key_map.show_full_help]) {
                self.help.show_all = true;
            } else if matches(&key_str, &[&self.key_map.close_full_help]) {
                self.help.show_all = false;
            }
        }

        // Handle mouse events
        if let Some(mouse) = msg.downcast_ref::<MouseMsg>() {
            // Only respond to press events
            if mouse.action != MouseAction::Press {
                return None;
            }

            match mouse.button {
                // Wheel scrolling moves cursor
                MouseButton::WheelUp if self.mouse_wheel_enabled => {
                    for _ in 0..self.mouse_wheel_delta {
                        self.cursor_up();
                    }
                }
                MouseButton::WheelDown if self.mouse_wheel_enabled => {
                    for _ in 0..self.mouse_wheel_delta {
                        self.cursor_down();
                    }
                }
                // Click to select item
                MouseButton::Left if self.mouse_click_enabled => {
                    // Calculate y offset for items area
                    // Title takes 1 line if shown
                    // Filter input takes 1 line if filtering
                    let mut content_start_y = 0usize;
                    if self.show_title && !self.title.is_empty() {
                        content_start_y += 1;
                    }
                    if self.show_filter && self.filter_state == FilterState::Filtering {
                        content_start_y += 1;
                    }

                    let click_y = mouse.y as usize;
                    if click_y >= content_start_y {
                        let item_height = self.delegate.height() + self.delegate.spacing();
                        let relative_y = click_y - content_start_y;
                        let item_index_in_view = relative_y / item_height.max(1);

                        // Convert to global cursor position
                        let per_page = self.paginator.get_per_page();
                        let page_start = self.paginator.page() * per_page;
                        let target_cursor = page_start + item_index_in_view;

                        // Only select if within bounds
                        if target_cursor < self.filtered_indices.len() {
                            self.cursor = target_cursor;
                        }
                    }
                }
                _ => {}
            }
        }

        None
    }

    fn title_view(&self) -> String {
        let mut view = String::new();

        // If the filter is showing, draw that. Otherwise draw the title.
        if self.show_filter && self.filter_state == FilterState::Filtering {
            view.push_str(&self.filter_input.view());
        } else if self.show_title {
            view.push_str(&self.styles.title.render(&self.title));

            // Status message (displayed in the title bar in the Go implementation).
            if self.filter_state != FilterState::Filtering
                && let Some(msg) = self.status_message.as_deref()
            {
                view.push_str("  ");
                view.push_str(msg);
            }
        }

        // Spinner (in-title, does not consume vertical space)
        if self.show_spinner {
            let spinner_view = self.spinner.view();
            // Keep this simple: append to the right with a gap if we have room.
            let gap = " ";
            if self.width > 0 {
                let current_w = lipgloss::width(&view);
                let spinner_w = lipgloss::width(&spinner_view);
                if current_w + lipgloss::width(gap) + spinner_w <= self.width {
                    view.push_str(gap);
                    view.push_str(&spinner_view);
                }
            }
        }

        if view.is_empty() {
            return view;
        }
        self.styles.title_bar.render(&view)
    }

    fn status_view(&self) -> String {
        let total_items = self.items.len();
        let visible_items = self.filtered_indices.len();

        let item_name = if visible_items == 1 {
            &self.item_name_singular
        } else {
            &self.item_name_plural
        };

        let items_display = format!("{visible_items} {item_name}");

        let mut status = String::new();
        if self.filter_state == FilterState::Filtering {
            if visible_items == 0 {
                status = self.styles.status_empty.render("Nothing matched");
            } else {
                status = items_display;
            }
        } else if total_items == 0 {
            status = self
                .styles
                .status_empty
                .render(&format!("No {}", self.item_name_plural));
        } else {
            if self.filter_state == FilterState::FilterApplied {
                let mut f = self.filter_input.value();
                f = f.trim().to_string();
                // Keep it short (Go truncates to 10 with an ellipsis).
                if f.chars().count() > 10 {
                    f = f.chars().take(10).collect::<String>() + "";
                }
                status.push('');
                status.push_str(&f);
                status.push_str("");
            }
            status.push_str(&items_display);
        }

        let num_filtered = total_items.saturating_sub(visible_items);
        if num_filtered > 0 {
            status.push_str(&self.styles.divider_dot.render(""));
            status.push_str(&format!("{num_filtered} filtered"));
        }

        self.styles.status_bar.render(&status)
    }

    fn pagination_view(&self) -> String {
        if self.paginator.get_total_pages() < 2 {
            return String::new();
        }
        self.styles.pagination.render(&self.paginator.view())
    }

    fn help_view(&self) -> String {
        let bindings: Vec<&Binding> = vec![
            &self.key_map.cursor_up,
            &self.key_map.cursor_down,
            &self.key_map.filter,
            &self.key_map.quit,
        ];
        self.styles
            .help
            .render(&self.help.short_help_view(&bindings))
    }

    fn populated_view(&self) -> String {
        if self.filtered_indices.is_empty() {
            if self.filter_state == FilterState::Filtering {
                return String::new();
            }
            return self
                .styles
                .no_items
                .render(&format!("No {}.", self.item_name_plural));
        }

        let total_visible = self.filtered_indices.len();
        let per_page = self.paginator.get_per_page();
        let (start, end) = self.paginator.get_slice_bounds(total_visible);

        let mut out = String::new();
        for (i, &item_idx) in self.filtered_indices[start..end].iter().enumerate() {
            let global_idx = start + i;
            let selected = global_idx == self.cursor;
            if let Some(item) = self.items.get(item_idx) {
                out.push_str(&self.delegate.render(item, global_idx, selected, self.width));
                if i != (end - start).saturating_sub(1) {
                    out.push_str(&"\n".repeat(self.delegate.spacing() + 1));
                }
            }
        }

        // If there aren't enough items to fill up this page, add trailing newlines
        // to fill the space where items would have been (matches Go behavior).
        let items_on_page = end.saturating_sub(start);
        if items_on_page < per_page {
            let n = (per_page - items_on_page) * (self.delegate.height() + self.delegate.spacing());
            out.push_str(&"\n".repeat(n));
        }

        out
    }

    /// Renders the list.
    #[must_use]
    pub fn view(&self) -> String {
        let mut sections: Vec<String> = Vec::new();

        if self.show_title || (self.show_filter && self.filtering_enabled) {
            sections.push(self.title_view());
        }

        sections.push(self.populated_view());

        if self.show_status_bar {
            sections.push(self.status_view());
        }

        if self.show_pagination {
            sections.push(self.pagination_view());
        }

        if self.show_help {
            sections.push(self.help_view());
        }

        sections.join("\n")
    }

    /// Initializes the list (called when used as a standalone Model).
    ///
    /// Returns `None` by default since lists are typically initialized with items.
    /// Override or use `start_spinner()` if loading items asynchronously.
    #[must_use]
    pub fn init(&self) -> Option<Cmd> {
        None
    }
}

/// Implement the Model trait for standalone bubbletea usage.
impl<I: Item, D: ItemDelegate<I>> Model for List<I, D> {
    fn init(&self) -> Option<Cmd> {
        List::init(self)
    }

    fn update(&mut self, msg: Message) -> Option<Cmd> {
        List::update(self, msg)
    }

    fn view(&self) -> String {
        List::view(self)
    }
}

// Implement Debug manually since FilterFn doesn't implement Debug
impl<I: Item + std::fmt::Debug, D: ItemDelegate<I> + std::fmt::Debug> std::fmt::Debug
    for List<I, D>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("List")
            .field("title", &self.title)
            .field("items_count", &self.items.len())
            .field("cursor", &self.cursor)
            .field("filter_state", &self.filter_state)
            .finish()
    }
}

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

    #[derive(Debug, Clone)]
    struct TestItem {
        name: String,
    }

    impl Item for TestItem {
        fn filter_value(&self) -> &str {
            &self.name
        }
    }

    fn test_items() -> Vec<TestItem> {
        vec![
            TestItem {
                name: "Apple".into(),
            },
            TestItem {
                name: "Banana".into(),
            },
            TestItem {
                name: "Cherry".into(),
            },
            TestItem {
                name: "Date".into(),
            },
        ]
    }

    #[test]
    fn test_list_new() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        assert_eq!(list.items().len(), 4);
        assert_eq!(list.index(), 0);
    }

    #[test]
    fn test_list_navigation() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        assert_eq!(list.index(), 0);

        list.cursor_down();
        assert_eq!(list.index(), 1);

        list.cursor_down();
        assert_eq!(list.index(), 2);

        list.cursor_up();
        assert_eq!(list.index(), 1);
    }

    #[test]
    fn test_list_selected_item() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        assert_eq!(list.selected_item().map(|i| i.name.as_str()), Some("Apple"));

        list.cursor_down();
        assert_eq!(
            list.selected_item().map(|i| i.name.as_str()),
            Some("Banana")
        );
    }

    #[test]
    fn test_list_filter() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        list.set_filter_value("an");

        // Should match "Banana"
        assert_eq!(list.visible_items().len(), 1);
        assert_eq!(list.visible_items()[0].name, "Banana");
    }

    #[test]
    fn test_list_reset_filter() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        list.set_filter_value("an");
        assert_eq!(list.visible_items().len(), 1);

        list.reset_filter();
        assert_eq!(list.visible_items().len(), 4);
    }

    #[test]
    fn test_cancel_filter_resets_pagination() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 10);

        list.filter_state = FilterState::Filtering;
        list.filtered_indices = vec![0];
        list.paginator
            .set_total_pages_from_items(list.filtered_indices.len());

        let key_msg = Message::new(KeyMsg::from_type(bubbletea::KeyType::Esc));
        let _ = list.update(key_msg);

        assert_eq!(list.filter_state, FilterState::Unfiltered);
        assert_eq!(list.filtered_indices.len(), list.items.len());
        // Pagination is derived from actual rendered chrome heights (Go parity).
        let per_page = list.paginator.get_per_page();
        let expected_pages = list.items.len().div_ceil(per_page);
        assert_eq!(list.paginator.get_total_pages(), expected_pages);
        assert_eq!(list.cursor, 0);
    }

    #[test]
    fn test_list_filter_state() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        assert_eq!(list.filter_state(), FilterState::Unfiltered);
    }

    #[test]
    fn test_list_infinite_scroll() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        list.infinite_scrolling = true;

        // At start, going up should wrap to end
        list.cursor_up();
        assert_eq!(list.index(), 3);

        // Going down should wrap to start
        list.cursor_down();
        assert_eq!(list.index(), 0);
    }

    #[test]
    fn test_list_status_message() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        assert!(list.status_message().is_none());

        list.new_status_message("Test message");
        assert_eq!(list.status_message(), Some("Test message"));
    }

    #[test]
    fn test_list_status_message_uses_singular_name() {
        let items = vec![TestItem {
            name: "Apple".into(),
        }];
        let mut list = List::new(items, DefaultDelegate::new(), 80, 6);
        list.item_name_singular = "fruit".to_string();
        list.item_name_plural = "fruits".to_string();

        let view = list.view();
        assert!(view.contains("1 fruit"));
    }

    #[test]
    fn test_list_apply_filter_resets_page() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 5);
        list.paginator.set_page(2);

        list.set_filter_value("a");

        assert_eq!(list.paginator.page(), 0);
    }

    #[test]
    fn test_list_reset_filter_resets_page() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 5);
        list.paginator.set_page(3);

        list.reset_filter();

        assert_eq!(list.paginator.page(), 0);
    }

    #[test]
    fn test_list_spinner() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);

        assert!(!list.spinner_visible());

        list.start_spinner();
        assert!(list.spinner_visible());

        list.stop_spinner();
        assert!(!list.spinner_visible());
    }

    #[test]
    fn test_list_view() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24).title("Fruits");

        let view = list.view();
        assert!(view.contains("Fruits"));
        assert!(view.contains("Apple"));
    }

    #[test]
    fn test_default_filter() {
        let targets = vec![
            "Apple".to_string(),
            "Banana".to_string(),
            "Cherry".to_string(),
        ];

        let ranks = default_filter("an", &targets);
        assert_eq!(ranks.len(), 1);
        assert_eq!(ranks[0].index, 1); // Banana
    }

    #[test]
    fn test_default_delegate() {
        let delegate = DefaultDelegate::new().with_height(2).with_spacing(1);
        assert_eq!(delegate.item_height, 2);
        assert_eq!(delegate.item_spacing, 1);
    }

    #[test]
    fn test_keymap_default() {
        let km = KeyMap::default();
        assert!(!km.cursor_up.get_keys().is_empty());
        assert!(!km.filter.get_keys().is_empty());
    }

    #[test]
    fn test_filter_state_display() {
        assert_eq!(FilterState::Unfiltered.to_string(), "unfiltered");
        assert_eq!(FilterState::Filtering.to_string(), "filtering");
        assert_eq!(FilterState::FilterApplied.to_string(), "filter applied");
    }

    // Model trait implementation tests

    #[test]
    fn test_model_trait_init_returns_none() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        // Use the Model trait method explicitly
        let cmd = Model::init(&list);
        assert!(cmd.is_none(), "Model::init should return None for List");
    }

    #[test]
    fn test_model_trait_view_returns_content() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24).title("Test List");
        // Use the Model trait method explicitly
        let view = Model::view(&list);
        assert!(view.contains("Test List"), "View should contain the title");
        assert!(view.contains("Apple"), "View should contain first item");
    }

    #[test]
    fn test_model_trait_update_handles_messages() {
        let mut list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        assert_eq!(list.index(), 0);

        // Create a down key message to navigate
        let key_msg = Message::new(KeyMsg {
            key_type: bubbletea::KeyType::Runes,
            runes: vec!['j'], // 'j' is mapped to cursor_down
            alt: false,
            paste: false,
        });

        // Use the Model trait method explicitly
        let _ = Model::update(&mut list, key_msg);
        assert_eq!(list.index(), 1, "Cursor should have moved down");
    }

    #[test]
    fn test_list_satisfies_model_bounds() {
        // This test verifies List can be used where Model + Send + 'static is required
        fn accepts_model<M: Model + Send + 'static>(_model: M) {}
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        accepts_model(list);
    }

    #[test]
    fn test_list_pagination_calculation() {
        // Pagination is derived from actual rendered chrome heights (Go parity).
        // Use a 1-line delegate so per-page math stays simple/deterministic.
        let delegate = DefaultDelegate::new()
            .with_show_description(false)
            .with_spacing(0)
            .with_height(1);
        let list = List::new(test_items(), delegate, 80, 10);

        let mut avail_height = list.height;
        if list.show_title || (list.show_filter && list.filtering_enabled) {
            avail_height = avail_height.saturating_sub(lipgloss_height(&list.title_view()));
        }
        if list.show_status_bar {
            avail_height = avail_height.saturating_sub(lipgloss_height(&list.status_view()));
        }
        if list.show_pagination {
            avail_height = avail_height.saturating_sub(lipgloss_height(&list.pagination_view()));
        }
        if list.show_help {
            avail_height = avail_height.saturating_sub(lipgloss_height(&list.help_view()));
        }

        let item_height = (<DefaultDelegate as ItemDelegate<TestItem>>::height(&list.delegate)
            + <DefaultDelegate as ItemDelegate<TestItem>>::spacing(&list.delegate))
        .max(1);
        let expected_per_page = (avail_height / item_height).max(1);
        assert_eq!(list.paginator().get_per_page(), expected_per_page);
    }

    #[test]
    fn test_list_paginator_accessor() {
        let list = List::new(test_items(), DefaultDelegate::new(), 80, 24);
        // Verify paginator accessor returns valid reference
        assert!(list.paginator().get_per_page() > 0);
        assert_eq!(list.paginator().page(), 0);
    }

    #[test]
    fn test_list_pagination_with_many_items() {
        let items: Vec<TestItem> = (1..=50)
            .map(|i| TestItem {
                name: format!("Item {}", i),
            })
            .collect();
        let delegate = DefaultDelegate::new()
            .with_show_description(false)
            .with_spacing(0)
            .with_height(1);
        let list = List::new(items, delegate, 80, 10);
        let per_page = list.paginator().get_per_page();
        let expected_pages = list.items.len().div_ceil(per_page);
        assert_eq!(list.paginator().get_total_pages(), expected_pages);
    }
}