cli-boxes 0.1.1

Unicode box drawing characters for creating beautiful CLI interfaces
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
//! # CLI Boxes
//!
//! [![Crates.io](https://img.shields.io/crates/v/cli-boxes.svg)](https://crates.io/crates/cli-boxes)
//! [![Documentation](https://docs.rs/cli-boxes/badge.svg)](https://docs.rs/cli-boxes)
//! [![License](https://img.shields.io/crates/l/cli-boxes.svg)](https://github.com/sabry-awad97/boxen-rs)
//!
//! A high-performance Rust library providing Unicode box-drawing characters for creating beautiful CLI interfaces.
//! Perfect for terminal applications, CLI tools, and text-based user interfaces.
//!
//! ## 🎯 Features
//!
//! - **9 Beautiful Box Styles**: From elegant single-line to decorative arrows
//! - **Unicode & ASCII Support**: Full Unicode compliance with ASCII fallback
//! - **Zero-Cost Abstractions**: Compile-time constants and zero-allocation parsing
//! - **Type Safety**: Strong typing prevents incorrect usage
//! - **Ergonomic Builder API**: Fluent interface for custom box creation
//! - **String Parsing**: Parse styles from configuration files or user input
//! - **Serde Integration**: Optional serialization support (feature-gated)
//! - **Comprehensive Testing**: 100% test coverage with extensive edge case handling
//!
//! ## 📦 Box Styles
//!
//! | Style | Preview | Use Case |
//! |-------|---------|----------|
//! | `SINGLE` | `┌─┐│┘─└│` | General purpose, clean appearance |
//! | `DOUBLE` | `╔═╗║╝═╚║` | Emphasis, important content |
//! | `ROUND` | `╭─╮│╯─╰│` | Modern, soft appearance |
//! | `BOLD` | `┏━┓┃┛━┗┃` | Strong emphasis, headers |
//! | `SINGLE_DOUBLE` | `╓─╖║╜─╙║` | Mixed style, unique look |
//! | `DOUBLE_SINGLE` | `╒═╕│╛═╘│` | Alternative mixed style |
//! | `CLASSIC` | `+─+|+─+|` | ASCII compatibility, legacy systems |
//! | `ARROW` | `↘↓↙←↖↑↗→` | Decorative, special effects |
//! | `NONE` | `        ` | Invisible borders, spacing |
//!
//! ## 🚀 Quick Start
//!
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! cli-boxes = "0.1.0"
//! ```
//!
//! ### Basic Usage
//!
//! ```rust
//! use cli_boxes::{BoxChars, BorderStyle};
//!
//! // Create a simple box
//! let box_chars = BoxChars::SINGLE;
//! println!("{}{}{}",
//!     box_chars.top_left,
//!     box_chars.top.to_string().repeat(10),
//!     box_chars.top_right
//! );
//! println!("{}          {}", box_chars.left, box_chars.right);
//! println!("{}{}{}",
//!     box_chars.bottom_left,
//!     box_chars.bottom.to_string().repeat(10),
//!     box_chars.bottom_right
//! );
//! // Output:
//! // ┌──────────┐
//! // │          │
//! // └──────────┘
//! ```
//!
//! ### Advanced Usage with Builder Pattern
//!
//! ```rust
//! use cli_boxes::BoxChars;
//!
//! // Create custom box with builder pattern
//! let custom = BoxChars::builder()
//!     .corners('●')
//!     .horizontal('═')
//!     .vertical('║')
//!     .top_left('╔')  // Override specific corner
//!     .build();
//!
//! // Asymmetric design
//! let fancy = BoxChars::builder()
//!     .top_left('╭').top('─').top_right('╮')
//!     .left('│').right('│')
//!     .bottom_left('└').bottom('─').bottom_right('┘')
//!     .build();
//! ```
//!
//! ### Dynamic Style Selection
//!
//! ```rust
//! use cli_boxes::{BorderStyle, BoxChars};
//!
//! // Parse from configuration
//! let style: BorderStyle = "double".parse().unwrap();
//! let box_chars = style.chars();
//!
//! // Iterate through all styles
//! for style in BorderStyle::all() {
//!     let chars = style.chars();
//!     println!("{}: {}", style, chars);
//! }
//! ```
//!
//! ## 🎨 Real-World Examples
//!
//! ### Creating a Status Box
//!
//! ```rust
//! use cli_boxes::BoxChars;
//!
//! fn create_status_box(message: &str, width: usize) -> String {
//!     let box_chars = BoxChars::DOUBLE;
//!     let padding = width.saturating_sub(message.len() + 2);
//!     let left_pad = padding / 2;
//!     let right_pad = padding - left_pad;
//!     
//!     format!(
//!         "{}{}{}\n{}{}{}{}{}\n{}{}{}",
//!         box_chars.top_left,
//!         box_chars.top.to_string().repeat(width),
//!         box_chars.top_right,
//!         box_chars.left,
//!         " ".repeat(left_pad),
//!         message,
//!         " ".repeat(right_pad),
//!         box_chars.right,
//!         box_chars.bottom_left,
//!         box_chars.bottom.to_string().repeat(width),
//!         box_chars.bottom_right
//!     )
//! }
//! ```
//!
//! ### Configuration-Driven Boxes
//!
//! ```rust
//! use cli_boxes::{BorderStyle, BoxChars};
//! use std::collections::HashMap;
//!
//! fn get_box_for_level(level: &str) -> BoxChars {
//!     let styles: HashMap<&str, BorderStyle> = [
//!         ("info", BorderStyle::Single),
//!         ("warning", BorderStyle::Bold),
//!         ("error", BorderStyle::Double),
//!         ("success", BorderStyle::Round),
//!     ].iter().cloned().collect();
//!     
//!     styles.get(level)
//!         .map(|s| s.chars())
//!         .unwrap_or(BoxChars::CLASSIC)
//! }
//! ```
//!
//! ## ⚡ Performance
//!
//! This library is designed for maximum performance:
//!
//! - **Zero Allocations**: String parsing uses byte-level comparison without heap allocation
//! - **Compile-Time Constants**: All predefined styles are `const` and computed at compile time
//! - **Minimal Dependencies**: Only `strum` for enum iteration, optional `serde` for serialization
//! - **Small Memory Footprint**: `BoxChars` is only 32 bytes (8 × 4-byte chars)
//!
//! ## 🔧 Optional Features
//!
//! ### Serde Support
//!
//! Enable serialization support:
//! ```toml
//! [dependencies]
//! cli-boxes = { version = "0.1.0", features = ["serde"] }
//! ```
//!
//! ```rust
//! # #[cfg(feature = "serde")]
//! # {
//! use cli_boxes::{BoxChars, BorderStyle};
//! use serde_json;
//!
//! let style = BorderStyle::Double;
//! let json = serde_json::to_string(&style).unwrap();
//! let deserialized: BorderStyle = serde_json::from_str(&json).unwrap();
//! # }
//! ```
//!
//! ## 🛡️ Error Handling
//!
//! The library provides helpful error messages for invalid input:
//!
//! ```rust
//! use cli_boxes::BorderStyle;
//!
//! match "invalid_style".parse::<BorderStyle>() {
//!     Ok(style) => println!("Parsed: {}", style),
//!     Err(e) => println!("{}", e),
//!     // Output: Invalid border style: 'invalid_style'.
//!     // Did you mean one of: none, single, double, round, bold,
//!     // single_double, double_single, classic, arrow?
//! }
//! ```
//!
//! ## 🔗 Related Crates
//!
//! - [`tui`](https://crates.io/crates/tui) - Terminal user interface library
//! - [`crossterm`](https://crates.io/crates/crossterm) - Cross-platform terminal manipulation
//! - [`console`](https://crates.io/crates/console) - Terminal and console abstraction
//!
//! ## 📄 License
//!
//! This project is licensed under either of
//! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
//! - MIT License ([LICENSE-MIT](LICENSE-MIT))
//!
//! at your option.

