lipgloss-tree 0.1.1

A tree component for terminal user interfaces, styled with Lip Gloss.
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
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! Node and tree data structures for building hierarchical content.
//!
//! This module provides the core data structures for representing tree nodes
//! and collections of children. It supports styling, filtering, and complex
//! tree operations with Go lipgloss compatibility.

use lipgloss::Style;
use std::fmt;

/// Helper trait to enable cloning boxed trait objects for Node.
///
/// This trait provides the mechanism for cloning `Box<dyn Node>` objects,
/// which is necessary for tree operations that need to duplicate node structures.
/// It's automatically implemented for any type that implements `Node + Clone`.
///
/// # Implementation Note
///
/// This trait is automatically implemented via a blanket implementation,
/// so you typically don't need to implement it manually.
pub trait CloneNode {
    /// Creates a cloned copy of this node as a boxed trait object.
    ///
    /// # Returns
    ///
    /// A new `Box<dyn Node>` containing a clone of this node.
    fn clone_node(&self) -> Box<dyn Node>;
}

impl<T> CloneNode for T
where
    T: 'static + Node + Clone,
{
    fn clone_node(&self) -> Box<dyn Node> {
        Box::new(self.clone())
    }
}

/// Trait defining a node in a tree structure.
///
/// `Node` represents an individual element in a tree that can have a value,
/// children, visibility state, and various styling options. It supports both
/// simple leaf nodes and complex tree nodes with nested children.
///
/// # Core Functionality
///
/// - **Value**: Each node has a string value that represents its content
/// - **Children**: Nodes can have child nodes forming a hierarchical structure
/// - **Visibility**: Nodes can be hidden from rendering
/// - **Styling**: Nodes support custom enumerators, indenters, and styling functions
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{Tree, Leaf, Node, Children};
///
/// // Create a simple leaf node
/// let leaf = Leaf::new("Hello", false);
/// assert_eq!(leaf.value(), "Hello");
/// assert!(!leaf.hidden());
///
/// // Create a tree node with children
/// let tree = Tree::new()
///     .root("Parent")
///     .child(vec!["Child 1".into(), "Child 2".into()]);
/// assert_eq!(tree.value(), "Parent");
/// assert_eq!(tree.children().length(), 2);
/// ```
pub trait Node: fmt::Display + CloneNode {
    /// Returns the string value of this node.
    ///
    /// The value is the textual content that will be displayed when
    /// the tree is rendered.
    ///
    /// # Returns
    ///
    /// The node's value as a `String`
    fn value(&self) -> String;

    /// Returns the children of this node.
    ///
    /// Children are returned as a boxed trait object to allow for
    /// different implementations of the `Children` trait.
    ///
    /// # Returns
    ///
    /// A `Box<dyn Children>` containing this node's children
    fn children(&self) -> Box<dyn Children>;

    /// Returns whether this node is hidden from rendering.
    ///
    /// Hidden nodes are not displayed in the tree output and are
    /// typically filtered out during rendering.
    ///
    /// # Returns
    ///
    /// `true` if the node is hidden, `false` otherwise
    fn hidden(&self) -> bool;

    /// Sets the visibility state of this node.
    ///
    /// # Arguments
    ///
    /// * `hidden` - `true` to hide the node, `false` to show it
    fn set_hidden(&mut self, hidden: bool);

    /// Updates the value of this node.
    ///
    /// # Arguments
    ///
    /// * `value` - The new string value for this node
    fn set_value(&mut self, value: String);

    // Optional per-node renderer overrides. Default to None.

    /// Returns the custom enumerator function for this node, if any.
    ///
    /// The enumerator function generates branch characters (like ├──, └──)
    /// for this specific node, overriding the default renderer behavior.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's custom enumerator function
    fn get_enumerator(&self) -> Option<&crate::Enumerator> {
        None
    }

    /// Returns the custom indenter function for this node, if any.
    ///
    /// The indenter function generates indentation strings for child content
    /// under this node, overriding the default renderer behavior.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's custom indenter function
    fn get_indenter(&self) -> Option<&crate::Indenter> {
        None
    }

    /// Returns the base item style for this node, if any.
    ///
    /// The base item style is applied to the node's content before any
    /// style functions are applied.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's base item style
    fn get_item_style(&self) -> Option<&Style> {
        None
    }

    /// Returns the base enumerator style for this node, if any.
    ///
    /// The base enumerator style is applied to the node's branch characters
    /// before any style functions are applied.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's base enumerator style
    fn get_enumerator_style(&self) -> Option<&Style> {
        None
    }

    /// Returns the item style function for this node, if any.
    ///
    /// The item style function provides dynamic styling based on the node's
    /// position and context within its parent's children.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's item style function
    fn get_item_style_func(&self) -> Option<&crate::StyleFunc> {
        None
    }

