crabular 0.7.0

A high-performance ASCII table library for Rust
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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
use crate::alignment::Alignment;
use crate::cell::Cell;
use crate::constraint::WidthConstraint;
use crate::padding::Padding;
use crate::row::Row;
use crate::style::{BorderChars, TableStyle};
use crate::vertical_alignment::VerticalAlignment;
use core::cell::RefCell;

pub struct Table {
    rows: Vec<Row>,
    headers: Option<Row>,
    style: TableStyle,
    constraints: Vec<WidthConstraint>,
    padding: Padding,
    column_spacing: usize,
    column_alignments: Vec<Alignment>,
    vertical_alignment: VerticalAlignment,
    truncate: Option<usize>,
    /// Cached column widths for repeated renders.
    /// Uses interior mutability to allow caching in `&self` methods.
    cached_widths: RefCell<Option<Vec<usize>>>,
}

impl Table {
    #[must_use]
    pub fn new() -> Self {
        Self {
            rows: Vec::new(),
            headers: None,
            style: TableStyle::Classic,
            constraints: Vec::new(),
            padding: Padding::default(),
            column_spacing: 1,
            column_alignments: Vec::new(),
            vertical_alignment: VerticalAlignment::Top,
            truncate: None,
            cached_widths: RefCell::new(None),
        }
    }

    /// Invalidates the cached column widths.
    fn invalidate_cache(&self) {
        *self.cached_widths.borrow_mut() = None;
    }

    pub fn set_headers<R: Into<Row>>(&mut self, headers: R) {
        let row = headers.into();
        let row = if let Some(limit) = self.truncate {
            Self::truncate_row(&row, limit)
        } else {
            row
        };
        self.headers = Some(row);
        self.invalidate_cache();
    }

    pub fn add_row<R: Into<Row>>(&mut self, row: R) {
        let row = row.into();
        let row = if let Some(limit) = self.truncate {
            Self::truncate_row(&row, limit)
        } else {
            row
        };
        self.rows.push(row);
        self.invalidate_cache();
    }

    pub fn insert_row<R: Into<Row>>(&mut self, index: usize, row: R) {
        let row = row.into();
        let row = if let Some(limit) = self.truncate {
            Self::truncate_row(&row, limit)
        } else {
            row
        };
        self.rows.insert(index, row);
        self.invalidate_cache();
    }

    pub fn remove_row(&mut self, index: usize) -> Option<Row> {
        if index < self.rows.len() {
            self.invalidate_cache();
            Some(self.rows.remove(index))
        } else {
            None
        }
    }

    /// Sorts the rows by the content of the specified column in ascending order.
    /// Uses lexicographic (string) comparison.
    pub fn sort(&mut self, column: usize) {
        self.rows.sort_by(|a, b| {
            let a_content = a.cells().get(column).map_or("", Cell::content);
            let b_content = b.cells().get(column).map_or("", Cell::content);
            a_content.cmp(b_content)
        });
    }

    /// Sorts the rows by the content of the specified column in descending order.
    /// Uses lexicographic (string) comparison.
    pub fn sort_desc(&mut self, column: usize) {
        self.rows.sort_by(|a, b| {
            let a_content = a.cells().get(column).map_or("", Cell::content);
            let b_content = b.cells().get(column).map_or("", Cell::content);
            b_content.cmp(a_content)
        });
    }

    /// Sorts the rows by the specified column, treating cell content as numbers.
    /// Non-numeric values are treated as 0.0.
    ///
    /// This method pre-parses numeric values before sorting for better performance
    /// on large tables.
    pub fn sort_num(&mut self, column: usize) {
        // Pre-parse numeric values to avoid repeated parsing during sort
        let parsed: Vec<f64> = self
            .rows
            .iter()
            .map(|row| {
                row.cells()
                    .get(column)
                    .and_then(|c| c.content().parse().ok())
                    .unwrap_or(0.0)
            })
            .collect();

        // Create indices and sort by parsed values
        let mut indices: Vec<usize> = (0..self.rows.len()).collect();
        indices.sort_by(|&a, &b| {
            parsed[a]
                .partial_cmp(&parsed[b])
                .unwrap_or(core::cmp::Ordering::Equal)
        });

        // Reorder rows using the sorted indices
        let mut sorted_rows = Vec::with_capacity(self.rows.len());
        for idx in indices {
            sorted_rows.push(core::mem::take(&mut self.rows[idx]));
        }
        self.rows = sorted_rows;
    }

    /// Sorts the rows by the specified column in descending order, treating content as numbers.
    /// Non-numeric values are treated as 0.0.
    ///
    /// This method pre-parses numeric values before sorting for better performance
    /// on large tables.
    pub fn sort_num_desc(&mut self, column: usize) {
        // Pre-parse numeric values to avoid repeated parsing during sort
        let parsed: Vec<f64> = self
            .rows
            .iter()
            .map(|row| {
                row.cells()
                    .get(column)
                    .and_then(|c| c.content().parse().ok())
                    .unwrap_or(0.0)
            })
            .collect();

        // Create indices and sort by parsed values (descending)
        let mut indices: Vec<usize> = (0..self.rows.len()).collect();
        indices.sort_by(|&a, &b| {
            parsed[b]
                .partial_cmp(&parsed[a])
                .unwrap_or(core::cmp::Ordering::Equal)
        });

        // Reorder rows using the sorted indices
        let mut sorted_rows = Vec::with_capacity(self.rows.len());
        for idx in indices {
            sorted_rows.push(core::mem::take(&mut self.rows[idx]));
        }
        self.rows = sorted_rows;
    }