#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![warn(clippy::cargo)]
#![doc(html_root_url = "https://docs.rs/cli-boxes/0.1.0")]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/sabry-awad97/boxen-rs/main/assets/logo.png"
)]
#![doc(
    html_favicon_url = "https://raw.githubusercontent.com/sabry-awad97/boxen-rs/main/assets/favicon.ico"
)]

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use strum::{EnumIter, IntoEnumIterator};

/// A collection of Unicode characters used for drawing boxes in CLI applications.
///
/// This struct contains all the necessary characters to draw a complete box:
/// corners, horizontal lines, and vertical lines. Each field represents a specific
/// position in the box structure.
///
/// # Box Structure
///
/// ```text
/// top_left ──── top ──── top_right
///    │                      │
///   left                  right
///    │                      │
/// bottom_left ── bottom ── bottom_right
/// ```
///
/// # Memory Layout
///
/// `BoxChars` is a compact struct containing 8 `char` values (32 bytes total on most platforms).
/// All predefined constants are evaluated at compile time for zero runtime cost.
///
/// # Thread Safety
///
/// `BoxChars` implements `Send` and `Sync`, making it safe to use across threads.
/// All operations are immutable after construction.
///
/// # Examples
///
/// ## Using Predefined Styles
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// // Use predefined single-line box characters
/// let single = BoxChars::SINGLE;
/// assert_eq!(single.top_left, '┌');
/// assert_eq!(single.top, '─');
/// assert_eq!(single.top_right, '┐');
///
/// // Double-line for emphasis
/// let double = BoxChars::DOUBLE;
/// assert_eq!(double.top_left, '╔');
/// ```
///
/// ## Custom Box Creation
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// // Direct constructor
/// let custom = BoxChars::new('*', '-', '*', '|', '*', '-', '*', '|');
///
/// // Builder pattern (recommended for readability)
/// let builder_box = BoxChars::builder()
///     .corners('*')
///     .horizontal('-')
///     .vertical('|')
///     .build();
///
/// assert_eq!(custom, builder_box);
/// ```
///
/// ## Drawing a Complete Box
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// fn draw_box(chars: &BoxChars, width: usize, height: usize) -> String {
///     let mut result = String::new();
///     
///     // Top border
///     result.push(chars.top_left);
///     result.push_str(&chars.top.to_string().repeat(width.saturating_sub(2)));
///     result.push(chars.top_right);
///     result.push('\n');
///     
///     // Side borders
///     for _ in 0..height.saturating_sub(2) {
///         result.push(chars.left);
///         result.push_str(&" ".repeat(width.saturating_sub(2)));
///         result.push(chars.right);
///         result.push('\n');
///     }
///     
///     // Bottom border
///     result.push(chars.bottom_left);
///     result.push_str(&chars.bottom.to_string().repeat(width.saturating_sub(2)));
///     result.push(chars.bottom_right);
///     
///     result
/// }
///
/// let box_str = draw_box(&BoxChars::SINGLE, 5, 3);
/// println!("{}", box_str);
/// // Output:
/// // ┌───┐
/// // │   │
/// // └───┘
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct BoxChars {
    /// Top-left corner character
    pub top_left: char,
    /// Top border character (repeated horizontally)
    pub top: char,
    /// Top-right corner character
    pub top_right: char,
    /// Right border character (repeated vertically)
    pub right: char,
    /// Bottom-right corner character
    pub bottom_right: char,
    /// Bottom border character (repeated horizontally)
    pub bottom: char,
    /// Bottom-left corner character
    pub bottom_left: char,
    /// Left border character (repeated vertically)
    pub left: char,
}

