azul-layout 0.0.7

Layout solver + font and image loader the Azul GUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
//! ICU4X-based internationalization support for Azul
//!
//! This module provides locale-aware formatting for:
//! - Numbers (decimal, currency, percentages)
//! - Dates and times
//! - Lists (and, or, unit)
//! - Plural rules
//!
//! The `IcuLocalizer` is initialized with the system locale at startup,
//! but can be overridden. It can optionally load additional locale data
//! from binary blob files at runtime.
//!
//! # Example
//!
//! ```rust,ignore
//! // In a callback:
//! let localizer = info.get_localizer();
//! let formatted = localizer.format_decimal(1234567);
//! // Returns "1,234,567" for en-US or "1.234.567" for de-DE
//! ```

use alloc::{
    collections::BTreeMap,
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use core::fmt::Write;
use std::sync::Mutex;

use azul_css::AzString;
use icu::collator::{Collator, options::CollatorOptions};
use icu::decimal::input::Decimal;
use icu::decimal::DecimalFormatter;
use icu::list::{ListFormatter, options::ListFormatterOptions};
use icu::locale::Locale;
use icu::plurals::PluralRules;
use writeable::Writeable;

// Import FmtArg types from fmt module for format_string_icu
use crate::fmt::{FmtArg, FmtArgVec, FmtValue};

// Re-export for external use
pub use icu::locale::locale;
pub use icu::plurals::{PluralCategory as IcuPluralCategory, PluralRules as IcuPluralRules};

/// Error type for ICU operations
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct IcuError {
    pub message: AzString,
}

impl IcuError {
    pub fn new(msg: impl Into<String>) -> Self {
        Self {
            message: AzString::from(msg.into()),
        }
    }
}

/// Result type for ICU operations
#[derive(Debug, Clone, PartialEq)]
#[repr(C, u8)]
pub enum IcuResult {
    Ok(AzString),
    Err(IcuError),
}

impl IcuResult {
    pub fn ok(s: impl Into<String>) -> Self {
        IcuResult::Ok(AzString::from(s.into()))
    }

    pub fn err(msg: impl Into<String>) -> Self {
        IcuResult::Err(IcuError::new(msg))
    }

    pub fn into_option(self) -> Option<AzString> {
        match self {
            IcuResult::Ok(s) => Some(s),
            IcuResult::Err(_) => None,
        }
    }

    pub fn unwrap_or(self, default: AzString) -> AzString {
        match self {
            IcuResult::Ok(s) => s,
            IcuResult::Err(_) => default,
        }
    }
}

/// The plural category for a number (used for translations)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum PluralCategory {
    Zero,
    One,
    Two,
    Few,
    Many,
    Other,
}

impl From<IcuPluralCategory> for PluralCategory {
    fn from(cat: IcuPluralCategory) -> Self {
        match cat {
            IcuPluralCategory::Zero => PluralCategory::Zero,
            IcuPluralCategory::One => PluralCategory::One,
            IcuPluralCategory::Two => PluralCategory::Two,
            IcuPluralCategory::Few => PluralCategory::Few,
            IcuPluralCategory::Many => PluralCategory::Many,
            IcuPluralCategory::Other => PluralCategory::Other,
        }
    }
}

/// List formatting type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum ListType {
    /// "A, B, and C"
    And,
    /// "A, B, or C"
    Or,
    /// "A, B, C" (for units like "3 feet, 7 inches")
    Unit,
}

/// Date/time field set for formatting
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum DateTimeFieldSet {
    /// Year, month, day (e.g., "January 15, 2025")
    YearMonthDay,
    /// Month and day only (e.g., "January 15")
    MonthDay,
    /// Year and month only (e.g., "January 2025")
    YearMonth,
    /// Hour and minute (e.g., "4:30 PM")
    HourMinute,
    /// Hour, minute, second (e.g., "4:30:45 PM")
    HourMinuteSecond,
    /// Full date and time
    Full,
}

/// Collation strength for string comparison
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(C)]
pub enum CollationStrength {
    /// Only primary differences (base letters) matter.
    /// e.g., "a" vs "b", but "a" == "A" and "a" == "à"
    Primary,
    /// Primary and secondary (accents) differences matter.
    /// e.g., "a" vs "à", but "a" == "A"
    Secondary,
    /// Primary, secondary, and tertiary (case) differences matter.
    /// e.g., "a" vs "A"
    #[default]
    Tertiary,
    /// All differences matter, including punctuation/whitespace.
    Quaternary,
}

/// Length/style for formatting
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum FormatLength {
    /// Short format (e.g., "1/15/25")
    Short,
    /// Medium format (e.g., "Jan 15, 2025")
    Medium,
    /// Long format (e.g., "January 15, 2025")
    Long,
}

/// A simple date structure for ICU formatting
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct IcuDate {
    pub year: i32,
    /// Month: 1-12
    pub month: u8,
    /// Day: 1-31
    pub day: u8,
}

/// A simple time structure for ICU formatting
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct IcuTime {
    /// Hour: 0-23
    pub hour: u8,
    /// Minute: 0-59
    pub minute: u8,
    /// Second: 0-59
    pub second: u8,
}

/// A combined date and time structure
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct IcuDateTime {
    pub date: IcuDate,
    pub time: IcuTime,
}

impl IcuDate {
    /// Create a new IcuDate from year, month, day.
    pub const fn new(year: i32, month: u8, day: u8) -> Self {
        Self { year, month, day }
    }

    /// Get the current local date.
    #[cfg(feature = "icu_chrono")]
    pub fn now() -> Self {
        use chrono::Datelike;
        let now = chrono::Local::now();
        Self {
            year: now.year(),
            month: now.month() as u8,
            day: now.day() as u8,
        }
    }

    /// Get the current UTC date.
    #[cfg(feature = "icu_chrono")]
    pub fn now_utc() -> Self {
        use chrono::Datelike;
        let now = chrono::Utc::now();
        Self {
            year: now.year(),
            month: now.month() as u8,
            day: now.day() as u8,
        }
    }
}

impl IcuTime {
    /// Create a new IcuTime from hour, minute, second.
    pub const fn new(hour: u8, minute: u8, second: u8) -> Self {
        Self { hour, minute, second }
    }