    /// Sorts the rows using a custom comparison function.
    pub fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Row, &Row) -> core::cmp::Ordering,
    {
        self.rows.sort_by(compare);
    }

    /// Filters rows in place, keeping only those for which the predicate returns true.
    /// Headers are not affected by filtering.
    pub fn filter<F>(&mut self, predicate: F)
    where
        F: FnMut(&Row) -> bool,
    {
        self.rows.retain(predicate);
    }

    /// Filters rows by the content of a specific column.
    /// Keeps rows where the column content equals the given value.
    pub fn filter_eq(&mut self, column: usize, value: &str) {
        self.rows.retain(|row| {
            row.cells()
                .get(column)
                .is_some_and(|cell| cell.content() == value)
        });
    }

    /// Filters rows by the content of a specific column using a predicate.
    /// Keeps rows where the predicate returns true for the column content.
    pub fn filter_col<F>(&mut self, column: usize, predicate: F)
    where
        F: Fn(&str) -> bool,
    {
        self.rows.retain(|row| {
            row.cells()
                .get(column)
                .is_some_and(|cell| predicate(cell.content()))
        });
    }

    /// Filters rows where the specified column content contains the given substring.
    pub fn filter_has(&mut self, column: usize, substring: &str) {
        self.rows.retain(|row| {
            row.cells()
                .get(column)
                .is_some_and(|cell| cell.content().contains(substring))
        });
    }

    /// Returns a new table containing only rows that match the predicate.
    /// The original table is not modified. Headers, style, and other settings are copied.
    #[must_use]
    pub fn filtered<F>(&self, mut predicate: F) -> Self
    where
        F: FnMut(&Row) -> bool,
    {
        Self {
            rows: self.rows.iter().filter(|r| predicate(r)).cloned().collect(),
            headers: self.headers.clone(),
            style: self.style,
            constraints: self.constraints.clone(),
            padding: self.padding,
            column_spacing: self.column_spacing,
            column_alignments: self.column_alignments.clone(),
            vertical_alignment: self.vertical_alignment,
            truncate: self.truncate,
            cached_widths: RefCell::new(None),
        }
    }

    /// Adds a new column to the table with the given values.
    /// The first value becomes the header (if headers exist), and the rest become row values.
    /// If there are more rows than values, empty cells are added.
    /// If there are more values than rows, extra values are ignored.
    pub fn add_column(&mut self, values: &[&str], alignment: Alignment) {
        let mut value_iter = values.iter();

        // Add to headers if they exist
        if let Some(ref mut headers) = self.headers {
            let content = value_iter.next().copied().unwrap_or("");
            headers.push(Cell::new(content, alignment));
        }

        // Add to each row
        for row in &mut self.rows {
            let content = value_iter.next().copied().unwrap_or("");
            row.push(Cell::new(content, alignment));
        }

        // Extend column alignments to include the new column
        self.column_alignments.push(alignment);
    }

    /// Inserts a new column at the specified index.
    /// The first value becomes the header (if headers exist), and the rest become row values.
    pub fn insert_column(&mut self, index: usize, values: &[&str], alignment: Alignment) {
        let mut value_iter = values.iter();

        // Insert into headers if they exist
        if let Some(ref mut headers) = self.headers {
            let content = value_iter.next().copied().unwrap_or("");
            headers.insert(index, Cell::new(content, alignment));
        }

        // Insert into each row
        for row in &mut self.rows {
            let content = value_iter.next().copied().unwrap_or("");
            row.insert(index, Cell::new(content, alignment));
        }

        // Shift constraints if needed
        if index < self.constraints.len() {
            self.constraints.insert(index, WidthConstraint::Auto);
        }

        // Shift column alignments if needed
        if index < self.column_alignments.len() {
            self.column_alignments.insert(index, alignment);
        }
    }

    /// Removes a column at the specified index from all rows and headers.
    /// Returns true if the column was removed, false if the index was out of bounds.
    pub fn remove_column(&mut self, index: usize) -> bool {
        let mut removed = false;

        // Remove from headers if they exist
        if let Some(ref mut headers) = self.headers
            && headers.remove(index).is_some()
        {
            removed = true;
        }

        // Remove from each row
        for row in &mut self.rows {
            if row.remove(index).is_some() {
                removed = true;
            }
        }

        // Remove constraint if it exists
        if index < self.constraints.len() {
            self.constraints.remove(index);
        }

        // Remove column alignment if it exists
        if index < self.column_alignments.len() {
            self.column_alignments.remove(index);
        }

        removed
    }

    /// Returns the number of columns in the table.
    /// Based on the maximum cell count across headers and all rows.
    #[must_use]
    pub fn cols(&self) -> usize {
        let header_cols = self.headers.as_ref().map_or(0, Row::len);
        let row_cols = self.rows.iter().map(Row::len).max().unwrap_or(0);
        header_cols.max(row_cols)
    }

    pub fn set_style(&mut self, style: TableStyle) {
        self.style = style;
    }

    pub fn set_padding(&mut self, padding: Padding) {
        self.padding = padding;
    }

    pub fn spacing(&mut self, spacing: usize) {
        self.column_spacing = spacing;
    }

    pub fn align(&mut self, column: usize, alignment: Alignment) {
        if column >= self.column_alignments.len() {
            self.column_alignments.resize(column + 1, Alignment::Left);
        }
        self.column_alignments[column] = alignment;
    }

    pub fn valign(&mut self, alignment: VerticalAlignment) {
        self.vertical_alignment = alignment;
    }

    pub fn constrain(&mut self, constraint: WidthConstraint) {
        self.constraints.push(constraint);
    }

    pub fn set_constraint(&mut self, column: usize, constraint: WidthConstraint) {
        if column >= self.constraints.len() {
            self.constraints.resize(column + 1, WidthConstraint::Auto);
        }
        self.constraints[column] = constraint;
    }

    #[must_use]
    pub fn constraints(&self) -> &[WidthConstraint] {
        &self.constraints
    }

    #[must_use]
    pub fn rows(&self) -> &[Row] {
        &self.rows
    }

    #[must_use]
    pub fn headers(&self) -> Option<&Row> {
        self.headers.as_ref()
    }

    #[must_use]
    pub fn style(&self) -> TableStyle {
        self.style
    }

    #[must_use]
    pub fn padding(&self) -> Padding {
        self.padding
    }

    #[must_use]
    pub fn get_spacing(&self) -> usize {
        self.column_spacing
    }

    #[must_use]
    pub fn get_align(&self, column: usize) -> Option<Alignment> {
        self.column_alignments.get(column).copied()
    }

    #[must_use]
    pub fn get_valign(&self) -> VerticalAlignment {
        self.vertical_alignment
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty() && self.headers.is_none()
    }

    #[must_use]
    pub fn row<R: Into<Row>>(mut self, cells: R) -> Self {
        self.add_row(cells.into());
        self
    }

    #[must_use]
    pub fn header<R: Into<Row>>(mut self, headers: R) -> Self {
        self.set_headers(headers);
        self
    }

    #[must_use]
    pub fn truncate(mut self, limit: usize) -> Self {
        self.truncate = Some(limit);
        self
    }

    fn truncate_row(row: &Row, limit: usize) -> Row {
        let mut new_row = Row::new();
        for cell in row.cells() {
            let content = cell.content();
            let truncated = if content.len() > limit {
                if limit > 3 {
                    format!("{}...", &content[..limit - 3])
                } else {
                    content[..limit].to_string()
                }
            } else {
                content.to_string()
            };
            new_row.push(Cell::new(&truncated, cell.alignment()));
        }
        new_row
    }

    pub fn print(&self) {
        print!("{}", self.render());
    }

    /// Renders the table into a provided byte buffer, reusing the allocation.
    ///
    /// This method allows for zero-allocation rendering when the buffer is reused
    /// across multiple renders, making it ideal for repeated rendering scenarios
    /// like pagination or filtering UI.
    ///
    /// # Arguments
    /// * `buf` - A buffer to render into. Will be cleared and reused.
    ///
    /// # Returns
    /// * `Ok(())` if rendering succeeded
    ///
    /// # Errors
    /// This function currently never returns an error, but returns `Result` for
    /// future compatibility with potential I/O operations.
    ///
    /// # Examples
    /// ```ignore
    /// let mut buffer = Vec::with_capacity(4096);
    /// for item in items {
    ///     buffer.clear();
    ///     table.render_into(&mut buffer)?;
    ///     stdout.write_all(&buffer)?;
    /// }
    /// ```
    pub fn render_into(&self, buf: &mut Vec<u8>) -> core::fmt::Result {
        buf.clear();
        let rendered = self.render();
        buf.extend_from_slice(rendered.as_bytes());
        Ok(())
    }

    /// Formats a cell's content with the given width and alignment.
    ///
    /// This is a lower-level function that can be useful for custom formatting needs.
    ///
    /// # Arguments
    /// * `content` - The cell content to format
    /// * `width` - The target width for the formatted output
    /// * `alignment` - The alignment to use
    ///
    /// # Returns
    /// The formatted string with appropriate padding
    ///
    /// # Examples
    /// ```
    /// # use crabular::{Table, Alignment};
    /// let formatted = Table::format_cell("test", 10, Alignment::Left);
    /// assert_eq!(formatted, "test      ");
    /// ```
    #[must_use]
    pub fn format_cell(content: &str, width: usize, alignment: Alignment) -> String {
        let content_len = content.chars().count();

        if content_len > width {
            return if width > 3 {
                let truncated: String = content.chars().take(width - 3).collect();
                format!("{truncated}...")
            } else {
                ".".repeat(width)
            };
        }

        if content_len == width {
            return content.to_string();
        }

        // Optimized version: pre-allocate and use push_str() instead of format!
        let padding = width - content_len;
        let mut result = String::with_capacity(width);

        match alignment {
            Alignment::Left => {
                result.push_str(content);
                for _ in 0..padding {
                    result.push(' ');
                }
            }
            Alignment::Right => {
                for _ in 0..padding {
                    result.push(' ');
                }
                result.push_str(content);
            }
            Alignment::Center => {
                let left = padding / 2;
                let right = padding - left;
                for _ in 0..left {
                    result.push(' ');
                }
                result.push_str(content);
                for _ in 0..right {
                    result.push(' ');
                }
            }
        }

        result
    }

    pub(crate) fn wrap_text(text: &str, width: usize) -> Vec<String> {
        if text.is_empty() || width == 0 {
            return vec![String::new()];
        }

        if text.chars().count() <= width {
            return vec![text.to_string()];
        }

        let mut lines = Vec::new();
        let mut current_line = String::with_capacity(width);
        let mut current_char_count = 0;

        // Iterate directly over split_whitespace() without collecting into Vec
        for word in text.split_whitespace() {
            let word_char_count = word.chars().count();

            if current_char_count == 0 {
                // Starting a new line
                if word_char_count > width {
                    Self::wrap_long_word(word, width, &mut lines);
                } else {
                    current_line.push_str(word);
                    current_char_count = word_char_count;
                }
            } else {
                // Continuing an existing line
                let potential_len = current_char_count + 1 + word_char_count;
                if potential_len <= width {
                    current_line.push(' ');
                    current_line.push_str(word);
                    current_char_count = potential_len;
                } else {
                    // Line is full, start a new one
                    lines.push(core::mem::take(&mut current_line));
                    current_char_count = 0;

                    if word_char_count > width {
                        Self::wrap_long_word(word, width, &mut lines);
                    } else {
                        current_line.push_str(word);
                        current_char_count = word_char_count;
                    }
                }
            }
        }

        if !current_line.is_empty() {
            lines.push(current_line);
        }

        if lines.is_empty() {
            lines.push(String::new());
        }

        lines
    }

    /// Helper to wrap a word that exceeds the column width.
    /// Breaks the word into chunks of `width` characters and appends to `lines`.
    fn wrap_long_word(word: &str, width: usize, lines: &mut Vec<String>) {
        let mut chars = word.chars().peekable();

        while chars.peek().is_some() {
            let chunk: String = chars.by_ref().take(width).collect();
            lines.push(chunk);
        }
    }

    fn calculate_column_widths(&self) -> Vec<usize> {
        let mut max_widths: Vec<usize> = Vec::new();

        if let Some(headers) = self.headers() {
            for (idx, cell) in headers.cells().iter().enumerate() {
                let width = cell.content().chars().count();
                if max_widths.len() < idx + 1 {
                    max_widths.resize(idx + 1, 0);
                }
                if width > max_widths[idx] {
                    max_widths[idx] = width;
                }
            }
        }

        for row in &self.rows {
            for (idx, cell) in row.cells().iter().enumerate() {
                let width = cell.content().chars().count();
                if max_widths.len() < idx + 1 {
                    max_widths.resize(idx + 1, 0);
                }
                if width > max_widths[idx] {
                    max_widths[idx] = width;
                }
            }
        }

        self.apply_width_constraints(&mut max_widths);
        self.apply_proportional_constraints(&mut max_widths);
        max_widths
    }

    fn apply_width_constraints(&self, widths: &mut [usize]) {
        for (i, constraint) in self.constraints.iter().enumerate() {
            if i < widths.len() {
                match constraint {
                    WidthConstraint::Fixed(w) => {
                        widths[i] = *w;
                    }
                    WidthConstraint::Min(m) => {
                        if widths[i] < *m {
                            widths[i] = *m;
                        }
                    }
                    WidthConstraint::Max(m) => {
                        if widths[i] > *m {
                            widths[i] = *m;
                        }
                    }
                    WidthConstraint::Wrap(w) => {
                        if widths[i] > *w {
                            widths[i] = *w;
                        }
                    }
                    WidthConstraint::Auto | WidthConstraint::Proportional(_) => {}
                }
            }
        }
    }

    fn apply_proportional_constraints(&self, widths: &mut [usize]) {
        let total_percentage: u8 = self
            .constraints
            .iter()
            .filter_map(|c| {
                if let WidthConstraint::Proportional(p) = c {
                    Some(*p)
                } else {
                    None
                }
            })
            .sum();

        if total_percentage == 0 || total_percentage > 100 {
            return;
        }

        let padding = self.padding.left + self.padding.right;
        let spacing = self
            .column_spacing
            .saturating_mul(widths.len().saturating_sub(1));
        let max_width: usize = 120;
        let available_width = max_width.saturating_sub(padding * widths.len() + spacing);

        let proportional_width = available_width;
        for (i, constraint) in self.constraints.iter().enumerate() {
            if i < widths.len()
                && let WidthConstraint::Proportional(percentage) = constraint
            {
                let calculated_width = (proportional_width * *percentage as usize) / 100;
                widths[i] = widths[i].max(calculated_width);
            }
        }
    }

    #[must_use]
    pub fn render(&self) -> String {
        if self.is_empty() {
            return String::new();
        }

        let column_widths = self.calculate_column_widths();
        self.render_with_widths(&column_widths)
    }

    /// Renders the table using cached column widths if available.
    ///
    /// This method provides improved performance for repeated renders of the same table.
    /// The first call calculates and caches column widths. Subsequent calls reuse the cache
    /// until the table is modified.
    ///
    /// # Returns
    /// The rendered table as a `String`
    ///
    /// # Examples
    /// ```
    /// # use crabular::{Table, Alignment};
    /// let table = Table::new().header(&["A", "B"]).row(&["1", "2"]);
    /// let _first = table.render_cached(); // Calculates and caches widths
    /// let _second = table.render_cached(); // Uses cached widths (faster)
    /// ```
    #[must_use]
    pub fn render_cached(&self) -> String {
        if self.is_empty() {
            return String::new();
        }

        // Use cached widths or calculate and cache them
        let column_widths = {
            let mut cache = self.cached_widths.borrow_mut();
            if let Some(ref widths) = *cache {
                widths.clone()
            } else {
                let widths = self.calculate_column_widths();
                *cache = Some(widths.clone());
                widths
            }
        };

        self.render_with_widths(&column_widths)
    }

    /// Internal method that renders the table with pre-calculated column widths.
    fn render_with_widths(&self, column_widths: &[usize]) -> String {
        let borders = self.style.border_chars();
        let skip_outer_borders = matches!(
            self.style,
            TableStyle::Minimal | TableStyle::Compact | TableStyle::Markdown
        );

        let num_columns = column_widths.len();
        let padding = self.padding.left + self.padding.right;

        // Pre-calculate approximate buffer size
        let row_width: usize = column_widths.iter().sum::<usize>()
            + padding * num_columns
            + self.column_spacing * num_columns.saturating_sub(1)
            + num_columns
            + 2; // border chars + newline

        let num_rows = self.len();
        let border_rows = if skip_outer_borders { 1 } else { 3 };
        let estimated_lines = num_rows + border_rows + usize::from(self.headers().is_some());
        let estimated_capacity = row_width * estimated_lines;

        let mut output = String::with_capacity(estimated_capacity);

        let boundaries_for = |row: Option<&Row>| {
            row.map_or_else(
                || Self::all_boundaries(num_columns),
                |row| Self::get_row_boundaries(row, num_columns),
            )
        };

        // Get the first row to determine top border boundaries
        let first_row = self.headers().or_else(|| self.rows.first());

        if !skip_outer_borders {
            let first_boundaries = boundaries_for(first_row);
            // For top border, only use first row boundaries (pass same for both)
            output.push_str(&Self::render_horizontal_border_with_spans(
                column_widths,
                self.padding,
                self.column_spacing,
                borders.top_left,
                borders.top_cross,
                borders.top_right,
                borders.horizontal,
                borders.top_cross,    // T-down (for top border, same as top_cross)
                borders.bottom_cross, // T-up (for top border, use bottom_cross)
                &first_boundaries,
                &first_boundaries, // Same boundaries - junction only if first row has boundary
            ));
        }

        if let Some(headers) = self.headers() {
            let header_boundaries = Self::get_row_boundaries(headers, num_columns);
            output.push_str(&self.render_row_with_wrapping(
                headers,
                column_widths,
                &borders,
                &self.column_alignments,
            ));
            if self.style == TableStyle::Markdown {
                output.push_str(&Self::render_markdown_header_separator(
                    column_widths,
                    self.padding,
                    self.column_spacing,
                ));
            } else {
                // Get first data row boundaries for the separator
                let first_data_boundaries = boundaries_for(self.rows.first());

                output.push_str(&Self::render_horizontal_border_with_spans(
                    column_widths,
                    self.padding,
                    self.column_spacing,
                    borders.left_cross,
                    borders.cross,
                    borders.right_cross,
                    borders.horizontal,
                    borders.top_cross,      // T-down (row below has boundary)
                    borders.bottom_cross,   // T-up (row above has boundary)
                    &first_data_boundaries, // Row below (first data row)
                    &header_boundaries,     // Row above (headers)
                ));
            }
        }

        for row in self.rows() {
            output.push_str(&self.render_row_with_wrapping(
                row,
                column_widths,
                &borders,
                &self.column_alignments,
            ));
        }

        if !skip_outer_borders {
            let last_row = self.rows.last().or(self.headers());
            let last_boundaries = boundaries_for(last_row);
            // For bottom border, only use last row boundaries (pass same for both)
            output.push_str(&Self::render_horizontal_border_with_spans(
                column_widths,
                self.padding,
                self.column_spacing,
                borders.bottom_left,
                borders.bottom_cross,
                borders.bottom_right,
                borders.horizontal,
                borders.top_cross,    // T-down
                borders.bottom_cross, // T-up
                &last_boundaries,     // Same boundaries - junction only if last row has boundary
                &last_boundaries,
            ));
        }

        output
    }

    /// Returns a vector indicating which column indices have a cell boundary.
    /// Index 0 and `num_columns` are always true (left and right table edges).
    fn get_row_boundaries(row: &Row, num_columns: usize) -> Vec<bool> {
        let mut boundaries = vec![false; num_columns + 1];
        boundaries[0] = true;
        boundaries[num_columns] = true;

        let mut col_idx = 0;
        for cell in row.cells() {
            if col_idx <= num_columns {
                boundaries[col_idx] = true;
            }
            col_idx += cell.span().max(1);
        }
        if col_idx <= num_columns {
            boundaries[col_idx] = true;
        }

        boundaries
    }

    /// Returns boundaries where all columns have separators (no colspan).
    fn all_boundaries(num_columns: usize) -> Vec<bool> {
        vec![true; num_columns + 1]
    }

    /// Forces recalculation of column widths on the next render.
    ///
    /// This method is primarily useful when the table has been modified externally
    /// or when you want to ensure fresh calculations.
    ///
    /// # Examples
    /// ```
    /// # use crabular::{Table, Alignment};
    /// let mut table = Table::new().header(&["A", "B"]).row(&["1", "2"]);
    /// table.recalculate_widths();
    /// ```
    pub fn recalculate_widths(&mut self) {
        self.invalidate_cache();
    }

    fn render_row_with_wrapping(
        &self,
        row: &Row,
        column_widths: &[usize],
        borders: &BorderChars,
        column_alignments: &[Alignment],
    ) -> String {
        let num_columns = column_widths.len();
        let mut wrapped_cells: Vec<Vec<String>> = Vec::with_capacity(row.len());
        let mut cell_spans: Vec<usize> = Vec::with_capacity(row.len());
        let mut max_lines = 1;

        // Build a set of column boundaries for this row
        // A boundary exists at column index `i` if a cell starts there
        let mut boundaries = vec![false; num_columns + 1];
        boundaries[0] = true; // Left edge always has boundary
        boundaries[num_columns] = true; // Right edge always has boundary

        let mut col_idx = 0;
        for cell in row.cells() {
            let span = cell.span().max(1);
            cell_spans.push(span);
            boundaries[col_idx] = true; // Cell starts here

            // Calculate combined width for spanned cells
            let combined_width = self.calculate_span_width(col_idx, span, column_widths);
            let wrap_width = self.get_wrap_width(col_idx);

            let effective_width = wrap_width.unwrap_or(combined_width);
            let lines = if cell.content().chars().count() > effective_width && wrap_width.is_some()
            {
                Self::wrap_text(cell.content(), effective_width)
            } else {
                vec![cell.content().to_string()]
            };

            max_lines = max_lines.max(lines.len());
            wrapped_cells.push(lines);

            col_idx += span;
        }
        // Mark boundary at end of last cell
        if col_idx <= num_columns {
            boundaries[col_idx] = true;
        }

        // Apply vertical alignment by calculating offset for each cell
        let aligned_cells: Vec<Vec<String>> = wrapped_cells
            .into_iter()
            .map(|cell_lines| {
                Self::apply_vertical_alignment(cell_lines, max_lines, self.vertical_alignment)
            })
            .collect();

        // Pre-calculate row line width
        let line_width: usize = column_widths.iter().sum::<usize>()
            + (self.padding.left + self.padding.right) * num_columns
            + self.column_spacing * num_columns.saturating_sub(1)
            + num_columns + 1 // border chars
            + 1; // newline

        let mut output = String::with_capacity(line_width * max_lines);

        for line_idx in 0..max_lines {
            output.push_str(borders.vertical);

            let mut col_idx = 0;
            for (cell_idx, cell_lines) in aligned_cells.iter().enumerate() {
                let span = cell_spans.get(cell_idx).copied().unwrap_or(1);
                let combined_width = self.calculate_span_width(col_idx, span, column_widths);

                let alignment = column_alignments.get(col_idx).copied().unwrap_or_else(|| {
                    row.cells()
                        .get(cell_idx)
                        .map_or(Alignment::Left, Cell::alignment)
                });

                let content = cell_lines.get(line_idx).map_or("", String::as_str);

                // Left padding
                for _ in 0..self.padding.left {
                    output.push(' ');
                }
                output.push_str(&Self::format_cell(content, combined_width, alignment));
                // Right padding
                for _ in 0..self.padding.right {
                    output.push(' ');
                }

                col_idx += span;

                // Add spacing and vertical border
                // Only add spacing if not at the last column
                if col_idx < num_columns {
                    for _ in 0..self.column_spacing {
                        output.push(' ');
                    }
                }
                output.push_str(borders.vertical);
            }
            output.push('\n');
        }

        output
    }

    /// Calculates the combined width for a cell that spans multiple columns.
    fn calculate_span_width(
        &self,
        start_col: usize,
        span: usize,
        column_widths: &[usize],
    ) -> usize {
        if span <= 1 {
            return column_widths.get(start_col).copied().unwrap_or(0);
        }

        let mut total_width = 0;
        for i in 0..span {
            let col = start_col + i;
            if col < column_widths.len() {
                total_width += column_widths[col];
                // Add padding and spacing for intermediate columns
                if i < span - 1 {
                    total_width += self.padding.left + self.padding.right + self.column_spacing + 1;
                }
            }
        }
        total_width
    }

    pub(crate) fn apply_vertical_alignment(
        cell_lines: Vec<String>,
        max_lines: usize,
        vertical_alignment: VerticalAlignment,
    ) -> Vec<String> {
        let cell_line_count = cell_lines.len();
        if cell_line_count >= max_lines {
            return cell_lines;
        }

        let padding_needed = max_lines - cell_line_count;
        let mut result = Vec::with_capacity(max_lines);

        match vertical_alignment {
            VerticalAlignment::Top => {
                result.extend(cell_lines);
                result.extend(core::iter::repeat_n(String::new(), padding_needed));
            }
            VerticalAlignment::Middle => {
                let top_padding = padding_needed / 2;
                let bottom_padding = padding_needed - top_padding;
                result.extend(core::iter::repeat_n(String::new(), top_padding));
                result.extend(cell_lines);
                result.extend(core::iter::repeat_n(String::new(), bottom_padding));
            }
            VerticalAlignment::Bottom => {
                result.extend(core::iter::repeat_n(String::new(), padding_needed));
                result.extend(cell_lines);
            }
        }

        result
    }

    fn get_wrap_width(&self, column: usize) -> Option<usize> {
        if let Some(WidthConstraint::Wrap(w)) = self.constraints.get(column) {
            return Some(*w);
        }
        None
    }

    /// Renders a horizontal border with proper handling of column spans.
    ///
    /// Uses different junction characters based on cell boundaries:
    /// - Cross (┼) when both rows have boundary
    /// - T-down (┬) when only row below has boundary
    /// - T-up (┴) when only row above has boundary
    /// - Horizontal (─) when neither has boundary
    #[allow(clippy::too_many_arguments)]
    fn render_horizontal_border_with_spans(
        column_widths: &[usize],
        padding: Padding,
        column_spacing: usize,
        left: &str,
        cross: &str,
        right: &str,
        horizontal: &str,
        cross_down: &str, // T pointing down (┬) - only row below has boundary
        cross_up: &str,   // T pointing up (┴) - only row above has boundary
        boundaries_below: &[bool],
        boundaries_above: &[bool],
    ) -> String {
        let num_columns = column_widths.len();

        // Pre-calculate line width
        let content_width: usize = column_widths.iter().sum::<usize>()
            + (padding.left + padding.right) * num_columns
            + column_spacing * num_columns.saturating_sub(1);
        let border_chars = num_columns + 1;
        let estimated_capacity = content_width + border_chars + 1;

        let mut line = String::with_capacity(estimated_capacity);

        line.push_str(left);

        // Check if horizontal is a single character for optimization
        let h_char = if horizontal.len() == 1 {
            horizontal.chars().next()
        } else {
            None
        };

        for (index, &width) in column_widths.iter().enumerate() {
            let cell_width = padding.left + width + padding.right;
            if let Some(ch) = h_char {
                for _ in 0..cell_width {
                    line.push(ch);
                }
            } else {
                for _ in 0..cell_width {
                    line.push_str(horizontal);
                }
            }

            if index < num_columns - 1 {
                // Column boundary index (between column `index` and `index + 1`)
                let boundary_idx = index + 1;
                let has_boundary_below =
                    boundaries_below.get(boundary_idx).copied().unwrap_or(true);
                let has_boundary_above =
                    boundaries_above.get(boundary_idx).copied().unwrap_or(true);

                // Determine the junction character based on boundaries
                let junction = match (has_boundary_above, has_boundary_below) {
                    (true, true) => cross,        // Both have boundary: ┼
                    (false, true) => cross_down,  // Only below: ┬
                    (true, false) => cross_up,    // Only above: ┴
                    (false, false) => horizontal, // Neither: ─ (continue horizontal)
                };

                if junction == horizontal {
                    // No boundary on both sides - continue with horizontal line
                    // Add spacing width + 1 (for the cross character position)
                    let span_width = column_spacing + 1;
                    if let Some(ch) = h_char {
                        for _ in 0..span_width {
                            line.push(ch);
                        }
                    } else {
                        for _ in 0..span_width {
                            line.push_str(horizontal);
                        }
                    }
                } else {
                    // There's a junction character to render
                    if let Some(ch) = h_char {
                        for _ in 0..column_spacing {
                            line.push(ch);
                        }
                    } else {
                        for _ in 0..column_spacing {
                            line.push_str(horizontal);
                        }
                    }
                    line.push_str(junction);
                }
            }
        }
        line.push_str(right);
        line.push('\n');

        line
    }

    fn render_markdown_header_separator(
        column_widths: &[usize],
        padding: Padding,
        column_spacing: usize,
    ) -> String {
        let num_columns = column_widths.len();
        let content_width: usize = column_widths.iter().sum::<usize>()
            + (padding.left + padding.right) * num_columns
            + column_spacing * num_columns.saturating_sub(1);
        let border_chars = num_columns + 1;
        let estimated_capacity = content_width + border_chars + 1;

        let mut line = String::with_capacity(estimated_capacity);
        line.push('|');

        for (index, &width) in column_widths.iter().enumerate() {
            let cell_width = padding.left + width + padding.right;
            if cell_width >= 2 {
                line.push('-');
                for _ in 0..cell_width.saturating_sub(2) {
                    line.push('-');
                }
                line.push('-');
            } else {
                for _ in 0..cell_width.max(1) {
                    line.push('-');
                }
            }

            if index < num_columns - 1 {
                for _ in 0..column_spacing {
                    line.push(' ');
                }
                line.push('|');
            }
        }

        line.push('|');
        line.push('\n');
        line
    }
}