/// Macro to reduce boilerplate when defining box character constants.
macro_rules! box_chars {
    ($name:ident, $tl:literal, $t:literal, $tr:literal, $r:literal, $br:literal, $b:literal, $bl:literal, $l:literal, $doc:literal) => {
        #[doc = $doc]
        pub const $name: Self = Self {
            top_left: $tl,
            top: $t,
            top_right: $tr,
            right: $r,
            bottom_right: $br,
            bottom: $b,
            bottom_left: $bl,
            left: $l,
        };
    };
}

impl BoxChars {
    /// Creates a new `BoxChars` with the specified characters.
    ///
    /// # Arguments
    ///
    /// * `top_left` - Top-left corner character
    /// * `top` - Top border character
    /// * `top_right` - Top-right corner character
    /// * `right` - Right border character
    /// * `bottom_right` - Bottom-right corner character
    /// * `bottom` - Bottom border character
    /// * `bottom_left` - Bottom-left corner character
    /// * `left` - Left border character
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BoxChars;
    ///
    /// let custom = BoxChars::new('*', '-', '*', '|', '*', '-', '*', '|');
    /// assert_eq!(custom.top_left, '*');
    /// assert_eq!(custom.top, '-');
    /// ```
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        top_left: char,
        top: char,
        top_right: char,
        right: char,
        bottom_right: char,
        bottom: char,
        bottom_left: char,
        left: char,
    ) -> Self {
        Self {
            top_left,
            top,
            top_right,
            right,
            bottom_right,
            bottom,
            bottom_left,
            left,
        }
    }

    /// Creates a builder for constructing custom box characters.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BoxChars;
    ///
    /// let custom = BoxChars::builder()
    ///     .corners('*')
    ///     .horizontal('-')
    ///     .vertical('|')
    ///     .build();
    /// ```
    #[must_use]
    pub fn builder() -> BoxCharsBuilder {
        BoxCharsBuilder::default()
    }

    box_chars!(
        NONE,
        ' ',
        ' ',
        ' ',
        ' ',
        ' ',
        ' ',
        ' ',
        ' ',
        "Creates a box with no visible characters (all spaces).\n\nThis is useful when you want to maintain box structure without visible borders, or as a fallback when no box styling is desired."
    );

    box_chars!(
        SINGLE,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using single-line Unicode box-drawing characters.\n\nThis is the most commonly used box style, providing clean and professional-looking borders that work well in most terminal environments.\n\nCharacters used: `┌─┐│┘─└│`"
    );

    box_chars!(
        DOUBLE,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using double-line Unicode box-drawing characters.\n\nThis style provides a bold, prominent appearance that's excellent for highlighting important content or creating emphasis in CLI applications.\n\nCharacters used: `╔═╗║╝═╚║`"
    );

    box_chars!(
        ROUND,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using rounded corner Unicode box-drawing characters.\n\nThis style provides a softer, more modern appearance with curved corners that's aesthetically pleasing and less harsh than sharp corners.\n\nCharacters used: `╭─╮│╯─╰│`"
    );

    box_chars!(
        BOLD,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using bold/thick line Unicode box-drawing characters.\n\nThis style provides maximum visual impact with thick, bold lines that command attention and create strong visual separation.\n\nCharacters used: `┏━┓┃┛━┗┃`"
    );

    box_chars!(
        SINGLE_DOUBLE,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using single horizontal, double vertical box-drawing characters.\n\nThis mixed style combines single-line horizontal borders with double-line vertical borders, creating a unique visual effect.\n\nCharacters used: `╓─╖║╜─╙║`"
    );

    box_chars!(
        DOUBLE_SINGLE,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a box using double horizontal, single vertical box-drawing characters.\n\nThis mixed style combines double-line horizontal borders with single-line vertical borders, creating an alternative visual effect to `SINGLE_DOUBLE`.\n\nCharacters used: `╒═╕│╛═╘│`"
    );

    box_chars!(
        CLASSIC,
        '+',
        '-',
        '+',
        '|',
        '+',
        '-',
        '+',
        '|',
        "Creates a box using classic ASCII characters for maximum compatibility.\n\nThis style uses only basic ASCII characters, ensuring compatibility with all terminal environments, including those that don't support Unicode.\n\nCharacters used: `+-+|+-+|`"
    );

    box_chars!(
        ARROW,
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        "Creates a decorative box using arrow Unicode characters.\n\nThis unique style uses directional arrows to create an unconventional but eye-catching border effect. Best used for special emphasis or creative CLI applications.\n\nCharacters used: `↘↓↙←↖↑↗→`"
    );
}

impl Default for BoxChars {
    /// Returns the default box characters (single-line style).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BoxChars;
    ///
    /// let default_box = BoxChars::default();
    /// assert_eq!(default_box, BoxChars::SINGLE);
    /// ```
    fn default() -> Self {
        Self::SINGLE
    }
}

impl fmt::Display for BoxChars {
    /// Formats the box characters as a string showing all 8 characters in order.
    ///
    /// The format is: `top_left`, `top`, `top_right`, `right`, `bottom_right`, `bottom`, `bottom_left`, `left`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BoxChars;
    ///
    /// let single = BoxChars::SINGLE;
    /// println!("{}", single); // Outputs: ┌─┐│┘─└│
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}{}{}{}{}{}{}{}",
            self.top_left,
            self.top,
            self.top_right,
            self.right,
            self.bottom_right,
            self.bottom,
            self.bottom_left,
            self.left
        )
    }
}

