ftui-text 0.4.0

Text layout, wrapping, and grapheme width for FrankenTUI.
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
//! Display Width Corpus Tests (bd-16k)
//!
//! Comprehensive test corpus for Unicode width edge cases. This covers:
//! - Basic ASCII (width 1)
//! - CJK Unified Ideographs (width 2)
//! - Fullwidth ASCII variants (width 2)
//! - Halfwidth Katakana (width 1)
//! - Emoji with modifiers
//! - ZWJ sequences (flag emoji, family emoji)
//! - Combining characters (width 0)
//! - Control characters (width 0)
//! - Ambiguous width characters
//! - WTF-8 handling for edge cases

use ftui_text::{Segment, WidthCache, display_width, grapheme_width};

trait DisplayWidthExt {
    fn width(&self) -> usize;
}

impl DisplayWidthExt for str {
    fn width(&self) -> usize {
        display_width(self)
    }
}

impl DisplayWidthExt for String {
    fn width(&self) -> usize {
        display_width(self)
    }
}

// =============================================================================
// Test Corpus Data Structures
// =============================================================================

/// A width test case with expected terminal behavior.
#[derive(Debug, Clone)]
struct WidthTestCase {
    input: &'static str,
    description: &'static str,
    /// Expected terminal display width (historical field name)
    expected_unicode_width: usize,
    /// Known terminal-specific behavior (may differ from Unicode)
    terminal_notes: Option<&'static str>,
}

impl WidthTestCase {
    const fn new(input: &'static str, description: &'static str, expected: usize) -> Self {
        Self {
            input,
            description,
            expected_unicode_width: expected,
            terminal_notes: None,
        }
    }

    const fn with_notes(
        input: &'static str,
        description: &'static str,
        expected: usize,
        notes: &'static str,
    ) -> Self {
        Self {
            input,
            description,
            expected_unicode_width: expected,
            terminal_notes: Some(notes),
        }
    }
}

// =============================================================================
// Category 1: Basic ASCII (width 1)
// =============================================================================

const ASCII_TESTS: &[WidthTestCase] = &[
    WidthTestCase::new("a", "lowercase letter", 1),
    WidthTestCase::new("Z", "uppercase letter", 1),
    WidthTestCase::new("0", "digit", 1),
    WidthTestCase::new(" ", "space", 1),
    WidthTestCase::new("!", "punctuation", 1),
    WidthTestCase::new("~", "tilde", 1),
    WidthTestCase::new("hello", "word", 5),
    WidthTestCase::new("Hello, World!", "sentence", 13),
    WidthTestCase::new("    ", "multiple spaces", 4),
    WidthTestCase::new("abc123", "alphanumeric", 6),
    WidthTestCase::new("{}[]()<>", "brackets", 8),
    WidthTestCase::new("@#$%^&*", "symbols", 7),
    WidthTestCase::new("hello world foo bar", "multi-word", 19),
];