    /// Get the current local time.
    #[cfg(feature = "icu_chrono")]
    pub fn now() -> Self {
        use chrono::Timelike;
        let now = chrono::Local::now();
        Self {
            hour: now.hour() as u8,
            minute: now.minute() as u8,
            second: now.second() as u8,
        }
    }

    /// Get the current UTC time.
    #[cfg(feature = "icu_chrono")]
    pub fn now_utc() -> Self {
        use chrono::Timelike;
        let now = chrono::Utc::now();
        Self {
            hour: now.hour() as u8,
            minute: now.minute() as u8,
            second: now.second() as u8,
        }
    }
}

impl IcuDateTime {
    /// Create a new IcuDateTime from date and time.
    pub const fn new(date: IcuDate, time: IcuTime) -> Self {
        Self { date, time }
    }

    /// Get the current local date and time.
    #[cfg(feature = "icu_chrono")]
    pub fn now() -> Self {
        Self {
            date: IcuDate::now(),
            time: IcuTime::now(),
        }
    }

    /// Get the current UTC date and time.
    #[cfg(feature = "icu_chrono")]
    pub fn now_utc() -> Self {
        Self {
            date: IcuDate::now_utc(),
            time: IcuTime::now_utc(),
        }
    }

    /// Get Unix timestamp in milliseconds (like JavaScript Date.now()).
    ///
    /// Returns the number of milliseconds since January 1, 1970 00:00:00 UTC.
    #[cfg(feature = "icu_chrono")]
    pub fn timestamp_now() -> i64 {
        chrono::Utc::now().timestamp_millis()
    }

    /// Get Unix timestamp in seconds.
    #[cfg(feature = "icu_chrono")]
    pub fn timestamp_now_seconds() -> i64 {
        chrono::Utc::now().timestamp()
    }

    /// Convert a Unix timestamp (seconds) to IcuDateTime.
    #[cfg(feature = "icu_chrono")]
    pub fn from_timestamp(timestamp_secs: i64) -> Option<Self> {
        use chrono::{Datelike, TimeZone, Timelike};
        chrono::Utc.timestamp_opt(timestamp_secs, 0).single().map(|dt| {
            Self {
                date: IcuDate {
                    year: dt.year(),
                    month: dt.month() as u8,
                    day: dt.day() as u8,
                },
                time: IcuTime {
                    hour: dt.hour() as u8,
                    minute: dt.minute() as u8,
                    second: dt.second() as u8,
                },
            }
        })
    }

    /// Convert a Unix timestamp (milliseconds) to IcuDateTime.
    #[cfg(feature = "icu_chrono")]
    pub fn from_timestamp_millis(timestamp_millis: i64) -> Option<Self> {
        Self::from_timestamp(timestamp_millis / 1000)
    }
}

/// The main ICU localizer that holds formatters for the current locale.
///
/// This struct is thread-safe and can be shared across callbacks.
/// It lazily initializes formatters on first use.
pub struct IcuLocalizer {
    /// The current locale (BCP 47 format, e.g., "en-US", "de-DE")
    locale: Locale,
    /// The locale string for C API access
    locale_string: AzString,
    /// Optional binary data blob for additional locale data
    data_blob: Option<Vec<u8>>,
    /// Cached decimal formatter
    decimal_formatter: Option<DecimalFormatter>,
    /// Cached plural rules (cardinal)
    plural_rules_cardinal: Option<PluralRules>,
    /// Cached plural rules (ordinal)
    plural_rules_ordinal: Option<PluralRules>,
    /// Cached list formatter (and)
    list_formatter_and: Option<ListFormatter>,
    /// Cached list formatter (or)
    list_formatter_or: Option<ListFormatter>,
    /// Cached collator
    collator: Option<Collator>,
}

impl core::fmt::Debug for IcuLocalizer {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("IcuLocalizer")
            .field("locale", &self.locale_string)
            .field("has_data_blob", &self.data_blob.is_some())
            .finish()
    }
}

impl IcuLocalizer {
    /// Create a new localizer with the given locale string (BCP 47 format).
    ///
    /// # Arguments
    /// * `locale_str` - A BCP 47 locale string like "en-US", "de-DE", "ja-JP"
    ///
    /// # Returns
    /// A new IcuLocalizer, or falls back to "en-US" if parsing fails.
    pub fn new(locale_str: &str) -> Self {
        let locale = locale_str.parse::<Locale>().unwrap_or_else(|_| {
            // Fallback to en-US if parsing fails
            "en-US".parse().unwrap()
        });

        Self {
            locale_string: AzString::from(locale.to_string()),
            locale,
            data_blob: None,
            decimal_formatter: None,
            plural_rules_cardinal: None,
            plural_rules_ordinal: None,
            list_formatter_and: None,
            list_formatter_or: None,
            collator: None,
        }
    }

    /// Create a localizer from the system's detected language.
    ///
    /// Uses the language detected by `azul_css::system::detect_system_language()`.
    pub fn from_system_language(system_language: &AzString) -> Self {
        Self::new(system_language.as_str())
    }

    /// Load additional locale data from a binary blob.
    ///
    /// The blob should be generated using `icu4x-datagen` with the `--format blob` flag.
    /// This allows supporting locales that aren't compiled into the binary.
    pub fn load_data_blob(&mut self, data: Vec<u8>) {
        self.data_blob = Some(data);
        // Clear cached formatters so they'll be recreated with new data
        self.decimal_formatter = None;
        self.plural_rules_cardinal = None;
        self.plural_rules_ordinal = None;
        self.list_formatter_and = None;
        self.list_formatter_or = None;
        self.collator = None;
    }

    /// Get the current locale string (BCP 47 format).
    pub fn get_locale(&self) -> AzString {
        self.locale_string.clone()
    }

    /// Get the language part of the locale (e.g., "en" from "en-US").
    pub fn get_language(&self) -> AzString {
        AzString::from(self.locale.id.language.to_string())
    }

    /// Get the region/country part of the locale if present (e.g., "US" from "en-US").
    pub fn get_region(&self) -> Option<AzString> {
        self.locale.id.region.map(|r| AzString::from(r.to_string()))
    }

    /// Change the current locale.
    ///
    /// This clears all cached formatters.
    pub fn set_locale(&mut self, locale_str: &str) -> bool {
        match locale_str.parse::<Locale>() {
            Ok(locale) => {
                self.locale = locale;
                self.locale_string = AzString::from(locale_str.to_string());
                // Clear caches
                self.decimal_formatter = None;
                self.plural_rules_cardinal = None;
                self.plural_rules_ordinal = None;
                self.list_formatter_and = None;
                self.list_formatter_or = None;
                self.collator = None;
                true
            }
            Err(_) => false,
        }
    }