impl core::fmt::Display for Table {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "{}", self.render())
    }
}

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

#[cfg(test)]
mod tests {
    use crate::{Alignment, Table, TableStyle, VerticalAlignment};

    #[test]
    fn new_is_empty() {
        let table = Table::new();
        assert!(table.is_empty());
        assert_eq!(table.len(), 0);
        assert_eq!(table.cols(), 0);
        assert!(table.headers().is_none());
    }

    #[test]
    fn default_is_empty() {
        let table = Table::default();
        assert!(table.is_empty());
    }

    #[test]
    fn default_style_is_classic() {
        let table = Table::new();
        assert_eq!(table.style(), TableStyle::Classic);
    }

    #[test]
    fn default_padding() {
        let table = Table::new();
        assert_eq!(table.padding().left, 1);
        assert_eq!(table.padding().right, 1);
    }

    #[test]
    fn default_spacing() {
        let table = Table::new();
        assert_eq!(table.get_spacing(), 1);
    }

    #[test]
    fn default_valign_is_top() {
        let table = Table::new();
        assert_eq!(table.get_valign(), VerticalAlignment::Top);
    }

    #[test]
    fn set_headers() {
        let mut table = Table::new();
        table.set_headers(["A", "B"]);
        assert!(table.headers().is_some());
        assert_eq!(table.headers().unwrap().len(), 2);
    }