    /// Returns the enumerator style function for this node, if any.
    ///
    /// The enumerator style function provides dynamic styling for branch
    /// characters based on the node's position and context.
    ///
    /// # Returns
    ///
    /// An optional reference to the node's enumerator style function
    fn get_enumerator_style_func(&self) -> Option<&crate::StyleFunc> {
        None
    }
}

impl Clone for NodeChildren {
    fn clone(&self) -> Self {
        let mut cloned = NodeChildren::new();
        for i in 0..self.length() {
            if let Some(n) = self.at(i) {
                cloned.append(n.clone_node());
            }
        }
        cloned
    }
}

/// A filtered view of children that applies start/end bounds and optional hidden filtering.
///
/// `Slice` provides a window into a larger children collection, allowing you to
/// view only a subset of children within specified bounds. It can also optionally
/// skip hidden nodes during iteration.
///
/// # Examples
///
/// ```rust,ignore
/// // Internal usage only - not part of public API
/// let slice = Slice::new(children, 1, 5, true); // Skip hidden nodes
/// ```
#[allow(dead_code)]
struct Slice {
    /// The underlying children collection
    data: Box<dyn Children>,
    /// Starting index (inclusive)
    start: usize,
    /// Ending index (exclusive)
    end: usize,
    /// Whether to skip hidden nodes
    skip_hidden: bool,
}

#[allow(dead_code)]
impl Slice {
    /// Creates a new slice view of the given children collection.
    ///
    /// # Arguments
    ///
    /// * `data` - The underlying children collection to slice
    /// * `start` - Starting index (inclusive)
    /// * `end` - Ending index (exclusive)
    /// * `skip_hidden` - Whether to filter out hidden nodes
    ///
    /// # Returns
    ///
    /// A new `Slice` that provides a filtered view of the children
    fn new(data: Box<dyn Children>, start: usize, end: usize, skip_hidden: bool) -> Self {
        Self {
            data,
            start,
            end,
            skip_hidden,
        }
    }
}

impl Children for Slice {
    fn at(&self, index: usize) -> Option<&dyn Node> {
        let mut j = 0usize;
        let upper = self.end.min(self.data.length());
        for i in self.start..upper {
            if let Some(node) = self.data.at(i) {
                if self.skip_hidden && node.hidden() {
                    continue;
                }
                if j == index {
                    return Some(node);
                }
                j += 1;
            }
        }
        None
    }

    fn length(&self) -> usize {
        let mut count = 0usize;
        let upper = self.end.min(self.data.length());
        for i in self.start..upper {
            if let Some(node) = self.data.at(i) {
                if self.skip_hidden && node.hidden() {
                    continue;
                }
                count += 1;
            }
        }
        count
    }
}

/// Trait defining a collection of child nodes in a tree structure.
///
/// `Children` provides the interface for accessing and querying collections
/// of tree nodes. Implementations can provide different storage strategies,
/// filtering capabilities, or views of the underlying data.
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{NodeChildren, Children, Leaf, Node};
///
/// let mut children = NodeChildren::new();
/// children.append(Box::new(Leaf::new("Item 1", false)));
/// children.append(Box::new(Leaf::new("Item 2", false)));
///
/// assert_eq!(children.length(), 2);
/// assert_eq!(children.at(0).unwrap().value(), "Item 1");
/// ```
pub trait Children {
    /// Returns the node at the given index.
    ///
    /// # Arguments
    ///
    /// * `index` - The zero-based index of the desired node
    ///
    /// # Returns
    ///
    /// An optional reference to the node at the given index,
    /// or `None` if the index is out of bounds
    fn at(&self, index: usize) -> Option<&dyn Node>;

    /// Returns the total number of children in this collection.
    ///
    /// # Returns
    ///
    /// The count of child nodes as a `usize`
    fn length(&self) -> usize;
}

/// A concrete implementation of the `Children` trait using a vector of boxed nodes.
///
/// `NodeChildren` is the primary implementation for storing and managing
/// collections of tree nodes. It provides efficient access, modification,
/// and iteration over child nodes.
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{NodeChildren, Leaf, Children};
///
/// let mut children = NodeChildren::new();
/// children.append(Box::new(Leaf::new("First", false)));
/// children.append(Box::new(Leaf::new("Second", false)));
///
/// assert_eq!(children.length(), 2);
/// ```
pub struct NodeChildren {
    /// Vector storing the child nodes as boxed trait objects
    nodes: Vec<Box<dyn Node>>,
}

impl NodeChildren {
    /// Creates a new empty `NodeChildren` collection.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{NodeChildren, Children};
    ///
    /// let children = NodeChildren::new();
    /// assert_eq!(children.length(), 0);
    /// ```
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    /// Creates a `NodeChildren` collection from a vector of boxed nodes.
    ///
    /// # Arguments
    ///
    /// * `nodes` - A vector of boxed nodes to initialize the collection with
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{NodeChildren, Leaf, Children};
    ///
    /// let nodes = vec![
    ///     Box::new(Leaf::new("A", false)) as Box<dyn lipgloss_tree::Node>,
    ///     Box::new(Leaf::new("B", false)) as Box<dyn lipgloss_tree::Node>,
    /// ];
    /// let children = NodeChildren::from_nodes(nodes);
    /// assert_eq!(children.length(), 2);
    /// ```
    pub fn from_nodes(nodes: Vec<Box<dyn Node>>) -> Self {
        Self { nodes }
    }