    // Number Formatting

    fn get_decimal_formatter(&mut self) -> &DecimalFormatter {
        if self.decimal_formatter.is_none() {
            // Try to create formatter, fall back to default locale if it fails
            let formatter = DecimalFormatter::try_new(self.locale.clone().into(), Default::default())
                .unwrap_or_else(|_| {
                    DecimalFormatter::try_new(Default::default(), Default::default())
                        .expect("default locale should always work")
                });
            self.decimal_formatter = Some(formatter);
        }
        self.decimal_formatter.as_ref().unwrap()
    }

    /// Format an integer with locale-appropriate grouping separators.
    ///
    /// # Example
    /// - en-US: 1234567 → "1,234,567"
    /// - de-DE: 1234567 → "1.234.567"
    /// - fr-FR: 1234567 → "1 234 567"
    pub fn format_integer(&mut self, value: i64) -> AzString {
        let decimal = Decimal::from(value);
        let formatter = self.get_decimal_formatter();
        let mut output = String::new();
        let _ = write!(output, "{}", formatter.format(&decimal));
        AzString::from(output)
    }

    /// Format a decimal number with locale-appropriate separators.
    ///
    /// # Arguments
    /// * `integer_part` - The integer part of the number
    /// * `decimal_places` - Number of decimal places (negative power of 10)
    ///
    /// # Example
    /// `format_decimal(123456, 2)` formats 1234.56
    /// - en-US: "1,234.56"
    /// - de-DE: "1.234,56"
    pub fn format_decimal(&mut self, integer_part: i64, decimal_places: i16) -> AzString {
        let mut decimal = Decimal::from(integer_part);
        decimal.multiply_pow10(-decimal_places);
        let formatter = self.get_decimal_formatter();
        let mut output = String::new();
        let _ = write!(output, "{}", formatter.format(&decimal));
        AzString::from(output)
    }

    // Plural Rules

    fn get_plural_rules_cardinal(&mut self) -> &PluralRules {
        if self.plural_rules_cardinal.is_none() {
            let rules = PluralRules::try_new(self.locale.clone().into(), Default::default())
                .unwrap_or_else(|_| {
                    PluralRules::try_new(Default::default(), Default::default())
                        .expect("default locale should always work")
                });
            self.plural_rules_cardinal = Some(rules);
        }
        self.plural_rules_cardinal.as_ref().unwrap()
    }

    /// Get the plural category for a number (cardinal: "1 item", "2 items").
    ///
    /// This is essential for proper pluralization in translations.
    ///
    /// # Example
    /// - English: 1 → One, 2 → Other
    /// - Polish: 1 → One, 2 → Few, 5 → Many
    /// - Arabic: 0 → Zero, 1 → One, 2 → Two, 3-10 → Few, 11-99 → Many
    pub fn get_plural_category(&mut self, value: i64) -> PluralCategory {
        let rules = self.get_plural_rules_cardinal();
        rules.category_for(value as usize).into()
    }

    /// Select the appropriate string based on plural category.
    ///
    /// # Arguments
    /// * `value` - The number to pluralize
    /// * `zero` - String for zero (if language supports it, otherwise uses `other`)
    /// * `one` - String for one
    /// * `two` - String for two (if language supports it, otherwise uses `other`)
    /// * `few` - String for few (if language supports it, otherwise uses `other`)
    /// * `many` - String for many (if language supports it, otherwise uses `other`)
    /// * `other` - String for other (fallback)
    ///
    /// # Example
    /// ```rust,ignore
    /// let msg = localizer.pluralize(
    ///     count,
    ///     "no items",    // zero
    ///     "1 item",      // one
    ///     "2 items",     // two
    ///     "{} items",    // few
    ///     "{} items",    // many
    ///     "{} items",    // other
    /// );
    /// ```
    pub fn pluralize(
        &mut self,
        value: i64,
        zero: &str,
        one: &str,
        two: &str,
        few: &str,
        many: &str,
        other: &str,
    ) -> AzString {
        let category = self.get_plural_category(value);
        let template = match category {
            PluralCategory::Zero => zero,
            PluralCategory::One => one,
            PluralCategory::Two => two,
            PluralCategory::Few => few,
            PluralCategory::Many => many,
            PluralCategory::Other => other,
        };
        // Replace {} placeholder with the actual value
        let result = template.replace("{}", &value.to_string());
        AzString::from(result)
    }

    // List Formatting

    fn get_list_formatter_and(&mut self) -> &ListFormatter {
        if self.list_formatter_and.is_none() {
            let formatter = ListFormatter::try_new_and(
                self.locale.clone().into(),
                ListFormatterOptions::default(),
            )
            .unwrap_or_else(|_| {
                ListFormatter::try_new_and(Default::default(), ListFormatterOptions::default())
                    .expect("default locale should always work")
            });
            self.list_formatter_and = Some(formatter);
        }
        self.list_formatter_and.as_ref().unwrap()
    }

    fn get_list_formatter_or(&mut self) -> &ListFormatter {
        if self.list_formatter_or.is_none() {
            let formatter = ListFormatter::try_new_or(
                self.locale.clone().into(),
                ListFormatterOptions::default(),
            )
            .unwrap_or_else(|_| {
                ListFormatter::try_new_or(Default::default(), ListFormatterOptions::default())
                    .expect("default locale should always work")
            });
            self.list_formatter_or = Some(formatter);
        }
        self.list_formatter_or.as_ref().unwrap()
    }

    /// Format a list of items with locale-appropriate conjunctions.
    ///
    /// # Arguments
    /// 
    /// * `items` - The items to format
    /// * `list_type` - The type of list (And, Or, Unit)
    ///
    /// # Example
    /// 
    /// - en-US And: ["A", "B", "C"] → "A, B, and C"
    /// - es-ES And: ["España", "Suiza", "Italia"] → "España, Suiza e Italia"
    /// - en-US Or: ["A", "B", "C"] → "A, B, or C"
    pub fn format_list(&mut self, items: &[AzString], list_type: ListType) -> AzString {
        let str_items: Vec<&str> = items.iter().map(|s| s.as_str()).collect();

        let formatted = match list_type {
            ListType::And => {
                let formatter = self.get_list_formatter_and();
                formatter.format(str_items.iter().copied())
            }
            ListType::Or => {
                let formatter = self.get_list_formatter_or();
                formatter.format(str_items.iter().copied())
            }
            ListType::Unit => {
                // Unit formatting uses comma separation without conjunction
                // For now, fall back to simple comma join
                // TODO: Use ListFormatter::try_new_unit when available
                return AzString::from(str_items.join(", "));
            }
        };

        let mut output = String::new();
        let _ = write!(output, "{}", formatted);
        AzString::from(output)
    }