/// Builder for creating custom `BoxChars` with a fluent, type-safe API.
///
/// The builder pattern provides an ergonomic way to construct custom box characters
/// with method chaining. All methods are `const fn` where possible for compile-time
/// evaluation. The builder starts with invisible characters (`NONE`) and allows
/// selective customization.
///
/// # Design Patterns
///
/// ## Uniform Styling
/// Use the convenience methods for consistent appearance:
/// - `corners()` - Sets all four corners to the same character
/// - `horizontal()` - Sets top and bottom borders  
/// - `vertical()` - Sets left and right borders
///
/// ## Selective Overrides
/// Start with uniform styling, then override specific positions:
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// let mixed = BoxChars::builder()
///     .corners('●')           // Set all corners
///     .horizontal('═')        // Set horizontal borders
///     .vertical('║')          // Set vertical borders
///     .top_left('╔')         // Override just top-left
///     .build();
/// ```
///
/// ## Asymmetric Designs
/// Create unique, asymmetric box styles:
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// let asymmetric = BoxChars::builder()
///     .top_left('╭').top('─').top_right('╮')
///     .left('│').right('│')
///     .bottom_left('└').bottom('─').bottom_right('┘')
///     .build();
/// ```
///
/// ## Theme-Based Construction
///
/// ```rust
/// use cli_boxes::BoxChars;
///
/// fn create_theme_box(theme: &str) -> BoxChars {
///     let mut builder = BoxChars::builder();
///     
///     match theme {
///         "minimal" => builder.corners('+').horizontal('-').vertical('|'),
///         "fancy" => builder.corners('●').horizontal('═').vertical('║'),
///         "retro" => builder.corners('*').horizontal('=').vertical(':'),
///         _ => builder.corners('?').horizontal('?').vertical('?'),
///     }.build()
/// }
/// ```
///
/// # Performance
///
/// The builder uses `const fn` methods where possible, allowing compile-time
/// evaluation when used with constant inputs. The final `build()` call is
/// zero-cost, simply returning the constructed `BoxChars` struct.
#[derive(Debug, Clone)]
pub struct BoxCharsBuilder {
    chars: BoxChars,
}

impl Default for BoxCharsBuilder {
    fn default() -> Self {
        Self {
            chars: BoxChars::NONE,
        }
    }
}

impl BoxCharsBuilder {
    /// Sets all corner characters to the same value.
    #[must_use]
    pub const fn corners(mut self, char: char) -> Self {
        self.chars.top_left = char;
        self.chars.top_right = char;
        self.chars.bottom_left = char;
        self.chars.bottom_right = char;
        self
    }

    /// Sets both horizontal border characters (top and bottom) to the same value.
    #[must_use]
    pub const fn horizontal(mut self, char: char) -> Self {
        self.chars.top = char;
        self.chars.bottom = char;
        self
    }

    /// Sets both vertical border characters (left and right) to the same value.
    #[must_use]
    pub const fn vertical(mut self, char: char) -> Self {
        self.chars.left = char;
        self.chars.right = char;
        self
    }

    /// Sets the top-left corner character.
    #[must_use]
    pub const fn top_left(mut self, char: char) -> Self {
        self.chars.top_left = char;
        self
    }

    /// Sets the top border character.
    #[must_use]
    pub const fn top(mut self, char: char) -> Self {
        self.chars.top = char;
        self
    }

    /// Sets the top-right corner character.
    #[must_use]
    pub const fn top_right(mut self, char: char) -> Self {
        self.chars.top_right = char;
        self
    }

    /// Sets the right border character.
    #[must_use]
    pub const fn right(mut self, char: char) -> Self {
        self.chars.right = char;
        self
    }

    /// Sets the bottom-right corner character.
    #[must_use]
    pub const fn bottom_right(mut self, char: char) -> Self {
        self.chars.bottom_right = char;
        self
    }

    /// Sets the bottom border character.
    #[must_use]
    pub const fn bottom(mut self, char: char) -> Self {
        self.chars.bottom = char;
        self
    }

    /// Sets the bottom-left corner character.
    #[must_use]
    pub const fn bottom_left(mut self, char: char) -> Self {
        self.chars.bottom_left = char;
        self
    }

    /// Sets the left border character.
    #[must_use]
    pub const fn left(mut self, char: char) -> Self {
        self.chars.left = char;
        self
    }

    /// Builds and returns the final `BoxChars`.
    #[must_use]
    pub const fn build(self) -> BoxChars {
        self.chars
    }
}