    /// Appends a child node to the end of the collection.
    ///
    /// # Arguments
    ///
    /// * `child` - The boxed node to add to the collection
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{NodeChildren, Leaf, Children};
    ///
    /// let mut children = NodeChildren::new();
    /// children.append(Box::new(Leaf::new("New Item", false)));
    /// assert_eq!(children.length(), 1);
    /// ```
    pub fn append(&mut self, child: Box<dyn Node>) {
        self.nodes.push(child);
    }

    /// Removes and returns the child node at the given index.
    ///
    /// # Arguments
    ///
    /// * `index` - The zero-based index of the node to remove
    ///
    /// # Returns
    ///
    /// The removed node if the index was valid, or `None` if out of bounds
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{NodeChildren, Leaf, Children};
    ///
    /// let mut children = NodeChildren::new();
    /// children.append(Box::new(Leaf::new("Remove me", false)));
    ///
    /// let removed = children.remove(0);
    /// assert!(removed.is_some());
    /// assert_eq!(children.length(), 0);
    /// ```
    pub fn remove(&mut self, index: usize) -> Option<Box<dyn Node>> {
        if index < self.nodes.len() {
            Some(self.nodes.remove(index))
        } else {
            None
        }
    }

    /// Returns a mutable reference to the boxed node at the given index.
    ///
    /// This allows you to modify the node in place or replace it entirely.
    ///
    /// # Arguments
    ///
    /// * `index` - The zero-based index of the desired node
    ///
    /// # Returns
    ///
    /// A mutable reference to the boxed node, or `None` if the index is out of bounds
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{NodeChildren, Leaf, Node};
    ///
    /// let mut children = NodeChildren::new();
    /// children.append(Box::new(Leaf::new("Original", false)));
    ///
    /// if let Some(node) = children.at_mut(0) {
    ///     node.set_value("Modified".to_string());
    /// }
    /// ```
    pub fn at_mut(&mut self, index: usize) -> Option<&mut Box<dyn Node>> {
        self.nodes.get_mut(index)
    }
}

impl Default for NodeChildren {
    /// Creates a default (empty) `NodeChildren` collection.
    ///
    /// Equivalent to `NodeChildren::new()` - creates an empty collection
    /// with no child nodes.
    fn default() -> Self {
        Self::new()
    }
}

impl Children for NodeChildren {
    fn at(&self, index: usize) -> Option<&dyn Node> {
        self.nodes.get(index).map(|node| node.as_ref())
    }

    fn length(&self) -> usize {
        self.nodes.len()
    }
}

/// A terminal node in the tree that contains a value but no children.
///
/// `Leaf` represents the simplest type of tree node - one that holds a string
/// value and a visibility flag, but cannot have child nodes. This is useful
/// for representing individual items in a tree structure.
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{Leaf, Node, Children};
///
/// let leaf = Leaf::new("Hello, World!", false);
/// assert_eq!(leaf.value(), "Hello, World!");
/// assert!(!leaf.hidden());
/// assert_eq!(leaf.children().length(), 0);
///
/// println!("{}", leaf); // Outputs: Hello, World!
/// ```
#[derive(Debug, Clone)]
pub struct Leaf {
    /// The textual content of this leaf node
    value: String,
    /// Whether this leaf is hidden from rendering
    hidden: bool,
}

impl Leaf {
    /// Creates a new leaf node with the given value and visibility.
    ///
    /// # Arguments
    ///
    /// * `value` - The content for this leaf (anything convertible to String)
    /// * `hidden` - Whether this leaf should be hidden from rendering
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Leaf, Node};
    ///
    /// let visible_leaf = Leaf::new("Visible", false);
    /// let hidden_leaf = Leaf::new("Hidden", true);
    ///
    /// assert!(!visible_leaf.hidden());
    /// assert!(hidden_leaf.hidden());
    /// ```
    pub fn new(value: impl Into<String>, hidden: bool) -> Self {
        Self {
            value: value.into(),
            hidden,
        }
    }
}

impl Node for Leaf {
    fn value(&self) -> String {
        self.value.clone()
    }

    fn children(&self) -> Box<dyn Children> {
        Box::new(NodeChildren::new())
    }

    fn hidden(&self) -> bool {
        self.hidden
    }

    fn set_hidden(&mut self, hidden: bool) {
        self.hidden = hidden;
    }

    fn set_value(&mut self, value: String) {
        self.value = value;
    }

    fn get_enumerator(&self) -> Option<&crate::Enumerator> {
        None
    }