    // Date/Time Formatting

    /// Format a date according to the current locale.
    ///
    /// # Arguments
    /// 
    /// * `date` - The date to format
    /// * `length` - The format length (Short, Medium, Long)
    ///
    /// # Example
    /// 
    /// For January 15, 2025:
    /// 
    /// - en-US Short: "1/15/25"
    /// - en-US Medium: "Jan 15, 2025"
    /// - en-US Long: "January 15, 2025"
    /// - de-DE Short: "15.01.25"
    /// - de-DE Medium: "15.01.2025"
    /// - de-DE Long: "15. Januar 2025"
    pub fn format_date(&mut self, date: IcuDate, length: FormatLength) -> IcuResult {
        use icu::datetime::fieldsets::YMD;
        use icu::datetime::input::Date;
        use icu::datetime::DateTimeFormatter;

        let icu_date = match Date::try_new_iso(date.year, date.month, date.day) {
            Ok(d) => d,
            Err(e) => return IcuResult::err(format!("Invalid date: {}", e)),
        };

        let field_set = match length {
            FormatLength::Short => YMD::short(),
            FormatLength::Medium => YMD::medium(),
            FormatLength::Long => YMD::long(),
        };

        let formatter = match DateTimeFormatter::try_new(self.locale.clone().into(), field_set) {
            Ok(f) => f,
            Err(e) => return IcuResult::err(format!("Failed to create formatter: {:?}", e)),
        };

        let mut output = String::new();
        let _ = write!(output, "{}", formatter.format(&icu_date));
        IcuResult::ok(output)
    }

    /// Format a time according to the current locale.
    ///
    /// # Example
    /// 
    /// For 16:30:45:
    /// 
    /// - en-US: "4:30 PM" or "4:30:45 PM"
    /// - de-DE: "16:30" or "16:30:45"
    pub fn format_time(&mut self, time: IcuTime, include_seconds: bool) -> IcuResult {
        use icu::datetime::fieldsets;
        use icu::datetime::input::Time;
        use icu::datetime::NoCalendarFormatter;

        let icu_time = match Time::try_new(time.hour, time.minute, time.second, 0) {
            Ok(t) => t,
            Err(e) => return IcuResult::err(format!("Invalid time: {}", e)),
        };

        let mut output = String::new();

        if include_seconds {
            let formatter: NoCalendarFormatter<fieldsets::T> =
                match NoCalendarFormatter::try_new(self.locale.clone().into(), fieldsets::T::medium()) {
                    Ok(f) => f,
                    Err(e) => return IcuResult::err(format!("Failed to create formatter: {:?}", e)),
                };
            let _ = write!(output, "{}", formatter.format(&icu_time));
        } else {
            let formatter: NoCalendarFormatter<fieldsets::T> =
                match NoCalendarFormatter::try_new(self.locale.clone().into(), fieldsets::T::short()) {
                    Ok(f) => f,
                    Err(e) => return IcuResult::err(format!("Failed to create formatter: {:?}", e)),
                };
            let _ = write!(output, "{}", formatter.format(&icu_time));
        }

        IcuResult::ok(output)
    }

    /// Format a date and time according to the current locale.
    pub fn format_datetime(&mut self, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
        use icu::datetime::fieldsets::YMD;
        use icu::datetime::input::{Date, DateTime, Time};
        use icu::datetime::DateTimeFormatter;

        let icu_date = match Date::try_new_iso(datetime.date.year, datetime.date.month, datetime.date.day) {
            Ok(d) => d,
            Err(e) => return IcuResult::err(format!("Invalid date: {}", e)),
        };

        let icu_time = match Time::try_new(datetime.time.hour, datetime.time.minute, datetime.time.second, 0) {
            Ok(t) => t,
            Err(e) => return IcuResult::err(format!("Invalid time: {}", e)),
        };

        let icu_datetime = DateTime {
            date: icu_date,
            time: icu_time,
        };

        let field_set = match length {
            FormatLength::Short => YMD::short().with_time_hm(),
            FormatLength::Medium => YMD::medium().with_time_hm(),
            FormatLength::Long => YMD::long().with_time_hm(),
        };

        let formatter = match DateTimeFormatter::try_new(self.locale.clone().into(), field_set) {
            Ok(f) => f,
            Err(e) => return IcuResult::err(format!("Failed to create formatter: {:?}", e)),
        };

        let mut output = String::new();
        let _ = write!(output, "{}", formatter.format(&icu_datetime));
        IcuResult::ok(output)
    }

    // Collation (locale-aware string sorting)

    fn get_collator(&mut self) -> &Collator {
        if self.collator.is_none() {
            // try_new returns CollatorBorrowed<'static>, convert to owned
            let collator = Collator::try_new(self.locale.clone().into(), CollatorOptions::default())
                .map(|borrowed| borrowed.static_to_owned())
                .unwrap_or_else(|_| {
                    Collator::try_new(Default::default(), CollatorOptions::default())
                        .map(|borrowed| borrowed.static_to_owned())
                        .expect("default locale should always work")
                });
            self.collator = Some(collator);
        }
        self.collator.as_ref().unwrap()
    }

    /// Compare two strings according to locale-specific collation rules.
    ///
    /// Returns:
    /// - `Ordering::Less` if `a` comes before `b`
    /// - `Ordering::Equal` if `a` equals `b`
    /// - `Ordering::Greater` if `a` comes after `b`
    ///
    /// # Example
    /// ```rust,ignore
    /// let mut localizer = IcuLocalizer::new("es-ES");
    /// // Spanish: "ch" was historically treated as a single letter after "c"
    /// // (though modern Spanish may differ)
    /// let cmp = localizer.compare("coche", "cena");
    /// ```
    pub fn compare(&mut self, a: &str, b: &str) -> core::cmp::Ordering {
        self.get_collator().as_borrowed().compare(a, b)
    }