/// Available box drawing styles with semantic meaning and use cases.
///
/// Each style provides a different visual appearance optimized for specific use cases.
/// This enum provides a convenient, type-safe way to select box styles without
/// directly referencing character constants.
///
/// # Style Guidelines
///
/// - **Single**: Default choice for most applications, clean and readable
/// - **Double**: Use for emphasis, headers, or important content sections  
/// - **Round**: Modern appearance, good for user-friendly interfaces
/// - **Bold**: Maximum emphasis, warnings, or critical information
/// - **Mixed Styles**: Unique visual effects, decorative purposes
/// - **Classic**: ASCII-only environments, legacy system compatibility
/// - **Arrow**: Special effects, directional indicators, creative designs
/// - **None**: Invisible spacing, layout without visible borders
///
/// # Performance Notes
///
/// All enum variants are zero-cost abstractions that compile to direct character constants.
/// String parsing is optimized for performance with zero heap allocations.
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use cli_boxes::{BorderStyle, BoxChars};
///
/// // Convert enum to box characters
/// let box_chars = BoxChars::from(BorderStyle::Single);
/// assert_eq!(box_chars.top_left, '┌');
///
/// // Using the convenience method
/// let double_chars = BorderStyle::Double.chars();
/// assert_eq!(double_chars.top_left, '╔');
/// ```
///
/// ## Dynamic Style Selection
///
/// ```rust
/// use cli_boxes::BorderStyle;
///
/// fn get_style_for_severity(level: u8) -> BorderStyle {
///     match level {
///         0 => BorderStyle::None,
///         1 => BorderStyle::Single,
///         2 => BorderStyle::Bold,
///         3 => BorderStyle::Double,
///         _ => BorderStyle::Classic,
///     }
/// }
///
/// let style = get_style_for_severity(2);
/// let chars = style.chars();
/// ```
///
/// ## Iteration and Discovery
///
/// ```rust
/// use cli_boxes::BorderStyle;
///
/// // Display all available styles
/// for style in BorderStyle::all() {
///     let chars = style.chars();
///     println!("{:12} -> {}", style.to_string(), chars);
/// }
/// ```
///
/// ## String Parsing with Error Handling
///
/// ```rust
/// use cli_boxes::BorderStyle;
/// use std::str::FromStr;
///
/// // Parse from configuration files or user input
/// let styles = ["single", "double", "round", "invalid"];
///
/// for style_str in &styles {
///     match style_str.parse::<BorderStyle>() {
///         Ok(style) => println!("✓ Parsed '{}' as {:?}", style_str, style),
///         Err(e) => println!("✗ Error: {}", e),
///     }
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EnumIter)]
pub enum BorderStyle {
    /// No box characters (all spaces)
    None,
    /// Single-line box drawing characters: ┌─┐│┘─└│
    Single,
    /// Double-line box drawing characters: ╔═╗║╝═╚║
    Double,
    /// Rounded corner box drawing characters: ╭─╮│╯─╰│
    Round,
    /// Bold/thick line box drawing characters: ┏━┓┃┛━┗┃
    Bold,
    /// Single horizontal, double vertical: ╓─╖║╜─╙║
    SingleDouble,
    /// Double horizontal, single vertical: ╒═╕│╛═╘│
    DoubleSingle,
    /// ASCII-compatible classic box characters: +─+|+─+|
    Classic,
    /// Arrow-based decorative box characters: ↘↓↙←↖↑↗→
    Arrow,
}

impl From<BorderStyle> for BoxChars {
    /// Converts a `BorderStyle` enum variant to its corresponding `BoxChars`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::{BorderStyle, BoxChars};
    ///
    /// let single_chars = BoxChars::from(BorderStyle::Single);
    /// assert_eq!(single_chars, BoxChars::SINGLE);
    ///
    /// let double_chars = BoxChars::from(BorderStyle::Double);
    /// assert_eq!(double_chars, BoxChars::DOUBLE);
    /// ```
    fn from(style: BorderStyle) -> Self {
        match style {
            BorderStyle::None => Self::NONE,
            BorderStyle::Single => Self::SINGLE,
            BorderStyle::Double => Self::DOUBLE,
            BorderStyle::Round => Self::ROUND,
            BorderStyle::Bold => Self::BOLD,
            BorderStyle::SingleDouble => Self::SINGLE_DOUBLE,
            BorderStyle::DoubleSingle => Self::DOUBLE_SINGLE,
            BorderStyle::Classic => Self::CLASSIC,
            BorderStyle::Arrow => Self::ARROW,
        }
    }
}

impl BorderStyle {
    /// Returns the `BoxChars` associated with this border style.
    ///
    /// This is a convenience method that's equivalent to `BoxChars::from(style)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BorderStyle;
    ///
    /// let style = BorderStyle::Bold;
    /// let chars = style.chars();
    /// assert_eq!(chars.top, '━');
    /// ```
    #[must_use]
    pub fn chars(self) -> BoxChars {
        BoxChars::from(self)
    }

    /// Returns an iterator over all available border styles.
    ///
    /// This is a convenience method that uses the `EnumIter` trait.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BorderStyle;
    ///
    /// for style in BorderStyle::all() {
    ///     println!("Style: {:?}", style);
    /// }
    /// ```
    pub fn all() -> impl Iterator<Item = Self> {
        Self::iter()
    }
}

impl fmt::Display for BorderStyle {
    /// Formats the border style as a lowercase string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use cli_boxes::BorderStyle;
    ///
    /// assert_eq!(BorderStyle::Single.to_string(), "single");
    /// assert_eq!(BorderStyle::DoubleSingle.to_string(), "double_single");
    /// assert_eq!(BorderStyle::Arrow.to_string(), "arrow");
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::None => "none",
            Self::Single => "single",
            Self::Double => "double",
            Self::Round => "round",
            Self::Bold => "bold",
            Self::SingleDouble => "single_double",
            Self::DoubleSingle => "double_single",
            Self::Classic => "classic",
            Self::Arrow => "arrow",
        };
        write!(f, "{s}")
    }
}

impl FromStr for BorderStyle {
    type Err = ParseBorderStyleError;