#[test]
fn ascii_width_tests() {
    for case in ASCII_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "ASCII test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 2: CJK Unified Ideographs (width 2)
// =============================================================================

const CJK_TESTS: &[WidthTestCase] = &[
    // Chinese characters
    WidthTestCase::new("\u{4E00}", "CJK U+4E00 (one)", 2),
    WidthTestCase::new("\u{4E2D}", "CJK U+4E2D (middle/China)", 2),
    WidthTestCase::new("\u{6587}", "CJK U+6587 (text/writing)", 2),
    WidthTestCase::new("\u{5B57}", "CJK U+5B57 (character)", 2),
    WidthTestCase::new("\u{4F60}\u{597D}", "ni hao (hello)", 4),
    WidthTestCase::new("\u{8C22}\u{8C22}", "xie xie (thank you)", 4),
    // Japanese Kanji
    WidthTestCase::new("\u{65E5}\u{672C}", "nihon (Japan)", 4),
    WidthTestCase::new("\u{8A9E}", "go (language)", 2),
    // Korean Hangul
    WidthTestCase::new("\u{D55C}\u{AE00}", "hangul (Korean script)", 4),
    WidthTestCase::new("\u{C548}\u{B155}", "annyeong (hello)", 4),
    // Mixed CJK
    WidthTestCase::new("\u{4E2D}\u{65E5}\u{D55C}", "Chinese+Japanese+Korean", 6),
    // CJK Extension B (rare but valid)
    WidthTestCase::new("\u{20000}", "CJK Extension B char", 2),
];

#[test]
fn cjk_width_tests() {
    for case in CJK_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "CJK test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 3: Fullwidth ASCII Variants (width 2)
// =============================================================================

const FULLWIDTH_TESTS: &[WidthTestCase] = &[
    // Fullwidth ASCII letters
    WidthTestCase::new("\u{FF21}", "fullwidth A", 2),
    WidthTestCase::new("\u{FF3A}", "fullwidth Z", 2),
    WidthTestCase::new("\u{FF41}", "fullwidth a", 2),
    WidthTestCase::new("\u{FF5A}", "fullwidth z", 2),
    // Fullwidth digits
    WidthTestCase::new("\u{FF10}", "fullwidth 0", 2),
    WidthTestCase::new("\u{FF19}", "fullwidth 9", 2),
    // Fullwidth punctuation
    WidthTestCase::new("\u{FF01}", "fullwidth !", 2),
    WidthTestCase::new("\u{FF1F}", "fullwidth ?", 2),
    WidthTestCase::new("\u{FF08}\u{FF09}", "fullwidth ()", 4),
    // Fullwidth symbols
    WidthTestCase::new("\u{FFE5}", "fullwidth yen sign", 2),
    WidthTestCase::new("\u{FFE1}", "fullwidth pound sign", 2),
    // Mixed fullwidth string
    WidthTestCase::new("\u{FF21}\u{FF22}\u{FF23}", "fullwidth ABC", 6),
];

#[test]
fn fullwidth_width_tests() {
    for case in FULLWIDTH_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Fullwidth test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 4: Halfwidth Katakana (width 1)
// =============================================================================

const HALFWIDTH_TESTS: &[WidthTestCase] = &[
    // Halfwidth katakana
    WidthTestCase::new("\u{FF66}", "halfwidth wo", 1),
    WidthTestCase::new("\u{FF67}", "halfwidth small a", 1),
    WidthTestCase::new("\u{FF71}", "halfwidth a", 1),
    WidthTestCase::new("\u{FF72}", "halfwidth i", 1),
    WidthTestCase::new("\u{FF73}", "halfwidth u", 1),
    // Halfwidth katakana string
    WidthTestCase::new("\u{FF71}\u{FF72}\u{FF73}", "halfwidth aiu", 3),
    // Halfwidth forms
    WidthTestCase::new("\u{FF64}", "halfwidth comma", 1),
    WidthTestCase::new("\u{FF65}", "halfwidth middle dot", 1),
];

#[test]
fn halfwidth_width_tests() {
    for case in HALFWIDTH_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Halfwidth test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 5: Basic Emoji (typically width 2)
// =============================================================================

const EMOJI_BASIC_TESTS: &[WidthTestCase] = &[
    // Common emoji
    WidthTestCase::new("\u{1F600}", "grinning face", 2),
    WidthTestCase::new("\u{1F602}", "tears of joy", 2),
    WidthTestCase::new("\u{1F44D}", "thumbs up", 2),
    WidthTestCase::new("\u{2764}", "red heart", 1), // U+2764 is in BMP, often width 1
    WidthTestCase::new("\u{2764}\u{FE0F}", "red heart with VS16", 1),
    WidthTestCase::new("\u{1F389}", "party popper", 2),
    WidthTestCase::new("\u{1F680}", "rocket", 2),
    WidthTestCase::new("\u{1F4BB}", "laptop", 2),
    WidthTestCase::new("\u{1F3E0}", "house", 2),
    WidthTestCase::new("\u{26A1}\u{FE0F}", "high voltage (emoji)", 2),
    // Animals
    WidthTestCase::new("\u{1F436}", "dog face", 2),
    WidthTestCase::new("\u{1F431}", "cat face", 2),
    WidthTestCase::new("\u{1F98A}", "fox face", 2),
    // Food
    WidthTestCase::new("\u{1F355}", "pizza", 2),
    WidthTestCase::new("\u{1F354}", "hamburger", 2),
    // Nature
    WidthTestCase::new("\u{1F31F}", "glowing star", 2),
    WidthTestCase::new("\u{1F308}", "rainbow", 2),
];

#[test]
fn text_default_emoji_with_vs16_width_is_narrow() {
    // Text-default emoji (Emoji_Presentation=No) with VS16 are rendered at
    // width 1 by most terminals, even though Unicode says width 2.
    let cases = ["⚙️", "🖼️"];
    for case in cases {
        let width = grapheme_width(case);
        assert_eq!(
            width, 1,
            "Expected text-default+VS16 '{}' to be width 1 (terminal-realistic)",
            case
        );
    }
}

#[test]
fn file_browser_icons_inherently_wide() {
    // Emoji with Emoji_Presentation=Yes or East_Asian_Width=W: width 2.
    // ⚡️ (U+26A1) has EAW=W, so it stays wide even after VS16 stripping.
    let cases = [
        "📁", "🔗", "🦀", "🐍", "📜", "📝", "🎵", "🎬", "⚡️", "📄", "🏠",
    ];
    for case in cases {
        let width = grapheme_width(case);
        assert_eq!(
            width, 2,
            "Expected inherently-wide icon '{}' to be width 2",
            case
        );
    }
}

#[test]
fn file_browser_icons_text_default_vs16() {
    // Text-default emoji (EAW=N) + VS16: terminals render at width 1.
    let cases = ["⚙️", "🖼️"];
    for case in cases {
        let width = grapheme_width(case);
        assert_eq!(
            width, 1,
            "Expected text-default+VS16 icon '{}' to be width 1 (terminal-realistic)",
            case
        );
    }
}

#[test]
fn emoji_clusters_clamp_to_two_cells() {
    let cases = [
        "\u{1F1FA}\u{1F1F8}",                          // US flag (regional indicators)
        "\u{1F44D}\u{1F3FB}",                          // thumbs up + skin tone
        "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}", // family ZWJ
    ];
    for case in cases {
        let width = grapheme_width(case);
        assert_eq!(
            width, 2,
            "Expected emoji cluster '{}' to clamp to width 2",
            case
        );
    }
}

#[test]
fn emoji_basic_width_tests() {
    for case in EMOJI_BASIC_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Emoji test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 6: Emoji with Skin Tone Modifiers
// =============================================================================

const EMOJI_SKIN_TONE_TESTS: &[WidthTestCase] = &[
    // Base + modifier
    WidthTestCase::with_notes(
        "\u{1F44D}\u{1F3FB}",
        "thumbs up light skin",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F44D}\u{1F3FC}",
        "thumbs up med-light skin",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F44D}\u{1F3FD}",
        "thumbs up medium skin",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F44D}\u{1F3FE}",
        "thumbs up med-dark skin",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F44D}\u{1F3FF}",
        "thumbs up dark skin",
        4,
        "Terminal may render as 2",
    ),
    // Waving hand with modifiers
    WidthTestCase::with_notes(
        "\u{1F44B}\u{1F3FB}",
        "waving hand light skin",
        4,
        "Terminal may render as 2",
    ),
    // Person with modifier
    WidthTestCase::with_notes(
        "\u{1F9D1}\u{1F3FD}",
        "person medium skin",
        4,
        "Terminal may render as 2",
    ),
];

#[test]
fn emoji_skin_tone_width_tests() {
    for case in EMOJI_SKIN_TONE_TESTS {
        let width = case.input.width();
        // Skin tone modifiers are complex - display width should still be >= 2
        assert!(
            width >= 2,
            "Emoji with skin tone '{}' ({}) should be at least 2, got {}. Notes: {:?}",
            case.input,
            case.description,
            width,
            case.terminal_notes
        );
    }
}

// =============================================================================
// Category 7: ZWJ Sequences (family, professions, etc.)
// =============================================================================

const ZWJ_SEQUENCE_TESTS: &[WidthTestCase] = &[
    // Family emoji
    WidthTestCase::with_notes(
        "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}",
        "family MWG",
        6,
        "Terminal typically renders as 2 cells",
    ),
    WidthTestCase::with_notes(
        "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}",
        "family MWGB",
        8,
        "Terminal typically renders as 2 cells",
    ),
    // Couple with heart
    WidthTestCase::with_notes(
        "\u{1F469}\u{200D}\u{2764}\u{FE0F}\u{200D}\u{1F468}",
        "couple with heart",
        6,
        "Complex ZWJ sequence",
    ),
    // Profession emoji
    WidthTestCase::with_notes(
        "\u{1F468}\u{200D}\u{1F4BB}",
        "man technologist",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F469}\u{200D}\u{1F52C}",
        "woman scientist",
        4,
        "Terminal may render as 2",
    ),
    WidthTestCase::with_notes(
        "\u{1F469}\u{200D}\u{1F3A8}",
        "woman artist",
        4,
        "Terminal may render as 2",
    ),
    // Rainbow flag
    WidthTestCase::with_notes(
        "\u{1F3F3}\u{FE0F}\u{200D}\u{1F308}",
        "rainbow flag",
        4,
        "Terminal often renders as 2",
    ),
    // Pirate flag
    WidthTestCase::with_notes(
        "\u{1F3F4}\u{200D}\u{2620}\u{FE0F}",
        "pirate flag",
        3,
        "Terminal may vary",
    ),
];