    /// Sort a vector of strings in place using locale-aware collation.
    ///
    /// This properly handles accented characters, case sensitivity, and
    /// language-specific sorting rules.
    ///
    /// # Example
    /// ```rust,ignore
    /// let mut localizer = IcuLocalizer::new("de-DE");
    /// let mut names = vec!["Österreich", "Andorra", "Ägypten"];
    /// localizer.sort_strings(&mut names);
    /// // German sorts Ä with A, Ö with O
    /// ```
    pub fn sort_strings(&mut self, strings: &mut [AzString]) {
        let collator = self.get_collator().as_borrowed();
        strings.sort_by(|a, b| collator.compare(a.as_str(), b.as_str()));
    }

    /// Sort a vector of strings and return a new sorted vector.
    pub fn sorted_strings(&mut self, strings: &[AzString]) -> Vec<AzString> {
        let mut result: Vec<AzString> = strings.to_vec();
        self.sort_strings(&mut result);
        result
    }

    /// Check if two strings are equal according to locale collation rules.
    ///
    /// This may return `true` for strings that differ in case or accents,
    /// depending on the collation strength.
    pub fn strings_equal(&mut self, a: &str, b: &str) -> bool {
        self.compare(a, b) == core::cmp::Ordering::Equal
    }

    /// Get the sort key for a string.
    ///
    /// Sort keys can be compared byte-by-byte for fast sorting of many strings.
    /// This is more efficient when sorting large collections.
    pub fn get_sort_key(&mut self, s: &str) -> Vec<u8> {
        let collator = self.get_collator().as_borrowed();
        let mut key = Vec::new();
        let _ = collator.write_sort_key_to(s, &mut key);
        key
    }
}

impl Default for IcuLocalizer {
    fn default() -> Self {
        Self::new("en-US")
    }
}

impl Clone for IcuLocalizer {
    fn clone(&self) -> Self {
        // Clone without cached formatters (they'll be recreated on demand)
        Self {
            locale: self.locale.clone(),
            locale_string: self.locale_string.clone(),
            data_blob: self.data_blob.clone(),
            decimal_formatter: None,
            plural_rules_cardinal: None,
            plural_rules_ordinal: None,
            list_formatter_and: None,
            list_formatter_or: None,
            collator: None,
        }
    }
}

// Thread-safe wrapper for use in callbacks

/// Inner data for IcuLocalizerHandle - contains the actual cache and settings.
struct IcuLocalizerInner {
    cache: Mutex<BTreeMap<String, IcuLocalizer>>,
    /// Default locale to use when none is specified
    default_locale: Mutex<AzString>,
}

/// A thread-safe cache of ICU localizers for multiple locales.
///
/// This is passed to callbacks via `CallbackInfo` and `LayoutCallbackInfo`.
/// It uses `Arc` internally for safe shared access, making it FFI-compatible
/// as a single pointer.
///
/// Each locale's IcuLocalizer is lazily created and cached on first use.
/// All methods take a `locale: &str` parameter to specify which locale to use.
#[repr(C)]
#[derive(Clone)]
pub struct IcuLocalizerHandle {
    ptr: Arc<IcuLocalizerInner>,
}

impl core::fmt::Debug for IcuLocalizerHandle {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let default_locale = self.ptr.default_locale.lock()
            .map(|g| g.clone())
            .unwrap_or_else(|_| AzString::from(""));
        f.debug_struct("IcuLocalizerHandle")
            .field("default_locale", &default_locale)
            .finish()
    }
}

impl Default for IcuLocalizerHandle {
    fn default() -> Self {
        Self {
            ptr: Arc::new(IcuLocalizerInner {
                cache: Mutex::new(BTreeMap::new()),
                default_locale: Mutex::new(AzString::from("en-US")),
            }),
        }
    }
}

impl IcuLocalizerHandle {
    /// Create a new empty cache with a default locale.
    pub fn new(default_locale: &str) -> Self {
        Self {
            ptr: Arc::new(IcuLocalizerInner {
                cache: Mutex::new(BTreeMap::new()),
                default_locale: Mutex::new(AzString::from(default_locale)),
            }),
        }
    }

    /// Create a cache initialized with the system language.
    pub fn from_system_language(language: &AzString) -> Self {
        Self::new(language.as_str())
    }

    /// Get the default locale string.
    pub fn get_default_locale(&self) -> AzString {
        self.ptr.default_locale.lock()
            .map(|g| g.clone())
            .unwrap_or_else(|_| AzString::from("en-US"))
    }

    /// Set the default locale.
    pub fn set_default_locale(&mut self, locale: &str) {
        if let Ok(mut guard) = self.ptr.default_locale.lock() {
            *guard = AzString::from(locale);
        }
    }

    /// Alias for set_default_locale for compatibility.
    pub fn set_locale(&mut self, locale: &str) {
        self.set_default_locale(locale);
    }

    /// Load additional locale data from a binary blob for all cached localizers.
    ///
    /// The blob should be generated using `icu4x-datagen` with the `--format blob` flag.
    /// This allows supporting locales that aren't compiled into the binary.
    ///
    /// Returns `true` if the data was successfully loaded.
    pub fn load_data_blob(&self, data: &[u8]) -> bool {
        if let Ok(mut cache) = self.ptr.cache.lock() {
            // Clear the cache so all localizers will be recreated with new data
            cache.clear();
            // Note: The actual blob needs to be stored somewhere accessible to new localizers
            // For now, we just clear the cache so they'll be recreated with default data
            true
        } else {
            false
        }
    }