    fn get_indenter(&self) -> Option<&crate::Indenter> {
        None
    }
}

impl fmt::Display for Leaf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}

/// A tree node that can contain both a value and child nodes.
///
/// `Tree` is the main building block for creating hierarchical tree structures.
/// Unlike `Leaf` nodes, trees can have children and support advanced features
/// like custom styling, enumerators, indenters, and offset-based child filtering.
///
/// # Key Features
///
/// - **Hierarchical structure**: Can contain child nodes forming a tree
/// - **Custom styling**: Support for root, item, and enumerator styling
/// - **Custom rendering**: Override enumerators and indenters per-node
/// - **Child filtering**: Use offsets to display only a subset of children
/// - **Builder pattern**: Fluent API for easy tree construction
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::Tree;
///
/// let tree = Tree::new()
///     .root("My Project")
///     .child(vec![
///         "file1.txt".into(),
///         "file2.txt".into(),
///         Tree::new()
///             .root("subfolder")
///             .child(vec!["nested.txt".into()])
///             .into(),
///     ]);
///
/// println!("{}", tree);
/// ```
///
/// This creates a tree structure like:
/// ```text
/// My Project
/// ├── file1.txt
/// ├── file2.txt
/// ├── subfolder
/// │   └── nested.txt
/// ```
#[derive(Clone)]
pub struct Tree {
    /// The root value of this tree node
    value: String,
    /// Whether this tree node is hidden from rendering
    hidden: bool,
    /// Offset bounds [start, end] for filtering children
    offset: [usize; 2],
    /// Collection of child nodes
    children: NodeChildren,

    // Style and rendering properties
    /// Custom enumerator function for this tree
    enumerator: Option<crate::Enumerator>,
    /// Custom indenter function for this tree
    indenter: Option<crate::Indenter>,
    /// Style applied to the root value
    root_style: Option<Style>,
    /// Base style applied to all child items
    item_style: Option<Style>,
    /// Base style applied to all enumerators
    enumerator_style: Option<Style>,
    /// Dynamic styling function for items
    item_style_func: Option<crate::StyleFunc>,
    /// Dynamic styling function for enumerators
    enumerator_style_func: Option<crate::StyleFunc>,
}