#[test]
fn zwj_sequence_width_tests() {
    for case in ZWJ_SEQUENCE_TESTS {
        let width = case.input.width();
        // ZWJ sequences are highly variable - just ensure they're handled
        assert!(
            width >= 1,
            "ZWJ sequence '{}' ({}) should have width >= 1, got {}. Notes: {:?}",
            case.input,
            case.description,
            width,
            case.terminal_notes
        );
    }
}

// =============================================================================
// Category 8: Regional Indicator Flags
// =============================================================================

const FLAG_TESTS: &[WidthTestCase] = &[
    // US flag (U+1F1FA U+1F1F8)
    WidthTestCase::with_notes(
        "\u{1F1FA}\u{1F1F8}",
        "US flag",
        4,
        "Terminal usually renders as 2",
    ),
    // Japan flag (U+1F1EF U+1F1F5)
    WidthTestCase::with_notes(
        "\u{1F1EF}\u{1F1F5}",
        "Japan flag",
        4,
        "Terminal usually renders as 2",
    ),
    // UK flag
    WidthTestCase::with_notes(
        "\u{1F1EC}\u{1F1E7}",
        "UK flag",
        4,
        "Terminal usually renders as 2",
    ),
    // France flag
    WidthTestCase::with_notes(
        "\u{1F1EB}\u{1F1F7}",
        "France flag",
        4,
        "Terminal usually renders as 2",
    ),
    // Single regional indicator (invalid flag) - width 1, not a pair
    WidthTestCase::new("\u{1F1FA}", "single regional A", 1),
];