    /// Get or create a localizer for the given locale.
    /// This is an internal helper that handles cache access.
    fn with_localizer<F, R>(&self, locale: &str, f: F) -> R
    where
        F: FnOnce(&mut IcuLocalizer) -> R,
        R: Default,
    {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                f(localizer)
            })
            .unwrap_or_default()
    }

    /// Get the language part of a locale (e.g., "en" from "en-US").
    pub fn get_language(&self, locale: &str) -> AzString {
        self.with_localizer(locale, |l| l.get_language())
    }

    /// Format an integer with locale-appropriate grouping.
    ///
    /// # Example
    /// ```rust,ignore
    /// cache.format_integer("en-US", 1234567) // → "1,234,567"
    /// cache.format_integer("de-DE", 1234567) // → "1.234.567"
    /// ```
    pub fn format_integer(&self, locale: &str, value: i64) -> AzString {
        self.with_localizer(locale, |l| l.format_integer(value))
    }

    /// Format a decimal number.
    ///
    /// # Arguments
    /// * `locale` - BCP 47 locale string (e.g., "en-US", "de-DE")
    /// * `integer_part` - The full integer value (e.g., 123456 for 1234.56)
    /// * `decimal_places` - Number of decimal places (e.g., 2 for 1234.56)
    pub fn format_decimal(&self, locale: &str, integer_part: i64, decimal_places: i16) -> AzString {
        self.with_localizer(locale, |l| l.format_decimal(integer_part, decimal_places))
    }

    /// Get the plural category for a number.
    ///
    /// # Example
    /// ```rust,ignore
    /// cache.get_plural_category("en", 1)  // → PluralCategory::One
    /// cache.get_plural_category("pl", 5)  // → PluralCategory::Many
    /// ```
    pub fn get_plural_category(&self, locale: &str, value: i64) -> PluralCategory {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.get_plural_category(value)
            })
            .unwrap_or(PluralCategory::Other)
    }

    /// Select a string based on plural rules.
    ///
    /// # Arguments
    /// * `locale` - BCP 47 locale string
    /// * `value` - The number to pluralize
    /// * `zero`, `one`, `two`, `few`, `many`, `other` - Strings for each category
    pub fn pluralize(
        &self,
        locale: &str,
        value: i64,
        zero: &str,
        one: &str,
        two: &str,
        few: &str,
        many: &str,
        other: &str,
    ) -> AzString {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.pluralize(value, zero, one, two, few, many, other)
            })
            .unwrap_or_else(|_| AzString::from(other))
    }

    /// Format a list of items with locale-appropriate conjunctions.
    ///
    /// # Example
    /// ```rust,ignore
    /// cache.format_list("en-US", &items, ListType::And) // → "A, B, and C"
    /// cache.format_list("de-DE", &items, ListType::And) // → "A, B und C"
    /// ```
    pub fn format_list(&self, locale: &str, items: &[AzString], list_type: ListType) -> AzString {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.format_list(items, list_type)
            })
            .unwrap_or_else(|_| {
                let strs: Vec<&str> = items.iter().map(|s| s.as_str()).collect();
                AzString::from(strs.join(", "))
            })
    }

    /// Format a date according to the specified locale.
    ///
    /// # Example
    /// ```rust,ignore
    /// let today = IcuDate::now();
    /// cache.format_date("en-US", today, FormatLength::Medium) // → "Jan 15, 2025"
    /// cache.format_date("de-DE", today, FormatLength::Medium) // → "15.01.2025"
    /// ```
    pub fn format_date(&self, locale: &str, date: IcuDate, length: FormatLength) -> IcuResult {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.format_date(date, length)
            })
            .unwrap_or_else(|e| IcuResult::err(format!("Lock error: {:?}", e)))
    }

    /// Format a time according to the specified locale.
    ///
    /// # Example
    /// ```rust,ignore
    /// let now = IcuTime::now();
    /// cache.format_time("en-US", now, false) // → "4:30 PM"
    /// cache.format_time("de-DE", now, false) // → "16:30"
    /// ```
    pub fn format_time(&self, locale: &str, time: IcuTime, include_seconds: bool) -> IcuResult {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.format_time(time, include_seconds)
            })
            .unwrap_or_else(|e| IcuResult::err(format!("Lock error: {:?}", e)))
    }

    /// Format a date and time according to the specified locale.
    pub fn format_datetime(&self, locale: &str, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.format_datetime(datetime, length)
            })
            .unwrap_or_else(|e| IcuResult::err(format!("Lock error: {:?}", e)))
    }

    // =========================================================================
    // Collation (locale-aware string comparison and sorting)
    // =========================================================================

    /// Compare two strings according to locale-specific collation rules.
    ///
    /// Returns -1 if a < b, 0 if a == b, 1 if a > b.
    ///
    /// # Example
    /// ```rust,ignore
    /// cache.compare_strings("de-DE", "Äpfel", "Banane") // → -1 (Ä sorts with A)
    /// cache.compare_strings("sv-SE", "Äpple", "Öl")     // → -1 (Swedish: Ä before Ö)
    /// ```
    pub fn compare_strings(&self, locale: &str, a: &str, b: &str) -> i32 {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                match localizer.compare(a, b) {
                    core::cmp::Ordering::Less => -1,
                    core::cmp::Ordering::Equal => 0,
                    core::cmp::Ordering::Greater => 1,
                }
            })
            .unwrap_or(0)
    }

    /// Sort a vector of strings using locale-aware collation.
    ///
    /// Returns a new sorted vector.
    ///
    /// # Example
    /// ```rust,ignore
    /// let sorted = cache.sort_strings("de-DE", &["Österreich", "Andorra", "Ägypten"]);
    /// // Result: ["Ägypten", "Andorra", "Österreich"] (Ä sorts with A, Ö with O)
    /// ```
    pub fn sort_strings(&self, locale: &str, strings: &[AzString]) -> IcuStringVec {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                IcuStringVec::from(localizer.sorted_strings(strings))
            })
            .unwrap_or_else(|_| IcuStringVec::from(strings.to_vec()))
    }

    /// Check if two strings are equal according to locale collation rules.
    pub fn strings_equal(&self, locale: &str, a: &str, b: &str) -> bool {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.strings_equal(a, b)
            })
            .unwrap_or_else(|_| a == b)
    }

    /// Get the sort key for a string (for efficient bulk sorting).
    pub fn get_sort_key(&self, locale: &str, s: &str) -> Vec<u8> {
        self.ptr.cache
            .lock()
            .map(|mut cache| {
                let localizer = cache
                    .entry(locale.to_string())
                    .or_insert_with(|| IcuLocalizer::new(locale));
                localizer.get_sort_key(s)
            })
            .unwrap_or_default()
    }

    /// Convenience function to format a localized message with plural support.
    ///
    /// This handles the common case of "{count} {item/items}" patterns.
    /// The `{}` placeholder in the template will be replaced with the formatted number.
    pub fn format_plural(&self, locale: &str, value: i64, zero: &str, one: &str, other: &str) -> AzString {
        let template = self.pluralize(locale, value, zero, one, other, other, other, other);
        let formatted_num = self.format_integer(locale, value);
        AzString::from(template.as_str().replace("{}", formatted_num.as_str()))
    }

    /// Format a list of strings conveniently.
    pub fn format_list_strings(&self, locale: &str, items: &[&str], list_type: ListType) -> AzString {
        let az_items: Vec<AzString> = items.iter().map(|s| AzString::from(*s)).collect();
        self.format_list(locale, &az_items, list_type)
    }

    /// Clear the cache (useful for memory management or locale data reload).
    pub fn clear_cache(&self) {
        if let Ok(mut cache) = self.ptr.cache.lock() {
            cache.clear();
        }
    }

    /// Get the number of cached locales.
    pub fn cached_locale_count(&self) -> usize {
        self.ptr.cache
            .lock()
            .map(|cache| cache.len())
            .unwrap_or(0)
    }

    /// Get a list of all cached locale strings.
    pub fn cached_locales(&self) -> Vec<AzString> {
        self.ptr.cache
            .lock()
            .map(|cache| cache.keys().map(|k| AzString::from(k.clone())).collect())
            .unwrap_or_default()
    }
}