    /// Parses a string into a `BorderStyle`.
    ///
    /// The parsing is case-insensitive and accepts both `snake_case` and `kebab-case`.
    /// This implementation is optimized to avoid heap allocations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::str::FromStr;
    /// use cli_boxes::BorderStyle;
    ///
    /// assert_eq!("single".parse::<BorderStyle>().unwrap(), BorderStyle::Single);
    /// assert_eq!("DOUBLE".parse::<BorderStyle>().unwrap(), BorderStyle::Double);
    /// assert_eq!("single-double".parse::<BorderStyle>().unwrap(), BorderStyle::SingleDouble);
    /// assert_eq!("double_single".parse::<BorderStyle>().unwrap(), BorderStyle::DoubleSingle);
    ///
    /// // Error case
    /// assert!("invalid".parse::<BorderStyle>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Helper function to match strings case-insensitively with hyphen/underscore normalization
        let matches = |target: &str| -> bool {
            if s.len() != target.len() {
                return false;
            }
            s.bytes().zip(target.bytes()).all(|(a, b)| {
                let a_norm = if a == b'-' {
                    b'_'
                } else {
                    a.to_ascii_lowercase()
                };
                a_norm == b
            })
        };

        if matches("none") {
            Ok(Self::None)
        } else if matches("single") {
            Ok(Self::Single)
        } else if matches("double") {
            Ok(Self::Double)
        } else if matches("round") {
            Ok(Self::Round)
        } else if matches("bold") {
            Ok(Self::Bold)
        } else if matches("single_double") {
            Ok(Self::SingleDouble)
        } else if matches("double_single") {
            Ok(Self::DoubleSingle)
        } else if matches("classic") {
            Ok(Self::Classic)
        } else if matches("arrow") {
            Ok(Self::Arrow)
        } else {
            Err(ParseBorderStyleError::InvalidStyle(s.to_string()))
        }
    }
}

/// Error type for parsing `BorderStyle` from string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseBorderStyleError {
    /// The provided string does not match any known border style.
    InvalidStyle(String),
}

impl fmt::Display for ParseBorderStyleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidStyle(style) => {
                let suggestions = BorderStyle::all()
                    .map(|s| s.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");

                write!(
                    f,
                    "Invalid border style: '{style}'. Did you mean one of: {suggestions}?"
                )
            }
        }
    }
}