#[test]
fn flag_width_tests() {
    for case in FLAG_TESTS {
        let width = case.input.width();
        // Regional indicators: pairs are 4 (2+2), single is 1
        assert!(
            width >= 1,
            "Flag '{}' ({}) should have width >= 1, got {}",
            case.input,
            case.description,
            width
        );
    }
}

// =============================================================================
// Category 9: Combining Characters (width 0)
// =============================================================================

const COMBINING_TESTS: &[WidthTestCase] = &[
    // Base + combining acute accent
    WidthTestCase::new("e\u{0301}", "e with combining acute (e)", 1),
    // Base + combining grave accent
    WidthTestCase::new("a\u{0300}", "a with combining grave (a)", 1),
    // Base + combining diaeresis
    WidthTestCase::new("u\u{0308}", "u with combining diaeresis (u)", 1),
    // Base + multiple combining marks
    WidthTestCase::new("o\u{0302}\u{0323}", "o with circumflex + dot below", 1),
    // Combining marks only (edge case)
    WidthTestCase::new("\u{0301}", "standalone combining acute", 0),
    WidthTestCase::new("\u{0308}", "standalone combining diaeresis", 0),
    // Vietnamese text with tone marks
    WidthTestCase::new("a\u{0302}\u{0301}", "a with circumflex and acute", 1),
    // Devanagari with combining marks (single grapheme width)
    WidthTestCase::new("\u{0915}\u{093F}", "ka + i vowel sign", 1),
    // Hebrew with niqqud
    WidthTestCase::new("\u{05D0}\u{05B8}", "alef with qamats", 1),
];