impl Tree {
    /// Creates a new empty tree with default settings.
    ///
    /// The tree starts with no root value, no children, and default
    /// rendering settings.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Node, Children};
    ///
    /// let tree = Tree::new();
    /// assert!(tree.value().is_empty());
    /// assert_eq!(tree.children().length(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            value: String::new(),
            hidden: false,
            offset: [0, 0],
            children: NodeChildren::new(),
            // CRITICAL FIX: Set default enumerator and indenter so trees don't inherit
            // from parent List's list_indenter. This prevents spacing conflicts when
            // trees are nested in lists with 2-space indentation.
            enumerator: Some(crate::default_enumerator),
            indenter: Some(crate::default_indenter),
            root_style: None,
            item_style: None,
            enumerator_style: None,
            item_style_func: None,
            enumerator_style_func: None,
        }
    }

    /// Sets the root value of this tree.
    ///
    /// The root value is displayed at the top of the tree when rendered.
    /// If no root is set, the tree will start directly with its children.
    ///
    /// # Arguments
    ///
    /// * `root` - The root value (anything convertible to String)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Node};
    ///
    /// let tree = Tree::new().root("My Root");
    /// assert_eq!(tree.value(), "My Root");
    /// ```
    pub fn root(mut self, root: impl Into<String>) -> Self {
        self.value = root.into();
        self
    }

    /// Sets the visibility of this tree.
    ///
    /// Hidden trees are not rendered in the output, but their children
    /// may still be visible depending on the rendering context.
    ///
    /// # Arguments
    ///
    /// * `hide` - `true` to hide this tree, `false` to show it
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Node};
    ///
    /// let hidden_tree = Tree::new().root("Hidden").hide(true);
    /// assert!(hidden_tree.hidden());
    /// ```
    pub fn hide(mut self, hide: bool) -> Self {
        self.hidden = hide;
        self
    }

    /// Sets the offset range for displaying children.
    ///
    /// This allows you to display only a subset of the tree's children,
    /// which is useful for pagination or filtering large trees.
    ///
    /// # Arguments
    ///
    /// * `start` - Starting index (inclusive) for child display
    /// * `end` - Ending index (exclusive) for child display
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["A".into(), "B".into(), "C".into(), "D".into()])
    ///     .offset(1, 3); // Will only show children B and C
    /// ```
    ///
    /// # Note
    ///
    /// If `start > end`, the values will be swapped. If `end` exceeds the
    /// number of children, it will be clamped to the children count.
    pub fn offset(mut self, start: usize, end: usize) -> Self {
        let (start, end) = if start > end {
            (end, start)
        } else {
            (start, end)
        };

        let end = if end > self.children.length() {
            self.children.length()
        } else {
            end
        };

        self.offset = [start, end];
        self
    }

    /// Adds multiple children to this tree.
    ///
    /// This method accepts a vector of boxed nodes and appends them all
    /// to the tree's children collection. It matches Go's `Child(...any)` method
    /// for API compatibility.
    ///
    /// # Arguments
    ///
    /// * `children` - A vector of boxed nodes to add as children
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Node, Children};
    ///
    /// let tree = Tree::new()
    ///     .root("Parent")
    ///     .child(vec![
    ///         "Child 1".into(),
    ///         "Child 2".into(),
    ///         Tree::new().root("Nested").into(),
    ///     ]);
    ///
    /// assert_eq!(tree.children().length(), 3);
    /// ```
    pub fn child(mut self, children: Vec<Box<dyn Node>>) -> Self {
        for child in children {
            self.children.append(child);
        }
        self
    }

    /// Adds a single child to this tree.
    ///
    /// This is a convenience method for adding one child at a time,
    /// accepting anything that can be converted into a boxed node.
    ///
    /// # Arguments
    ///
    /// * `child` - A node (or convertible value) to add as a child
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Leaf, Node, Children};
    ///
    /// let tree = Tree::new()
    ///     .root("Parent")
    ///     .add_child("String child")
    ///     .add_child(Leaf::new("Leaf child", false))
    ///     .add_child(Tree::new().root("Tree child"));
    ///
    /// assert_eq!(tree.children().length(), 3);
    /// ```
    pub fn add_child(mut self, child: impl Into<Box<dyn Node>>) -> Self {
        self.children.append(child.into());
        self
    }

    /// Sets a custom enumerator function for this tree.
    ///
    /// The enumerator generates branch characters (like ├──, └──) based on
    /// each child's position. This overrides the default enumerator for this tree.
    ///
    /// # Arguments
    ///
    /// * `enumerator` - A function that takes `(children, index)` and returns a string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    ///
    /// let tree = Tree::new()
    ///     .root("Custom")
    ///     .enumerator(|children, i| {
    ///         if i == children.length() - 1 {
    ///             "╰──".to_string()  // Rounded last branch
    ///         } else {
    ///             "├──".to_string()  // Standard branch
    ///         }
    ///     })
    ///     .child(vec!["A".into(), "B".into()]);
    /// ```
    pub fn enumerator(mut self, enumerator: crate::Enumerator) -> Self {
        self.enumerator = Some(enumerator);
        self
    }

    /// Sets a custom indenter function for this tree.
    ///
    /// The indenter generates indentation strings for nested child content.
    /// This overrides the default indenter for this tree.
    ///
    /// # Arguments
    ///
    /// * `indenter` - A function that takes `(children, index)` and returns an indentation string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    ///
    /// let tree = Tree::new()
    ///     .indenter(|children, i| {
    ///         if i == children.length() - 1 {
    ///             "    ".to_string()  // Spaces for last child
    ///         } else {
    ///             "│   ".to_string()  // Vertical line for continuing
    ///         }
    ///     });
    /// ```
    pub fn indenter(mut self, indenter: crate::Indenter) -> Self {
        self.indenter = Some(indenter);
        self
    }

    /// Sets the styling for the root value of this tree.
    ///
    /// # Arguments
    ///
    /// * `style` - The lipgloss `Style` to apply to the root
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .root("Styled Root")
    ///     .root_style(Style::new().bold(true).foreground("blue"));
    /// ```
    pub fn root_style(mut self, style: Style) -> Self {
        self.root_style = Some(style);
        self
    }

    /// Sets the base style applied to all child items.
    ///
    /// This style is applied to item content before any style functions.
    ///
    /// # Arguments
    ///
    /// * `style` - The lipgloss `Style` to apply to all items
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .item_style(Style::new().foreground("green"));
    /// ```
    pub fn item_style(mut self, style: Style) -> Self {
        self.item_style = Some(style);
        self
    }

    /// Sets the base style applied to all enumerators (branch characters).
    ///
    /// This style is applied to enumerators before any style functions.
    ///
    /// # Arguments
    ///
    /// * `style` - The lipgloss `Style` to apply to all enumerators
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .enumerator_style(Style::new().foreground("yellow"));
    /// ```
    pub fn enumerator_style(mut self, style: Style) -> Self {
        self.enumerator_style = Some(style);
        self
    }

    /// Sets a dynamic styling function for child items.
    ///
    /// The function receives the children collection and the current index,
    /// allowing for context-aware styling decisions.
    ///
    /// # Arguments
    ///
    /// * `func` - A function that takes `(children, index)` and returns a `Style`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["First".into(), "Second".into(), "Third".into()])
    ///     .item_style_func(|_children, i| {
    ///         if i % 2 == 0 {
    ///             Style::new().foreground("red")
    ///         } else {
    ///             Style::new().foreground("blue")
    ///         }
    ///     });
    /// ```
    pub fn item_style_func(mut self, func: crate::StyleFunc) -> Self {
        self.item_style_func = Some(func);
        self
    }

    /// Sets a dynamic styling function for enumerators (branch characters).
    ///
    /// The function receives the children collection and the current index,
    /// allowing for context-aware styling of branch characters.
    ///
    /// # Arguments
    ///
    /// * `func` - A function that takes `(children, index)` and returns a `Style`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Children};
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .enumerator_style_func(|children, i| {
    ///         if i == children.length() - 1 {
    ///             Style::new().foreground("red")   // Last item in red
    ///         } else {
    ///             Style::new().foreground("green") // Others in green
    ///         }
    ///     });
    /// ```
    pub fn enumerator_style_func(mut self, func: crate::StyleFunc) -> Self {
        self.enumerator_style_func = Some(func);
        self
    }

    /// Returns the custom enumerator function for this tree.
    ///
    /// The enumerator function generates branch characters (like ├──, └──) for
    /// this tree's children based on their position in the collection. This
    /// allows for custom tree rendering styles.
    ///
    /// # Returns
    ///
    /// An optional reference to the enumerator function. Returns `Some` if a
    /// custom enumerator has been set with [`Tree::enumerator`], or `None`
    /// if using the default enumerator.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    ///
    /// let tree = Tree::new()
    ///     .enumerator(|children, i| {
    ///         if i == children.length() - 1 {
    ///             "└──".to_string()
    ///         } else {
    ///             "├──".to_string()
    ///         }
    ///     });
    ///
    /// assert!(tree.get_enumerator().is_some());
    /// ```
    pub fn get_enumerator(&self) -> Option<&crate::Enumerator> {
        self.enumerator.as_ref()
    }

    /// Returns the custom indenter function for this tree.
    ///
    /// The indenter function generates indentation strings for nested content
    /// under this tree's children. This determines how deeply nested items
    /// are visually offset in the rendered output.
    ///
    /// # Returns
    ///
    /// An optional reference to the indenter function. Returns `Some` if a
    /// custom indenter has been set with [`Tree::indenter`], or `None`
    /// if using the default indenter.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    ///
    /// let tree = Tree::new()
    ///     .indenter(|children, i| {
    ///         if i == children.length() - 1 {
    ///             "    ".to_string()  // Spaces for last child
    ///         } else {
    ///             "│   ".to_string()  // Vertical line continuing
    ///         }
    ///     });
    ///
    /// assert!(tree.get_indenter().is_some());
    /// ```
    pub fn get_indenter(&self) -> Option<&crate::Indenter> {
        self.indenter.as_ref()
    }

    /// Returns the styling configuration for this tree's root value.
    ///
    /// The root style is applied to the tree's main value when rendered,
    /// allowing for custom colors, formatting, and visual effects on the
    /// top-level tree node.
    ///
    /// # Returns
    ///
    /// An optional reference to the root style. Returns `Some` if a custom
    /// style has been set with [`Tree::root_style`], or `None` if using
    /// the default (unstyled) appearance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .root("Project Root")
    ///     .root_style(Style::new().bold(true).foreground("blue"));
    ///
    /// assert!(tree.get_root_style().is_some());
    /// ```
    pub fn get_root_style(&self) -> Option<&Style> {
        self.root_style.as_ref()
    }

    /// Returns the dynamic styling function for this tree's child items.
    ///
    /// The item style function provides context-aware styling based on each
    /// child's position within the tree. It receives the children collection
    /// and the current child's index, allowing for complex styling logic.
    ///
    /// # Returns
    ///
    /// An optional reference to the item style function. Returns `Some` if a
    /// custom function has been set with [`Tree::item_style_func`], or `None`
    /// if using the default (no dynamic styling).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .item_style_func(|_children, i| {
    ///         if i % 2 == 0 {
    ///             Style::new().foreground("red")
    ///         } else {
    ///             Style::new().foreground("blue")
    ///         }
    ///     });
    ///
    /// assert!(tree.get_item_style_func().is_some());
    /// ```
    pub fn get_item_style_func(&self) -> Option<&crate::StyleFunc> {
        self.item_style_func.as_ref()
    }

    /// Returns the dynamic styling function for this tree's branch characters.
    ///
    /// The enumerator style function provides context-aware styling for the
    /// branch characters (like ├──, └──) based on each child's position. It
    /// receives the children collection and current index for styling decisions.
    ///
    /// # Returns
    ///
    /// An optional reference to the enumerator style function. Returns `Some`
    /// if a custom function has been set with [`Tree::enumerator_style_func`],
    /// or `None` if using the default (no dynamic styling).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Tree, Children};
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["First".into(), "Last".into()])
    ///     .enumerator_style_func(|children, i| {
    ///         if i == children.length() - 1 {
    ///             Style::new().foreground("red")    // Last item
    ///         } else {
    ///             Style::new().foreground("green")  // Others
    ///         }
    ///     });
    ///
    /// assert!(tree.get_enumerator_style_func().is_some());
    /// ```
    pub fn get_enumerator_style_func(&self) -> Option<&crate::StyleFunc> {
        self.enumerator_style_func.as_ref()
    }

    /// Returns the base styling configuration for this tree's child items.
    ///
    /// The item style is applied to all child item content before any
    /// dynamic style functions are applied. This provides a consistent
    /// base appearance for all children in the tree.
    ///
    /// # Returns
    ///
    /// An optional reference to the base item style. Returns `Some` if a
    /// custom style has been set with [`Tree::item_style`], or `None`
    /// if using the default (unstyled) appearance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .item_style(Style::new().foreground("green").italic(true));
    ///
    /// assert!(tree.get_item_style().is_some());
    /// ```
    pub fn get_item_style(&self) -> Option<&Style> {
        self.item_style.as_ref()
    }

    /// Returns the base styling configuration for this tree's branch characters.
    ///
    /// The enumerator style is applied to all branch characters (like ├──, └──)
    /// before any dynamic style functions are applied. This provides consistent
    /// base styling for all tree branch elements.
    ///
    /// # Returns
    ///
    /// An optional reference to the base enumerator style. Returns `Some` if a
    /// custom style has been set with [`Tree::enumerator_style`], or `None`
    /// if using the default (unstyled) appearance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::Tree;
    /// use lipgloss::Style;
    ///
    /// let tree = Tree::new()
    ///     .child(vec!["Item 1".into(), "Item 2".into()])
    ///     .enumerator_style(Style::new().foreground("yellow").bold(true));
    ///
    /// assert!(tree.get_enumerator_style().is_some());
    /// ```
    pub fn get_enumerator_style(&self) -> Option<&Style> {
        self.enumerator_style.as_ref()
    }
}