// ============================================================================
// IcuFormattedValue: Wrapper for strfmt integration
// ============================================================================

/// Wrapper that formats FmtValue using ICU localization.
///
/// Used internally for format_string functionality.
struct IcuFormattedValue {
    value: FmtValue,
    localizer: IcuLocalizerHandle,
    locale: String,
}

impl strfmt::DisplayStr for IcuFormattedValue {
    fn display_str(&self, f: &mut strfmt::Formatter<'_, '_>) -> strfmt::Result<()> {
        use strfmt::DisplayStr;

        match &self.value {
            // For integers, use ICU formatting
            FmtValue::Uint(v) => {
                self.localizer.format_integer(&self.locale, *v as i64).as_str().display_str(f)
            }
            FmtValue::Sint(v) => {
                self.localizer.format_integer(&self.locale, *v as i64).as_str().display_str(f)
            }
            FmtValue::Ulong(v) => {
                self.localizer.format_integer(&self.locale, *v as i64).as_str().display_str(f)
            }
            FmtValue::Slong(v) => {
                self.localizer.format_integer(&self.locale, *v).as_str().display_str(f)
            }
            FmtValue::Usize(v) => {
                self.localizer.format_integer(&self.locale, *v as i64).as_str().display_str(f)
            }
            FmtValue::Isize(v) => {
                self.localizer.format_integer(&self.locale, *v as i64).as_str().display_str(f)
            }
            // For floats, use decimal formatting (2 decimal places by default)
            FmtValue::Float(v) => {
                // Convert to integer representation with 2 decimal places
                let int_part = (*v * 100.0) as i64;
                self.localizer.format_decimal(&self.locale, int_part, 2).as_str().display_str(f)
            }
            FmtValue::Double(v) => {
                // Convert to integer representation with 2 decimal places
                let int_part = (*v * 100.0) as i64;
                self.localizer.format_decimal(&self.locale, int_part, 2).as_str().display_str(f)
            }
            // For string lists, use ICU list formatting
            FmtValue::StrVec(sv) => {
                let items: Vec<AzString> = sv.as_ref().iter().cloned().collect();
                self.localizer.format_list(&self.locale, &items, ListType::And).as_str().display_str(f)
            }
            // Other types use standard formatting
            FmtValue::Bool(v) => format!("{v:?}").display_str(f),
            FmtValue::Uchar(v) => v.display_str(f),
            FmtValue::Schar(v) => v.display_str(f),
            FmtValue::Ushort(v) => v.display_str(f),
            FmtValue::Sshort(v) => v.display_str(f),
            FmtValue::Str(v) => v.as_str().display_str(f),
        }
    }
}

// C-compatible Vec types for FFI

// OptionAzString is the same as OptionString from azul_css
pub type OptionAzString = azul_css::OptionString;

azul_css::impl_vec!(AzString, IcuStringVec, IcuStringVecDestructor, IcuStringVecDestructorType, IcuStringVecSlice, OptionAzString);
azul_css::impl_vec_clone!(AzString, IcuStringVec, IcuStringVecDestructor);
azul_css::impl_vec_debug!(AzString, IcuStringVec);

// ============================================================================
// Extension trait for LayoutCallbackInfo (from azul-core)
// ============================================================================

use azul_core::callbacks::LayoutCallbackInfo;

/// Extension trait to add ICU internationalization methods to LayoutCallbackInfo.
///
/// This trait is implemented for `LayoutCallbackInfo` when the `icu` feature is enabled.
/// Import this trait to use ICU methods on LayoutCallbackInfo in layout callbacks.
///
/// # Example
/// ```rust,ignore
/// use azul_layout::icu::LayoutCallbackInfoIcuExt;
///
/// fn my_layout(info: LayoutCallbackInfo) -> StyledDom {
///     let formatted = info.icu_format_integer(1234567);
///     // ...
/// }
/// ```
pub trait LayoutCallbackInfoIcuExt {
    /// Get the current locale string (BCP 47 format, e.g., "en-US", "de-DE").
    fn icu_get_locale(&self) -> AzString;

    /// Get the current language (e.g., "en" from "en-US").
    fn icu_get_language(&self) -> AzString;

    /// Format an integer with locale-appropriate grouping separators.
    fn icu_format_integer(&self, value: i64) -> AzString;

    /// Format a decimal number with locale-appropriate separators.
    fn icu_format_decimal(&self, integer_part: i64, decimal_places: i16) -> AzString;

    /// Get the plural category for a number.
    fn icu_get_plural_category(&self, value: i64) -> PluralCategory;

    /// Select a string based on plural rules.
    fn icu_pluralize(
        &self,
        value: i64,
        zero: &str,
        one: &str,
        two: &str,
        few: &str,
        many: &str,
        other: &str,
    ) -> AzString;

    /// Format a list of items with locale-appropriate conjunctions.
    fn icu_format_list(&self, items: &[AzString], list_type: ListType) -> AzString;

    /// Format a date according to the current locale.
    fn icu_format_date(&self, date: IcuDate, length: FormatLength) -> IcuResult;

    /// Format a time according to the current locale.
    fn icu_format_time(&self, time: IcuTime, include_seconds: bool) -> IcuResult;