impl std::error::Error for ParseBorderStyleError {}

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

    #[test]
    fn test_box_chars_constants() {
        // Test that all constants have the expected characters
        assert_eq!(BoxChars::NONE.top_left, ' ');
        assert_eq!(BoxChars::SINGLE.top_left, '');
        assert_eq!(BoxChars::DOUBLE.top_left, '');
        assert_eq!(BoxChars::ROUND.top_left, '');
        assert_eq!(BoxChars::BOLD.top_left, '');
        assert_eq!(BoxChars::SINGLE_DOUBLE.top_left, '');
        assert_eq!(BoxChars::DOUBLE_SINGLE.top_left, '');
        assert_eq!(BoxChars::CLASSIC.top_left, '+');
        assert_eq!(BoxChars::ARROW.top_left, '');
    }

    #[test]
    fn test_box_chars_new() {
        let custom = BoxChars::new('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
        assert_eq!(custom.top_left, 'a');
        assert_eq!(custom.top, 'b');
        assert_eq!(custom.top_right, 'c');
        assert_eq!(custom.right, 'd');
        assert_eq!(custom.bottom_right, 'e');
        assert_eq!(custom.bottom, 'f');
        assert_eq!(custom.bottom_left, 'g');
        assert_eq!(custom.left, 'h');
    }

    #[test]
    fn test_box_chars_default() {
        let default = BoxChars::default();
        assert_eq!(default, BoxChars::SINGLE);
    }

    #[test]
    fn test_box_chars_display() {
        let single = BoxChars::SINGLE;
        assert_eq!(single.to_string(), "┌─┐│┘─└│");

        let custom = BoxChars::new('*', '-', '*', '|', '*', '-', '*', '|');
        assert_eq!(custom.to_string(), "*-*|*-*|");
    }

    #[test]
    fn test_box_chars_traits() {
        let single = BoxChars::SINGLE;
        let single_copy = single;

        // Test Copy trait
        assert_eq!(single, single_copy);

        // Test Hash trait
        let mut set = HashSet::new();
        set.insert(single);
        assert!(set.contains(&single));

        // Test Debug trait
        let debug_str = format!("{single:?}");
        assert!(debug_str.contains("BoxChars"));
    }

    #[test]
    fn test_builder_pattern() {
        let custom = BoxChars::builder()
            .corners('*')
            .horizontal('-')
            .vertical('|')
            .build();

        assert_eq!(custom.top_left, '*');
        assert_eq!(custom.top_right, '*');
        assert_eq!(custom.bottom_left, '*');
        assert_eq!(custom.bottom_right, '*');
        assert_eq!(custom.top, '-');
        assert_eq!(custom.bottom, '-');
        assert_eq!(custom.left, '|');
        assert_eq!(custom.right, '|');
    }

    #[test]
    fn test_builder_individual_methods() {
        let custom = BoxChars::builder()
            .top_left('a')
            .top('b')
            .top_right('c')
            .right('d')
            .bottom_right('e')
            .bottom('f')
            .bottom_left('g')
            .left('h')
            .build();

        assert_eq!(custom.top_left, 'a');
        assert_eq!(custom.top, 'b');
        assert_eq!(custom.top_right, 'c');
        assert_eq!(custom.right, 'd');
        assert_eq!(custom.bottom_right, 'e');
        assert_eq!(custom.bottom, 'f');
        assert_eq!(custom.bottom_left, 'g');
        assert_eq!(custom.left, 'h');
    }

    #[test]
    fn test_builder_chaining() {
        let result = BoxChars::builder()
            .corners('')
            .horizontal('')
            .vertical('')
            .top_left('') // Override corner
            .build();

        assert_eq!(result.top_left, ''); // Overridden
        assert_eq!(result.top_right, ''); // From corners
        assert_eq!(result.top, ''); // From horizontal
        assert_eq!(result.left, ''); // From vertical
    }

    #[test]
    fn test_builder_default() {
        let default_builder = BoxCharsBuilder::default();
        let result = default_builder.build();
        assert_eq!(result, BoxChars::NONE);
    }

    #[test]
    fn test_border_style_enum() {
        // Test all variants exist
        let styles = [
            BorderStyle::None,
            BorderStyle::Single,
            BorderStyle::Double,
            BorderStyle::Round,
            BorderStyle::Bold,
            BorderStyle::SingleDouble,
            BorderStyle::DoubleSingle,
            BorderStyle::Classic,
            BorderStyle::Arrow,
        ];

        assert_eq!(styles.len(), 9);
    }

    #[test]
    fn test_border_style_to_box_chars() {
        assert_eq!(BoxChars::from(BorderStyle::None), BoxChars::NONE);
        assert_eq!(BoxChars::from(BorderStyle::Single), BoxChars::SINGLE);
        assert_eq!(BoxChars::from(BorderStyle::Double), BoxChars::DOUBLE);
        assert_eq!(BoxChars::from(BorderStyle::Round), BoxChars::ROUND);
        assert_eq!(BoxChars::from(BorderStyle::Bold), BoxChars::BOLD);
        assert_eq!(
            BoxChars::from(BorderStyle::SingleDouble),
            BoxChars::SINGLE_DOUBLE
        );
        assert_eq!(
            BoxChars::from(BorderStyle::DoubleSingle),
            BoxChars::DOUBLE_SINGLE
        );
        assert_eq!(BoxChars::from(BorderStyle::Classic), BoxChars::CLASSIC);
        assert_eq!(BoxChars::from(BorderStyle::Arrow), BoxChars::ARROW);
    }

    #[test]
    fn test_border_style_chars_method() {
        let style = BorderStyle::Bold;
        let chars = style.chars();
        assert_eq!(chars, BoxChars::BOLD);
        assert_eq!(chars.top, '');
    }

    #[test]
    fn test_border_style_display() {
        assert_eq!(BorderStyle::None.to_string(), "none");
        assert_eq!(BorderStyle::Single.to_string(), "single");
        assert_eq!(BorderStyle::Double.to_string(), "double");
        assert_eq!(BorderStyle::Round.to_string(), "round");
        assert_eq!(BorderStyle::Bold.to_string(), "bold");
        assert_eq!(BorderStyle::SingleDouble.to_string(), "single_double");
        assert_eq!(BorderStyle::DoubleSingle.to_string(), "double_single");
        assert_eq!(BorderStyle::Classic.to_string(), "classic");
        assert_eq!(BorderStyle::Arrow.to_string(), "arrow");
    }

    #[test]
    fn test_border_style_from_str() {
        // Test basic parsing
        assert_eq!("none".parse::<BorderStyle>().unwrap(), BorderStyle::None);
        assert_eq!(
            "single".parse::<BorderStyle>().unwrap(),
            BorderStyle::Single
        );
        assert_eq!(
            "double".parse::<BorderStyle>().unwrap(),
            BorderStyle::Double
        );
        assert_eq!("round".parse::<BorderStyle>().unwrap(), BorderStyle::Round);
        assert_eq!("bold".parse::<BorderStyle>().unwrap(), BorderStyle::Bold);
        assert_eq!(
            "single_double".parse::<BorderStyle>().unwrap(),
            BorderStyle::SingleDouble
        );
        assert_eq!(
            "double_single".parse::<BorderStyle>().unwrap(),
            BorderStyle::DoubleSingle
        );
        assert_eq!(
            "classic".parse::<BorderStyle>().unwrap(),
            BorderStyle::Classic
        );
        assert_eq!("arrow".parse::<BorderStyle>().unwrap(), BorderStyle::Arrow);
    }

    #[test]
    fn test_border_style_from_conversion() {
        assert_eq!(BoxChars::from(BorderStyle::Single), BoxChars::SINGLE);
        assert_eq!(BoxChars::from(BorderStyle::Double), BoxChars::DOUBLE);
        assert_eq!(BoxChars::from(BorderStyle::Round), BoxChars::ROUND);
        assert_eq!(BoxChars::from(BorderStyle::Bold), BoxChars::BOLD);
        assert_eq!(
            BoxChars::from(BorderStyle::SingleDouble),
            BoxChars::SINGLE_DOUBLE
        );
        assert_eq!(
            BoxChars::from(BorderStyle::DoubleSingle),
            BoxChars::DOUBLE_SINGLE
        );
        assert_eq!(BoxChars::from(BorderStyle::Classic), BoxChars::CLASSIC);
        assert_eq!(BoxChars::from(BorderStyle::Arrow), BoxChars::ARROW);
        assert_eq!(BoxChars::from(BorderStyle::None), BoxChars::NONE);
    }

    #[test]
    fn test_border_style_all() {
        let all_styles: Vec<_> = BorderStyle::all().collect();
        assert_eq!(all_styles.len(), 9);
        assert!(all_styles.contains(&BorderStyle::Single));
        assert!(all_styles.contains(&BorderStyle::Double));
    }

    #[test]
    fn test_border_style_from_str_case_insensitive() {
        assert_eq!(
            "SINGLE".parse::<BorderStyle>().unwrap(),
            BorderStyle::Single
        );
        assert_eq!(
            "Double".parse::<BorderStyle>().unwrap(),
            BorderStyle::Double
        );
        assert_eq!("ROUND".parse::<BorderStyle>().unwrap(), BorderStyle::Round);
        assert_eq!("Bold".parse::<BorderStyle>().unwrap(), BorderStyle::Bold);
    }

    #[test]
    fn test_border_style_from_str_kebab_case() {
        assert_eq!(
            "single-double".parse::<BorderStyle>().unwrap(),
            BorderStyle::SingleDouble
        );
        assert_eq!(
            "double-single".parse::<BorderStyle>().unwrap(),
            BorderStyle::DoubleSingle
        );
        assert_eq!(
            "SINGLE-DOUBLE".parse::<BorderStyle>().unwrap(),
            BorderStyle::SingleDouble
        );
        assert_eq!(
            "Double-Single".parse::<BorderStyle>().unwrap(),
            BorderStyle::DoubleSingle
        );
    }

    #[test]
    fn test_border_style_from_str_invalid() {
        assert!("invalid".parse::<BorderStyle>().is_err());
        assert!("".parse::<BorderStyle>().is_err());
        assert!("singleee".parse::<BorderStyle>().is_err());
        assert!("single_".parse::<BorderStyle>().is_err());
    }

    #[test]
    fn test_parse_border_style_error() {
        let error = "invalid".parse::<BorderStyle>().unwrap_err();
        assert_eq!(
            error,
            ParseBorderStyleError::InvalidStyle("invalid".to_string())
        );

        let error_display = error.to_string();
        assert!(error_display.contains("Invalid border style: 'invalid'"));
        assert!(error_display.contains("Did you mean one of:"));
        assert!(error_display.contains("single"));
        assert!(error_display.contains("double"));
    }

    #[test]
    fn test_parse_border_style_error_traits() {
        let error = ParseBorderStyleError::InvalidStyle("test".to_string());

        // Test Debug
        let debug_str = format!("{error:?}");
        assert!(debug_str.contains("InvalidStyle"));

        // Test Error trait
        let _: &dyn std::error::Error = &error;
    }

    #[test]
    fn test_zero_allocation_parsing() {
        // This test ensures our optimized parsing doesn't allocate
        // We can't directly test allocations in unit tests, but we can test
        // that the parsing logic works correctly for edge cases

        // Test exact length matching
        assert!("single".parse::<BorderStyle>().is_ok());
        assert!("singlee".parse::<BorderStyle>().is_err()); // Too long
        assert!("singl".parse::<BorderStyle>().is_err()); // Too short

        // Test case normalization
        assert_eq!(
            "SINGLE".parse::<BorderStyle>().unwrap(),
            BorderStyle::Single
        );
        assert_eq!(
            "single".parse::<BorderStyle>().unwrap(),
            BorderStyle::Single
        );
        assert_eq!(
            "Single".parse::<BorderStyle>().unwrap(),
            BorderStyle::Single
        );

        // Test hyphen/underscore normalization
        assert_eq!(
            "single-double".parse::<BorderStyle>().unwrap(),
            BorderStyle::SingleDouble
        );
        assert_eq!(
            "single_double".parse::<BorderStyle>().unwrap(),
            BorderStyle::SingleDouble
        );
    }

    #[test]
    fn test_comprehensive_style_coverage() {
        // Ensure all BorderStyle variants have corresponding BoxChars
        for style in BorderStyle::all() {
            let chars = BoxChars::from(style);
            let chars_method = style.chars();
            assert_eq!(chars, chars_method);

            // Ensure the conversion is reversible through string representation
            let style_str = style.to_string();
            let parsed_style: BorderStyle = style_str.parse().unwrap();
            assert_eq!(style, parsed_style);
        }
    }

    #[test]
    fn test_unicode_characters() {
        // Test that Unicode characters are correctly stored and retrieved
        let single = BoxChars::SINGLE;
        assert_eq!(single.top_left as u32, 0x250C); //        assert_eq!(single.top as u32, 0x2500); //
        let double = BoxChars::DOUBLE;
        assert_eq!(double.top_left as u32, 0x2554); //        assert_eq!(double.top as u32, 0x2550); //
        let round = BoxChars::ROUND;
        assert_eq!(round.top_left as u32, 0x256D); //        assert_eq!(round.bottom_right as u32, 0x256F); //    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_serialization() {
        use serde_json;

        let single = BoxChars::SINGLE;
        let serialized = serde_json::to_string(&single).unwrap();
        let deserialized: BoxChars = serde_json::from_str(&serialized).unwrap();
        assert_eq!(single, deserialized);

        // Test camelCase field names
        assert!(serialized.contains("topLeft"));
        assert!(serialized.contains("topRight"));
        assert!(serialized.contains("bottomLeft"));
        assert!(serialized.contains("bottomRight"));
    }

    #[test]
    fn test_edge_cases() {
        // Test empty builder
        let empty = BoxChars::builder().build();
        assert_eq!(empty, BoxChars::NONE);

        // Test builder method chaining order doesn't matter
        let box1 = BoxChars::builder()
            .corners('*')
            .horizontal('-')
            .vertical('|')
            .build();
        let box2 = BoxChars::builder()
            .vertical('|')
            .corners('*')
            .horizontal('-')
            .build();
        assert_eq!(box1, box2);

        // Test that builder methods override previous values
        let overridden = BoxChars::builder().corners('*').corners('#').build();
        assert_eq!(overridden.top_left, '#');
        assert_eq!(overridden.top_right, '#');
    }

    #[test]
    fn test_memory_layout() {
        use std::mem;

        // BoxChars should be small and efficiently packed
        assert_eq!(mem::size_of::<BoxChars>(), mem::size_of::<char>() * 8);

        // BorderStyle should be small (single byte enum)
        assert!(mem::size_of::<BorderStyle>() <= mem::size_of::<u8>());

        // Test alignment
        assert_eq!(mem::align_of::<BoxChars>(), mem::align_of::<char>());
    }
}