impl Default for Tree {
    /// Creates a default tree instance.
    ///
    /// Equivalent to `Tree::new()` - creates an empty tree with no root value,
    /// no children, and default rendering settings.
    fn default() -> Self {
        Self::new()
    }
}

impl Node for Tree {
    fn value(&self) -> String {
        self.value.clone()
    }

    fn children(&self) -> Box<dyn Children> {
        // Return a subset of children based on offset, cloning nodes to preserve structure
        let start = self.offset[0];
        let end = if self.offset[1] == 0 {
            self.children.length()
        } else {
            self.children.length().saturating_sub(self.offset[1])
        };

        let mut filtered_children = NodeChildren::new();
        for i in start..end.min(self.children.length()) {
            if let Some(node) = self.children.at(i) {
                if node.hidden() {
                    continue;
                }
                filtered_children.append(node.clone_node());
            }
        }
        Box::new(filtered_children)
    }

    fn hidden(&self) -> bool {
        self.hidden
    }

    fn set_hidden(&mut self, hidden: bool) {
        self.hidden = hidden;
    }

    fn set_value(&mut self, value: String) {
        self.value = value;
    }

    fn get_enumerator(&self) -> Option<&crate::Enumerator> {
        self.enumerator.as_ref()
    }

    fn get_indenter(&self) -> Option<&crate::Indenter> {
        self.indenter.as_ref()
    }