    /// Format a date and time according to the current locale.
    fn icu_format_datetime(&self, datetime: IcuDateTime, length: FormatLength) -> IcuResult;

    /// Compare two strings according to locale-specific collation rules.
    /// Returns -1 if a < b, 0 if a == b, 1 if a > b.
    fn icu_compare_strings(&self, a: &str, b: &str) -> i32;

    /// Sort a list of strings using locale-aware collation.
    fn icu_sort_strings(&self, strings: &[AzString]) -> IcuStringVec;

    /// Check if two strings are equal according to locale collation rules.
    fn icu_strings_equal(&self, a: &str, b: &str) -> bool;
}

impl LayoutCallbackInfoIcuExt for LayoutCallbackInfo {
    fn icu_get_locale(&self) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        handle.get_default_locale()
    }

    fn icu_get_language(&self) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.get_language(locale)
    }

    fn icu_format_integer(&self, value: i64) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_integer(locale, value)
    }

    fn icu_format_decimal(&self, integer_part: i64, decimal_places: i16) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_decimal(locale, integer_part, decimal_places)
    }

    fn icu_get_plural_category(&self, value: i64) -> PluralCategory {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.get_plural_category(locale, value)
    }

    fn icu_pluralize(
        &self,
        value: i64,
        zero: &str,
        one: &str,
        two: &str,
        few: &str,
        many: &str,
        other: &str,
    ) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.pluralize(locale, value, zero, one, two, few, many, other)
    }

    fn icu_format_list(&self, items: &[AzString], list_type: ListType) -> AzString {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_list(locale, items, list_type)
    }

    fn icu_format_date(&self, date: IcuDate, length: FormatLength) -> IcuResult {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_date(locale, date, length)
    }

    fn icu_format_time(&self, time: IcuTime, include_seconds: bool) -> IcuResult {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_time(locale, time, include_seconds)
    }

    fn icu_format_datetime(&self, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.format_datetime(locale, datetime, length)
    }

    fn icu_compare_strings(&self, a: &str, b: &str) -> i32 {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.compare_strings(locale, a, b)
    }

    fn icu_sort_strings(&self, strings: &[AzString]) -> IcuStringVec {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.sort_strings(locale, strings)
    }

    fn icu_strings_equal(&self, a: &str, b: &str) -> bool {
        let system_style = self.get_system_style();
        let handle = IcuLocalizerHandle::from_system_language(&system_style.language);
        let locale = system_style.language.as_str();
        handle.strings_equal(locale, a, b)
    }
}

// Tests

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

    #[test]
    fn test_format_integer_en_us() {
        let mut localizer = IcuLocalizer::new("en-US");
        assert_eq!(localizer.format_integer(1234567).as_str(), "1,234,567");
    }

    #[test]
    fn test_format_integer_de_de() {
        let mut localizer = IcuLocalizer::new("de-DE");
        let result = localizer.format_integer(1234567);
        // German uses period as thousand separator
        assert!(result.as_str().contains('.') || result.as_str().contains('\u{a0}'));
    }

    #[test]
    fn test_plural_category_english() {
        let mut localizer = IcuLocalizer::new("en-US");
        assert_eq!(localizer.get_plural_category(1), PluralCategory::One);
        assert_eq!(localizer.get_plural_category(2), PluralCategory::Other);
        assert_eq!(localizer.get_plural_category(0), PluralCategory::Other);
    }

    #[test]
    fn test_format_list_and() {
        let mut localizer = IcuLocalizer::new("en-US");
        let items = vec![
            AzString::from("A"),
            AzString::from("B"),
            AzString::from("C"),
        ];
        let result = localizer.format_list(&items, ListType::And);
        assert!(result.as_str().contains("and"));
    }

    #[test]
    fn test_format_date() {
        let mut localizer = IcuLocalizer::new("en-US");
        let date = IcuDate {
            year: 2025,
            month: 1,
            day: 15,
        };
        let result = localizer.format_date(date, FormatLength::Medium);
        assert!(matches!(result, IcuResult::Ok(_)));
    }

    #[test]
    fn test_cache_thread_safety() {
        let cache = IcuLocalizerHandle::from_system_language(&AzString::from("en-US"));

        // Test that we can clone and use from multiple "threads" (simulated)
        let cache2 = cache.clone();

        assert_eq!(
            cache.format_integer("en-US", 1000).as_str(), 
            cache2.format_integer("en-US", 1000).as_str()
        );
    }

    #[test]
    fn test_cache_multi_locale() {
        let cache = IcuLocalizerHandle::default();

        // Format with different locales - each should be cached separately
        let en = cache.format_integer("en-US", 1234567);
        let de = cache.format_integer("de-DE", 1234567);
        
        // US uses comma, German uses period
        assert!(en.as_str().contains(','));
        assert!(de.as_str().contains('.') || de.as_str().contains('\u{a0}'));
    }

    #[test]
    fn test_collation_compare() {
        let mut localizer = IcuLocalizer::new("en-US");
        assert_eq!(localizer.compare("apple", "banana"), core::cmp::Ordering::Less);
        assert_eq!(localizer.compare("banana", "apple"), core::cmp::Ordering::Greater);
        assert_eq!(localizer.compare("apple", "apple"), core::cmp::Ordering::Equal);
    }

    #[test]
    fn test_collation_sort() {
        let mut localizer = IcuLocalizer::new("en-US");
        let mut strings = vec![
            AzString::from("cherry"),
            AzString::from("apple"),
            AzString::from("banana"),
        ];
        localizer.sort_strings(&mut strings);
        assert_eq!(strings[0].as_str(), "apple");
        assert_eq!(strings[1].as_str(), "banana");
        assert_eq!(strings[2].as_str(), "cherry");
    }

    #[test]
    fn test_collation_german_umlauts() {
        let mut localizer = IcuLocalizer::new("de-DE");
        // In German, Ä sorts with A
        let result = localizer.compare("Ägypten", "Andorra");
        // Both start with A-like characters, so comparison depends on secondary differences
        assert!(result != core::cmp::Ordering::Equal);
    }

    #[test]
    fn test_sort_key() {
        let mut localizer = IcuLocalizer::new("en-US");
        let key_a = localizer.get_sort_key("apple");
        let key_b = localizer.get_sort_key("banana");
        // Sort keys should compare bytewise to give same ordering as compare()
        assert!(key_a < key_b);
    }
}