    #[test]
    fn add_row() {
        let mut table = Table::new();
        table.add_row(["1", "2"]);
        assert_eq!(table.len(), 1);
        assert!(!table.is_empty());
    }

    #[test]
    fn insert_row() {
        let mut table = Table::new();
        table.add_row(["a", "1"]);
        table.add_row(["c", "3"]);
        table.insert_row(1, ["b", "2"]);
        assert_eq!(table.len(), 3);
        assert_eq!(table.rows()[1].cells()[0].content(), "b");
    }

    #[test]
    fn remove_row() {
        let mut table = Table::new();
        table.add_row(["a", "1"]);
        table.add_row(["b", "2"]);
        let removed = table.remove_row(0);
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().cells()[0].content(), "a");
        assert_eq!(table.len(), 1);
    }

    #[test]
    fn remove_row_out_of_bounds() {
        let mut table = Table::new();
        table.add_row(["a"]);
        assert!(table.remove_row(5).is_none());
    }

    #[test]
    fn cols() {
        let table = Table::new().header(["A", "B", "C"]).row(["1", "2", "3"]);
        assert_eq!(table.cols(), 3);
    }

    #[test]
    fn fluent_api() {
        let table = Table::new()
            .header(["ID", "Value"])
            .row(["1", "100"])
            .row(["2", "200"]);
        assert_eq!(table.len(), 2);
        assert!(table.headers().is_some());
    }

    // Sorting tests
    #[test]
    fn sort_ascending() {
        let mut table = Table::new();
        table.add_row(["Squidward"]);
        table.add_row(["Kelana"]);
        table.add_row(["Kata"]);
        table.sort(0);
        assert_eq!(table.rows()[0].cells()[0].content(), "Kata");
        assert_eq!(table.rows()[1].cells()[0].content(), "Kelana");
        assert_eq!(table.rows()[2].cells()[0].content(), "Squidward");
    }

    #[test]
    fn sort_descending() {
        let mut table = Table::new();
        table.add_row(["Kelana"]);
        table.add_row(["Squidward"]);
        table.sort_desc(0);
        assert_eq!(table.rows()[0].cells()[0].content(), "Squidward");
        assert_eq!(table.rows()[1].cells()[0].content(), "Kelana");
    }

    #[test]
    fn sort_num_ascending() {
        let mut table = Table::new();
        table.add_row(["100"]);
        table.add_row(["25"]);
        table.add_row(["50"]);
        table.sort_num(0);
        assert_eq!(table.rows()[0].cells()[0].content(), "25");
        assert_eq!(table.rows()[1].cells()[0].content(), "50");
        assert_eq!(table.rows()[2].cells()[0].content(), "100");
    }

    #[test]
    fn sort_num_descending() {
        let mut table = Table::new();
        table.add_row(["25"]);
        table.add_row(["100"]);
        table.sort_num_desc(0);
        assert_eq!(table.rows()[0].cells()[0].content(), "100");
        assert_eq!(table.rows()[1].cells()[0].content(), "25");
    }

    #[test]
    fn sort_preserves_headers() {
        let mut table = Table::new();
        table.set_headers(["Name"]);
        table.add_row(["Squidward"]);
        table.add_row(["Kelana"]);
        table.sort(0);
        assert_eq!(table.headers().unwrap().cells()[0].content(), "Name");
    }

    // Filter tests
    #[test]
    fn filter() {
        let mut table = Table::new();
        table.add_row(["Kelana", "25"]);
        table.add_row(["Kata", "30"]);
        table.add_row(["Squidward", "25"]);
        table.filter(|row| row.cells()[1].content() == "25");
        assert_eq!(table.len(), 2);
    }

    #[test]
    fn filter_eq() {
        let mut table = Table::new();
        table.add_row(["Active"]);
        table.add_row(["Inactive"]);
        table.add_row(["Active"]);
        table.filter_eq(0, "Active");
        assert_eq!(table.len(), 2);
    }

    #[test]
    fn filter_col() {
        let mut table = Table::new();
        table.add_row(["100"]);
        table.add_row(["50"]);
        table.add_row(["75"]);
        table.filter_col(0, |val| val.parse::<i32>().is_ok_and(|n| n > 60));
        assert_eq!(table.len(), 2);
    }

    #[test]
    fn filter_has() {
        let mut table = Table::new();
        table.add_row(["Kelana Smith"]);
        table.add_row(["Kata Jones"]);
        table.add_row(["Squidward Smith"]);
        table.filter_has(0, "Smith");
        assert_eq!(table.len(), 2);
    }

    #[test]
    fn filtered_returns_new_table() {
        let mut table = Table::new();
        table.set_style(TableStyle::Modern);
        table.add_row(["25"]);
        table.add_row(["30"]);
        table.add_row(["25"]);

        let filtered = table.filtered(|row| row.cells()[0].content() == "25");
        assert_eq!(table.len(), 3); // Original unchanged
        assert_eq!(filtered.len(), 2);
        assert_eq!(filtered.style(), TableStyle::Modern);
    }

    // Column operations tests
    #[test]
    fn add_column() {
        let mut table = Table::new();
        table.set_headers(["A", "B"]);
        table.add_row(["1", "2"]);
        table.add_column(&["C", "3"], Alignment::Right);
        assert_eq!(table.cols(), 3);
        assert_eq!(table.headers().unwrap().cells()[2].content(), "C");
    }

    #[test]
    fn insert_column() {
        let mut table = Table::new();
        table.set_headers(["A", "C"]);
        table.add_row(["1", "3"]);
        table.insert_column(1, &["B", "2"], Alignment::Center);
        assert_eq!(table.headers().unwrap().cells()[1].content(), "B");
    }

    #[test]
    fn remove_column() {
        let mut table = Table::new();
        table.set_headers(["A", "B", "C"]);
        table.add_row(["1", "2", "3"]);
        assert!(table.remove_column(1));
        assert_eq!(table.cols(), 2);
        assert_eq!(table.headers().unwrap().cells()[1].content(), "C");
    }

    // Render tests
    #[test]
    fn render_into_reuses_buffer() {
        let table = Table::new().header(["A", "B"]).row(["1", "2"]);

        let mut buffer = Vec::with_capacity(10);
        let original_capacity = buffer.capacity();

        table.render_into(&mut buffer).unwrap();
        let _first_capacity = buffer.capacity();

        buffer.clear();
        table.render_into(&mut buffer).unwrap();

        assert!(buffer.capacity() >= original_capacity);
        assert!(!buffer.is_empty());
    }

    #[test]
    fn render_single_row() {
        let table = Table::new().row(["a", "b"]);
        let output = table.render();
        assert!(!output.is_empty());
        assert!(output.contains('a'));
        assert!(output.contains('b'));
    }

    #[test]
    fn render_with_headers() {
        let table = Table::new().header(["X", "Y"]).row(["1", "2"]);
        let output = table.render();
        assert!(output.contains('X'));
        assert!(output.contains('Y'));
        assert!(output.contains('1'));
    }

    // Text wrapping tests
    #[test]
    fn wrap_text_short() {
        let lines = Table::wrap_text("hello", 10);
        assert_eq!(lines, vec!["hello"]);
    }

    #[test]
    fn wrap_text_multiple_words() {
        let lines = Table::wrap_text("hello world foo", 10);
        assert!(lines.len() >= 2);
    }

    #[test]
    fn wrap_text_long_word() {
        let lines = Table::wrap_text("supercalifragilisticexpialidocious", 10);
        assert!(lines.len() > 1);
    }

    #[test]
    fn wrap_text_unicode() {
        // Test with multi-byte UTF-8 characters (Japanese)
        let lines = Table::wrap_text("こんにちは世界", 5);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], "こんにちは");
        assert_eq!(lines[1], "世界");
    }

    #[test]
    fn wrap_text_unicode_long_word() {
        // Test wrapping a long word with multi-byte characters
        let lines = Table::wrap_text("日本語テスト文字列", 4);
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "日本語テ");
        assert_eq!(lines[1], "スト文字");
        assert_eq!(lines[2], "");
    }

    #[test]
    fn wrap_text_emoji() {
        // Test with emoji (4-byte UTF-8 characters)
        let lines = Table::wrap_text("🎉🎊🎁🎄🎅", 3);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], "🎉🎊🎁");
        assert_eq!(lines[1], "🎄🎅");
    }

    // Vertical alignment tests
    #[test]
    fn apply_vertical_alignment_top() {
        let lines = vec!["a".to_string()];
        let result = Table::apply_vertical_alignment(lines, 3, VerticalAlignment::Top);
        assert_eq!(result, vec!["a", "", ""]);
    }

    #[test]
    fn apply_vertical_alignment_middle() {
        let lines = vec!["a".to_string()];
        let result = Table::apply_vertical_alignment(lines, 3, VerticalAlignment::Middle);
        assert_eq!(result, vec!["", "a", ""]);
    }

    #[test]
    fn apply_vertical_alignment_bottom() {
        let lines = vec!["a".to_string()];
        let result = Table::apply_vertical_alignment(lines, 3, VerticalAlignment::Bottom);
        assert_eq!(result, vec!["", "", "a"]);
    }

    #[test]
    fn display_trait_matches_render() {
        let table = Table::new()
            .header(["Name", "Value"])
            .row(["Kata", "100"])
            .row(["Kelana", "200"]);

        let rendered = table.render();
        let displayed = format!("{table}");

        assert_eq!(rendered, displayed);
    }

    #[test]
    fn display_trait_empty_table() {
        let table = Table::new();
        let displayed = format!("{table}");
        assert_eq!(displayed, "");
    }

    #[test]
    fn display_trait_with_style() {
        let mut table = Table::new();
        table.set_style(TableStyle::Modern);
        table.set_headers(["A", "B"]);
        table.add_row(["1", "2"]);

        let rendered = table.render();
        let displayed = format!("{table}");

        assert_eq!(rendered, displayed);
    }

    #[test]
    fn add_row_invalidates_cache() {
        let mut table = Table::new().header(["A"]).row(["1"]);

        let first = table.render_cached();

        table.add_row(["2"]);

        let second = table.render_cached();

        assert_ne!(first, second);
    }

    #[test]
    fn set_headers_invalidates_cache() {
        let mut table = Table::new().header(["A"]).row(["1"]);

        let first = table.render_cached();

        table.set_headers(["B"]);

        let second = table.render_cached();

        assert_ne!(first, second);
    }

    #[test]
    fn render_into_matches_render() {
        let table = Table::new()
            .header(["Name", "Value"])
            .row(["Kata", "100"])
            .row(["Kelana", "200"]);

        let rendered = table.render();
        let mut buffer = Vec::new();
        table.render_into(&mut buffer).unwrap();

        assert_eq!(String::from_utf8(buffer).unwrap(), rendered);
    }

    #[test]
    fn format_cell_left_alignment() {
        let result = Table::format_cell("test", 10, Alignment::Left);
        assert_eq!(result, "test      ");
    }

    #[test]
    fn format_cell_right_alignment() {
        let result = Table::format_cell("test", 10, Alignment::Right);
        assert_eq!(result, "      test");
    }

    #[test]
    fn format_cell_center_alignment() {
        let result = Table::format_cell("test", 10, Alignment::Center);
        assert_eq!(result, "   test   ");
    }

    #[test]
    fn format_cell_truncation() {
        let result = Table::format_cell("hello world", 8, Alignment::Left);
        assert_eq!(result, "hello...");
    }

    #[test]
    fn format_cell_exact_width() {
        let result = Table::format_cell("test", 4, Alignment::Left);
        assert_eq!(result, "test");
    }

    #[test]
    fn recalculate_widths_forces_recalculation() {
        let mut table = Table::new().header(["A"]).row(["1"]);

        let _ = table.render_cached();

        table.recalculate_widths();
        let result = table.render_cached();

        assert!(!result.is_empty());
    }

    #[test]
    fn render_cached_reuses_cache() {
        let table = Table::new().header(["A", "B"]).row(["1", "2"]);

        // First call populates cache
        let first = table.render_cached();

        // Verify cache is populated
        assert!(table.cached_widths.borrow().is_some());

        // Second call should return same result (using cache)
        let second = table.render_cached();

        assert_eq!(first, second);
    }

    #[test]
    fn render_cached_matches_render() {
        let table = Table::new()
            .header(["Name", "Age"])
            .row(["Kata", "30"])
            .row(["Kelana", "25"]);

        let rendered = table.render();
        let cached = table.render_cached();

        assert_eq!(rendered, cached);
    }
}