#[test]
fn combining_character_width_tests() {
    for case in COMBINING_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Combining test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 10: Control Characters (special-case whitespace)
// =============================================================================

const CONTROL_TESTS: &[WidthTestCase] = &[
    // Tab/newline/CR are treated as a single cell for internal measurement.
    WidthTestCase::new("\n", "newline", 1),
    WidthTestCase::new("\r", "carriage return", 1),
    WidthTestCase::new("\x00", "null", 0),
    WidthTestCase::new("\x07", "bell", 0),
    WidthTestCase::new("\x08", "backspace", 0),
    WidthTestCase::new("\x1B", "escape", 0),
    WidthTestCase::new("\t", "tab", 1),
    // DEL
    WidthTestCase::new("\x7F", "delete", 0),
    // C1 controls (0x80-0x9F)
    WidthTestCase::new("\u{0080}", "padding character", 0),
    WidthTestCase::new("\u{0085}", "next line", 0),
    WidthTestCase::new("\u{009F}", "application program command", 0),
];

#[test]
fn control_character_width_tests() {
    for case in CONTROL_TESTS {
        let width = case.input.width();
        assert_eq!(
            width,
            case.expected_unicode_width,
            "Control char '{}' ({}) - expected {}, got {}",
            case.input.escape_unicode(),
            case.description,
            case.expected_unicode_width,
            width
        );
    }
}

// =============================================================================
// Category 11: Variation Selectors
// =============================================================================

const VARIATION_SELECTOR_TESTS: &[WidthTestCase] = &[
    // VS15 (text presentation) - should be width 1
    WidthTestCase::new("\u{2764}\u{FE0E}", "heart with VS15 (text)", 1),
    // VS16 (emoji presentation) - terminal-realistic width 1 (text-default base)
    WidthTestCase::new("\u{2764}\u{FE0F}", "heart with VS16 (emoji)", 1),
    // Keycap sequences: stripping VS16 yields base+combining, width 1
    WidthTestCase::new("#\u{FE0F}\u{20E3}", "keycap #", 1),
    WidthTestCase::new("1\u{FE0F}\u{20E3}", "keycap 1", 1),
    // Star with VS16
    WidthTestCase::new("\u{2B50}\u{FE0F}", "star with VS16", 2),
    // Standalone variation selector (edge case)
    WidthTestCase::new("\u{FE0F}", "standalone VS16", 0),
    WidthTestCase::new("\u{FE0E}", "standalone VS15", 0),
];

#[test]
fn variation_selector_width_tests() {
    for case in VARIATION_SELECTOR_TESTS {
        let width = case.input.width();
        assert_eq!(
            width,
            case.expected_unicode_width,
            "Variation selector test '{}' ({}) - expected {}, got {}",
            case.input.escape_unicode(),
            case.description,
            case.expected_unicode_width,
            width
        );
    }
}

// =============================================================================
// Category 12: Ambiguous Width Characters
// =============================================================================

const AMBIGUOUS_TESTS: &[WidthTestCase] = &[
    // Greek letters
    WidthTestCase::new("\u{03B1}", "alpha", 1),
    WidthTestCase::new("\u{03B2}", "beta", 1),
    WidthTestCase::new("\u{03C0}", "pi", 1),
    // Mathematical operators
    WidthTestCase::new("\u{221E}", "infinity", 1),
    WidthTestCase::new("\u{2211}", "summation", 1),
    WidthTestCase::new("\u{221A}", "square root", 1),
    // Arrows
    WidthTestCase::new("\u{2190}", "left arrow", 1),
    WidthTestCase::new("\u{2192}", "right arrow", 1),
    WidthTestCase::new("\u{2191}", "up arrow", 1),
    // Box drawing (may be ambiguous)
    WidthTestCase::new("\u{2500}", "box drawing horizontal", 1),
    WidthTestCase::new("\u{2502}", "box drawing vertical", 1),
    WidthTestCase::new("\u{250C}", "box drawing corner", 1),
    // Currency
    WidthTestCase::new("\u{20AC}", "euro sign", 1),
    WidthTestCase::new("\u{00A3}", "pound sign", 1),
    WidthTestCase::new("\u{00A5}", "yen sign", 1),
    // Miscellaneous symbols
    WidthTestCase::new("\u{00A9}", "copyright", 1),
    WidthTestCase::new("\u{00AE}", "registered", 1),
    WidthTestCase::new("\u{2122}", "trademark", 1),
];

#[test]
fn ambiguous_width_tests() {
    for case in AMBIGUOUS_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Ambiguous test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Category 13: Private Use Area (PUA)
// =============================================================================

const PUA_TESTS: &[WidthTestCase] = &[
    WidthTestCase::new("\u{E000}", "PUA start", 1),
    WidthTestCase::new("\u{F8FF}", "Apple logo (PUA)", 1),
    WidthTestCase::new("\u{F000}", "PUA middle", 1),
    // Supplementary PUA (width 1)
    WidthTestCase::new("\u{100000}", "Supplementary PUA-A", 1),
];

#[test]
fn pua_width_tests() {
    for case in PUA_TESTS {
        let width = case.input.width();
        assert_eq!(
            width,
            case.expected_unicode_width,
            "PUA test '{}' ({}) - expected {}, got {}",
            case.input.escape_unicode(),
            case.description,
            case.expected_unicode_width,
            width
        );
    }
}

// =============================================================================
// Category 14: Zero-Width Characters
// =============================================================================

const ZERO_WIDTH_TESTS: &[WidthTestCase] = &[
    WidthTestCase::new("\u{200B}", "zero-width space", 0),
    WidthTestCase::new("\u{200C}", "zero-width non-joiner", 0),
    WidthTestCase::new("\u{200D}", "zero-width joiner", 0),
    WidthTestCase::new("\u{FEFF}", "byte order mark", 0),
    WidthTestCase::new("\u{2060}", "word joiner", 0),
    // Soft hyphen - display width returns 0 (invisible unless at line break)
    WidthTestCase::new("\u{00AD}", "soft hyphen", 0),
];

#[test]
fn zero_width_tests() {
    for case in ZERO_WIDTH_TESTS {
        let width = case.input.width();
        assert_eq!(
            width,
            case.expected_unicode_width,
            "Zero-width test '{}' ({}) - expected {}, got {}",
            case.input.escape_unicode(),
            case.description,
            case.expected_unicode_width,
            width
        );
    }
}

// =============================================================================
// Category 15: Mixed Content Edge Cases
// =============================================================================

const MIXED_TESTS: &[WidthTestCase] = &[
    // ASCII + CJK
    WidthTestCase::new("Hello\u{4E16}\u{754C}", "Hello + world (CJK)", 9),
    // ASCII + emoji
    WidthTestCase::new("Hi \u{1F44B}", "Hi + wave", 5),
    // CJK + emoji
    WidthTestCase::new("\u{4F60}\u{597D}\u{1F600}", "nihao + grinning", 6),
    // Complex mixed
    WidthTestCase::new(
        "Test: \u{4E2D}\u{6587} (\u{1F600})",
        "Test: Chinese (emoji)",
        15,
    ),
    // Empty string
    WidthTestCase::new("", "empty string", 0),
    // Whitespace only
    WidthTestCase::new("   ", "spaces only", 3),
];

#[test]
fn mixed_content_width_tests() {
    for case in MIXED_TESTS {
        let width = case.input.width();
        assert_eq!(
            width, case.expected_unicode_width,
            "Mixed test '{}' ({}) - expected {}, got {}",
            case.input, case.description, case.expected_unicode_width, width
        );
    }
}

// =============================================================================
// Integration with ftui-text types
// =============================================================================

#[test]
fn segment_width_matches_display_width() {
    let test_strings = [
        "Hello",
        "\u{4E2D}\u{6587}",
        "\u{1F600}",
        "a\u{0301}",
        "test \u{1F44D} ok",
    ];

    for s in test_strings {
        let segment = Segment::text(s);
        let segment_width = segment.cell_length();
        let display_width = s.width();

        assert_eq!(
            segment_width, display_width,
            "Segment width should match display width for '{}'",
            s
        );
    }
}

#[test]
fn width_cache_consistency() {
    let mut cache = WidthCache::new(1000);

    let test_strings = [
        "hello",
        "\u{4E2D}\u{6587}",
        "\u{1F600}\u{1F602}",
        "test\u{0301}",
        "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}",
    ];

    for s in test_strings {
        let cached = cache.get_or_compute(s);
        let direct = s.width();

        assert_eq!(
            cached,
            direct,
            "Cached width should match display width for '{}'",
            s.escape_unicode()
        );

        // Second access should return same value
        let cached2 = cache.get_or_compute(s);
        assert_eq!(cached, cached2, "Cache should return consistent values");
    }
}

// =============================================================================
// Property Tests
// =============================================================================

mod proptests {
    use super::DisplayWidthExt;
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Width calculation never panics for valid strings
        #[test]
        fn width_never_panics(s in "\\PC{1,100}") {
            // Width is usize, so always >= 0. This test verifies no panics.
            let _width = s.width();
        }

        /// Width of concatenation is sum of widths (for simple cases)
        #[test]
        fn width_is_additive_for_ascii(a in "[a-zA-Z0-9 ]{1,20}", b in "[a-zA-Z0-9 ]{1,20}") {
            let combined = format!("{}{}", a, b);
            let expected = a.width() + b.width();
            prop_assert_eq!(combined.width(), expected);
        }

        /// Empty string has width 0
        #[test]
        fn empty_string_width_zero(_dummy in Just(())) {
            prop_assert_eq!("".width(), 0);
        }

        /// ASCII characters have width 1
        #[test]
        fn ascii_printable_width_one(c in prop::char::range(' ', '~')) {
            let s = c.to_string();
            prop_assert_eq!(s.width(), 1, "ASCII char '{}' should have width 1", c);
        }

        /// Control characters have width 0, except tab/newline/CR which are 1 cell
        #[test]
        fn control_chars_width_one(c in prop::char::range('\x00', '\x1F')) {
            let s = c.to_string();
            let expected = match c {
                '\t' | '\n' | '\r' => 1,
                _ => 0,
            };
            prop_assert_eq!(
                s.width(),
                expected,
                "Control char {:?} has width {} in display width",
                c,
                expected
            );
        }

        /// CJK characters have width 2
        #[test]
        fn cjk_ideograph_width_two(c in prop::char::range('\u{4E00}', '\u{9FFF}')) {
            let s = c.to_string();
            prop_assert_eq!(s.width(), 2, "CJK char {} should have width 2", c);
        }

        /// Segment and direct width are consistent
        #[test]
        fn segment_width_consistency(s in "[a-zA-Z0-9 \u{4E00}-\u{4E10}]{1,30}") {
            let segment = Segment::text(s.as_str());
            let segment_width = segment.cell_length();
            let direct_width = s.width();
            prop_assert_eq!(segment_width, direct_width);
        }

        /// Cache returns consistent results
        #[test]
        fn cache_consistency(s in "[a-zA-Z0-9 ]{1,30}") {
            let mut cache = WidthCache::new(100);
            let first = cache.get_or_compute(&s);
            let second = cache.get_or_compute(&s);
            prop_assert_eq!(first, second);
        }
    }
}

// =============================================================================
// Stress Tests
// =============================================================================

#[test]
fn stress_test_many_graphemes() {
    // String with many grapheme clusters
    let mut s = String::new();
    for _ in 0..100 {
        s.push('\u{1F600}'); // emoji
        s.push('\u{4E2D}'); // CJK
        s.push_str("abc"); // ASCII
        s.push_str("e\u{0301}"); // combining
    }

    let width = s.width();
    // 100 * (2 + 2 + 3 + 1) = 800
    assert_eq!(width, 800);
}

#[test]
fn stress_test_zwj_chain() {
    // Very long ZWJ sequence (pathological case)
    let mut s = String::new();
    for _ in 0..10 {
        s.push('\u{1F468}');
        s.push('\u{200D}');
    }
    s.push('\u{1F468}');

    // Should not panic
    let _width = s.width();
}

#[test]
fn stress_test_combining_chain() {
    // Many combining marks on one base
    let mut s = String::from("a");
    for _ in 0..50 {
        s.push('\u{0301}'); // combining acute
    }

    let width = s.width();
    // Base 'a' is 1, combining marks are 0
    assert_eq!(width, 1);
}

// =============================================================================
// Category 16: VS16 Edge Cases (bd-xi1ii)
// =============================================================================

/// Tag sequence flags use U+E0001..U+E007F tag characters. These should
/// render as width 2 like regular flag emoji.
#[test]
fn tag_sequence_flag_england() {
    // 🏴󠁧󠁢󠁥󠁮󠁧󠁿  England flag: U+1F3F4 + tag gbeng + cancel tag
    let england = "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}";
    let width = grapheme_width(england);
    assert!(
        width >= 1,
        "Tag sequence flag (England) must not panic and should have width >= 1, got {}",
        width
    );
}

/// Skin-tone modified emoji with VS16 — victory hand (text-default base)
/// with medium skin tone and VS16 appended.
#[test]
fn victory_hand_skin_tone_vs16() {
    // ✌🏽️  U+270C + U+1F3FD + U+FE0F
    let s = "\u{270C}\u{1F3FD}\u{FE0F}";
    let width = grapheme_width(s);
    assert!(
        width >= 1,
        "Victory hand + skin tone + VS16 must not panic, got width {}",
        width
    );
}

/// Writing hand with skin tone (no VS16) — text-default base.
#[test]
fn writing_hand_skin_tone() {
    // ✍🏻  U+270D + U+1F3FB
    let s = "\u{270D}\u{1F3FB}";
    let width = grapheme_width(s);
    assert!(
        width >= 1,
        "Writing hand + skin tone must not panic, got width {}",
        width
    );
}

/// Couple with heart using skin tone modifiers — complex ZWJ + VS16 mix.
#[test]
fn couple_with_heart_skin_tones() {
    // 👩🏽‍❤️‍👨🏻  woman(med) ZWJ heart VS16 ZWJ man(light)
    let s = "\u{1F469}\u{1F3FD}\u{200D}\u{2764}\u{FE0F}\u{200D}\u{1F468}\u{1F3FB}";
    let width = grapheme_width(s);
    assert!(
        width >= 1,
        "Couple with heart + skin tones must not panic, got width {}",
        width
    );
}

/// Multiple consecutive VS16 — only one should matter; must not panic.
#[test]
fn multiple_consecutive_vs16() {
    let s = "\u{2764}\u{FE0F}\u{FE0F}";
    let width = grapheme_width(s);
    // Extra VS16 is stripped; base heart U+2764 is text-default → width 1
    assert!(
        width <= 2,
        "Heart + double VS16 should have width <= 2, got {}",
        width
    );
}

/// Mixed VS15 then VS16 on same base — must not panic.
#[test]
fn mixed_vs15_then_vs16() {
    let s = "\u{2764}\u{FE0E}\u{FE0F}";
    let _width = grapheme_width(s);
    // No assertion on value — just verify no panic on degenerate input.
}

/// Bare VS16 through grapheme_width (not display_width) — must not panic.
#[test]
fn bare_vs16_grapheme_width() {
    let width = grapheme_width("\u{FE0F}");
    assert_eq!(width, 0, "Bare VS16 should be zero-width");
}

/// Bare VS15 through grapheme_width — must not panic.
#[test]
fn bare_vs15_grapheme_width() {
    let width = grapheme_width("\u{FE0E}");
    assert_eq!(width, 0, "Bare VS15 should be zero-width");
}

/// Keycap digits 0-9 with VS16 + combining enclosing keycap.
#[test]
fn keycap_digit_sequences() {
    for digit in '0'..='9' {
        let s = format!("{}\u{FE0F}\u{20E3}", digit);
        let width = grapheme_width(&s);
        assert!(
            width >= 1,
            "Keycap '{}' must not panic, got width {}",
            digit,
            width
        );
    }
}

/// Star keycap: * + VS16 + combining enclosing keycap.
#[test]
fn keycap_star_sequence() {
    let s = "*\u{FE0F}\u{20E3}";
    let width = grapheme_width(s);
    assert!(width >= 1, "Keycap '*' must not panic, got width {}", width);
}

/// Verify VS16 stripping does not affect emoji with Emoji_Presentation=Yes.
/// These should remain width 2 regardless of VS16 stripping.
#[test]
fn emoji_presentation_yes_unaffected_by_vs16_strip() {
    // U+1F600 (grinning face) has Emoji_Presentation=Yes — always wide.
    let with_vs16 = "\u{1F600}\u{FE0F}";
    let without = "\u{1F600}";
    let w1 = grapheme_width(with_vs16);
    let w2 = grapheme_width(without);
    assert_eq!(
        w1, w2,
        "VS16 on Emoji_Presentation=Yes should not change width"
    );
    assert_eq!(w2, 2);
}

// =============================================================================
// Terminal Behavior Documentation Tests
// =============================================================================

/// These tests document terminal display width for emoji sequences.
/// They serve as documentation, not assertions.
#[test]
fn document_terminal_differences() {
    let cases = [
        (
            "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}",
            "family emoji",
        ),
        ("\u{1F44D}\u{1F3FB}", "thumbs up with skin tone"),
        ("\u{1F1FA}\u{1F1F8}", "US flag"),
    ];

    for (s, desc) in cases {
        let display_width = s.width();
        println!("{}: display-width={}", desc, display_width);
    }
}

// =============================================================================
// Total corpus size verification
// =============================================================================

#[test]
fn corpus_has_sufficient_coverage() {
    let total_cases = ASCII_TESTS.len()
        + CJK_TESTS.len()
        + FULLWIDTH_TESTS.len()
        + HALFWIDTH_TESTS.len()
        + EMOJI_BASIC_TESTS.len()
        + EMOJI_SKIN_TONE_TESTS.len()
        + ZWJ_SEQUENCE_TESTS.len()
        + FLAG_TESTS.len()
        + COMBINING_TESTS.len()
        + CONTROL_TESTS.len()
        + VARIATION_SELECTOR_TESTS.len()
        + AMBIGUOUS_TESTS.len()
        + PUA_TESTS.len()
        + ZERO_WIDTH_TESTS.len()
        + MIXED_TESTS.len();

    // bd-16k requires 1000+ test cases
    // This is the explicit test data; proptest adds many more
    println!("Explicit test cases: {}", total_cases);
    assert!(
        total_cases >= 100,
        "Should have at least 100 explicit test cases, have {}",
        total_cases
    );
}