    fn get_item_style(&self) -> Option<&Style> {
        self.item_style.as_ref()
    }

    fn get_enumerator_style(&self) -> Option<&Style> {
        self.enumerator_style.as_ref()
    }

    fn get_item_style_func(&self) -> Option<&crate::StyleFunc> {
        self.item_style_func.as_ref()
    }

    fn get_enumerator_style_func(&self) -> Option<&crate::StyleFunc> {
        self.enumerator_style_func.as_ref()
    }
}

impl fmt::Display for Tree {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut renderer = crate::renderer::Renderer::new()
            .enumerator(self.enumerator.unwrap_or(crate::default_enumerator))
            .indenter(self.indenter.unwrap_or(crate::default_indenter));

        // Build a TreeStyle snapshot from this Tree and apply to renderer
        let style = crate::renderer::TreeStyle {
            enumerator_func: self
                .enumerator_style_func
                .unwrap_or(|_, _| Style::new().padding_right(1)),
            item_func: self.item_style_func.unwrap_or(|_, _| Style::new()),
            root: self.root_style.clone().unwrap_or_default(),
            enumerator_base: self.enumerator_style.clone(),
            item_base: self.item_style.clone(),
        };
        renderer = renderer.style(style);

        let output = renderer.render(self, true, "");
        write!(f, "{}", output)
    }
}

// Direct conversions to Box<dyn Node> for the simplified API
impl From<&str> for Box<dyn Node> {
    fn from(s: &str) -> Self {
        Box::new(Leaf::new(s.to_string(), false))
    }
}

impl From<String> for Box<dyn Node> {
    fn from(s: String) -> Self {
        Box::new(Leaf::new(s, false))
    }
}

impl From<Tree> for Box<dyn Node> {
    fn from(tree: Tree) -> Self {
        Box::new(tree)
    }
}

impl From<Leaf> for Box<dyn Node> {
    fn from(leaf: Leaf) -> Self {
        Box::new(leaf)
    }
}

/// Creates a new tree with the specified root value.
///
/// This is a convenience function equivalent to `Tree::new().root(root)`.
///
/// # Arguments
///
/// * `root` - The root value for the tree (anything convertible to String)
///
/// # Returns
///
/// A new `Tree` instance with the specified root value
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{root, Node, Children};
///
/// let tree = root("My Project")
///     .child(vec!["file1.txt".into(), "file2.txt".into()]);
///
/// assert_eq!(tree.value(), "My Project");
/// assert_eq!(tree.children().length(), 2);
/// ```
pub fn root(root: impl Into<String>) -> Tree {
    Tree::new().root(root)
}

/// Creates a `NodeChildren` collection from string slice data.
///
/// This is a convenience function for quickly creating a collection of
/// leaf nodes from string data. Each string becomes a visible leaf node.
///
/// # Arguments
///
/// * `data` - A slice of string references to convert into leaf nodes
///
/// # Returns
///
/// A `NodeChildren` collection containing a leaf node for each string
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{new_string_data, Children, Node};
///
/// let children = new_string_data(&["Item 1", "Item 2", "Item 3"]);
/// assert_eq!(children.length(), 3);
/// assert_eq!(children.at(0).unwrap().value(), "Item 1");
/// ```
pub fn new_string_data(data: &[&str]) -> NodeChildren {
    let mut result = NodeChildren::new();
    for &item in data {
        result.append(Box::new(Leaf::new(item, false)));
    }
    result
}

/// A filtered view of children that applies a predicate function.
///
/// `Filter` wraps a children collection and applies a filtering function
/// to determine which children should be visible. Only children that pass
/// the filter predicate are accessible through the `Children` interface.
///
/// # Examples
///
/// ```rust
/// use lipgloss_tree::{Filter, new_string_data, Children};
///
/// let data = new_string_data(&["A", "B", "C", "D"]);
/// let filtered = Filter::new(Box::new(data))
///     .filter(|i| i % 2 == 0); // Only even indices
///
/// assert_eq!(filtered.length(), 2); // Only "A" and "C" are visible
/// ```
pub struct Filter {
    /// The underlying children collection to filter
    data: Box<dyn Children>,
    /// Optional predicate function for filtering
    filter: Option<Box<dyn Fn(usize) -> bool>>,
}

impl Filter {
    /// Creates a new filter with no filtering applied.
    ///
    /// Initially, all children from the underlying data will be visible.
    /// Use the `filter()` method to apply filtering logic.
    ///
    /// # Arguments
    ///
    /// * `data` - The children collection to wrap and filter
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Filter, new_string_data, Children};
    ///
    /// let data = new_string_data(&["Item 1", "Item 2"]);
    /// let filter = Filter::new(Box::new(data));
    /// assert_eq!(filter.length(), 2); // No filtering applied yet
    /// ```
    pub fn new(data: Box<dyn Children>) -> Self {
        Self { data, filter: None }
    }

    /// Sets the filtering predicate function.
    ///
    /// The function receives the index of each child in the underlying
    /// collection and should return `true` for children that should be
    /// visible, `false` for children that should be hidden.
    ///
    /// # Arguments
    ///
    /// * `f` - A predicate function that takes an index and returns a boolean
    ///
    /// # Examples
    ///
    /// ```rust
    /// use lipgloss_tree::{Filter, new_string_data, Children, Node};
    ///
    /// let data = new_string_data(&["A", "B", "C", "D", "E"]);
    /// let filtered = Filter::new(Box::new(data))
    ///     .filter(|i| i >= 2); // Only show items at index 2 and higher
    ///
    /// assert_eq!(filtered.length(), 3); // "C", "D", "E"
    /// assert_eq!(filtered.at(0).unwrap().value(), "C");
    /// ```
    pub fn filter<F>(mut self, f: F) -> Self
    where
        F: Fn(usize) -> bool + 'static,
    {
        self.filter = Some(Box::new(f));
        self
    }
}

impl Children for Filter {
    fn at(&self, index: usize) -> Option<&dyn Node> {
        if let Some(ref filter_func) = self.filter {
            let mut j = 0;
            for i in 0..self.data.length() {
                if filter_func(i) {
                    if j == index {
                        return self.data.at(i);
                    }
                    j += 1;
                }
            }
            None
        } else {
            self.data.at(index)
        }
    }

    fn length(&self) -> usize {
        if let Some(ref filter_func) = self.filter {
            let mut count = 0;
            for i in 0..self.data.length() {
                if filter_func(i) {
                    count += 1;
                }
            }
            count
        } else {
            self.data.length()
        }
    }
}