themed-styler 1.2.2

Client-side runtime styling engine for web and React Native with theme support and Tailwind subset
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
use indexmap::{IndexMap, IndexSet};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{de::Deserializer, Deserialize, Serialize};
use serde_json::json;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
mod default_state;
use default_state::bundled_state;

pub type CssProps = IndexMap<String, serde_json::Value>;
pub type SelectorStyles = IndexMap<String, CssProps>; // selector -> props

fn deserialize_variables<'de, D>(deserializer: D) -> Result<IndexMap<String, String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    let mut out: IndexMap<String, String> = IndexMap::new();
    if let Some(v) = value {
        flatten_variables(None, &v, &mut out);
    }
    Ok(out)
}

fn flatten_variables(prefix: Option<&str>, value: &serde_json::Value, out: &mut IndexMap<String, String>) {
    match value {
        serde_json::Value::Object(map) => {
            for (k, v) in map {
                let key = if let Some(p) = prefix {
                    format!("{}.{}", p, k)
                } else {
                    k.to_string()
                };
                flatten_variables(Some(&key), v, out);
            }
        }
        serde_json::Value::Array(arr) => {
            for (idx, v) in arr.iter().enumerate() {
                let key = if let Some(p) = prefix {
                    format!("{}.{}", p, idx)
                } else {
                    idx.to_string()
                };
                flatten_variables(Some(&key), v, out);
            }
        }
        serde_json::Value::Null => {}
        serde_json::Value::Bool(b) => {
            if let Some(p) = prefix {
                out.insert(p.to_string(), b.to_string());
            }
        }
        serde_json::Value::Number(n) => {
            if let Some(p) = prefix {
                out.insert(p.to_string(), n.to_string());
            }
        }
        serde_json::Value::String(s) => {
            if let Some(p) = prefix {
                out.insert(p.to_string(), s.clone());
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ThemeEntry {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub inherits: Option<String>,
    #[serde(default)]
    pub selectors: SelectorStyles,
    #[serde(default, deserialize_with = "deserialize_variables")]
    pub variables: IndexMap<String, String>,
    #[serde(default)]
    pub breakpoints: IndexMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct State {
    // New format: each theme has selectors, variables, breakpoints, and optional inherits
    pub themes: IndexMap<String, ThemeEntry>,
    pub default_theme: String,
    pub current_theme: String,
    // Legacy fields (kept for backward-compat JSON). Not used if themes[] carry variables/bps.
    #[serde(default)]
    pub theme_variables: IndexMap<String, IndexMap<String, String>>, // deprecated
    #[serde(default)]
    pub variables: IndexMap<String, String>, // deprecated global
    #[serde(default)]
    pub breakpoints: IndexMap<String, String>, // deprecated global
    #[serde(default)]
    pub used_selectors: IndexSet<String>, // deprecated: exact selector strings (kept for back-compat)
    #[serde(default)]
    pub used_classes: IndexSet<String>,   // observed classes on elements
    #[serde(default)]
    pub used_tags: IndexSet<String>,      // observed tags on elements
    /// Observed (tag, class) pairs. Encoded as "tag|class" for JSON simplicity.
    #[serde(default)]
    pub used_tag_classes: IndexSet<String>,
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("theme not found: {0}")]
    ThemeNotFound(String),
}

impl State {
    pub fn new_default() -> Self {
        // Prefer embedded Rust bundled defaults
        return bundled_state();
    }

    /// Public helper to access the embedded default state.
    pub fn default_state() -> Self {
        bundled_state()
    }

    pub fn set_theme(&mut self, theme: impl Into<String>) -> Result<(), Error> {
        let name = theme.into();
        if !self.themes.contains_key(&name) {
            return Err(Error::ThemeNotFound(name));
        }
        self.current_theme = name;
        Ok(())
    }

    pub fn add_theme(&mut self, name: impl Into<String>, styles: SelectorStyles) {
        let name = name.into();
        let entry = self.themes.entry(name).or_default();
        for (sel, props) in styles.into_iter() {
            let e = entry.selectors.entry(sel).or_default();
            merge_props(e, &props);
        }
    }

    pub fn set_variables(&mut self, vars: IndexMap<String, String>) {
        // Back-compat: set on current theme entry
        let cur = self.current_theme.clone();
        let entry = self.themes.entry(cur).or_default();
        entry.variables = vars;
    }

    pub fn set_breakpoints(&mut self, map: IndexMap<String, String>) {
        let cur = self.current_theme.clone();
        let entry = self.themes.entry(cur).or_default();
        entry.breakpoints = map;
    }

    pub fn set_default_theme(&mut self, name: impl Into<String>) {
        self.default_theme = name.into();
    }

    pub fn register_selectors<I: IntoIterator<Item = String>>(&mut self, selectors: I) {
        for s in selectors {
            self.used_selectors.insert(s);
        }
    }

    pub fn register_tailwind_classes<I: IntoIterator<Item = String>>(&mut self, classes: I) {
        for c in classes {
            self.used_classes.insert(c);
        }
    }

    pub fn register_tags<I: IntoIterator<Item = String>>(&mut self, tags: I) {
        for t in tags {
            self.used_tags.insert(t);
        }
    }

    pub fn register_tag_class(&mut self, tag: impl Into<String>, class_: impl Into<String>) {
        let key = format!("{}|{}", tag.into(), class_.into());
        self.used_tag_classes.insert(key);
    }


    pub fn clear_usage(&mut self) {
        self.used_selectors.clear();
        self.used_classes.clear();
        self.used_tags.clear();
        self.used_tag_classes.clear();
    }

    pub fn to_json(&self) -> serde_json::Value {
        json!({
            "themes": self.themes,
            "default_theme": self.default_theme,
            "current_theme": self.current_theme,
            // legacy fields are still serialized for back-compat but may be empty
            "theme_variables": self.theme_variables,
            "variables": self.variables,
            "breakpoints": self.breakpoints,
            "used_selectors": self.used_selectors,
            "used_classes": self.used_classes,
            "used_tags": self.used_tags,
            "used_tag_classes": self.used_tag_classes,
        })
    }

    pub fn from_json(value: serde_json::Value) -> anyhow::Result<Self> {
        let state: State = serde_json::from_value(value)?;
        Ok(state)
    }

    pub fn css_for_web(&self) -> String {
        // Compute CSS resolved from the effective theme (with inheritance)
        let (eff, vars) = self.effective_theme_all();
        let bps = self.effective_breakpoints();
        let mut rules: Vec<(String, CssProps)> = Vec::new();
        
        // Build closure: if a (tag,class) pair is observed, consider both the tag and the class as used too
        let mut used_tags: IndexSet<String> = self.used_tags.clone();
        let mut used_classes: IndexSet<String> = self.used_classes.clone();
        for key in &self.used_tag_classes {
            if let Some((t, c)) = split_tag_class_key(key) {
                used_tags.insert(t);
                used_classes.insert(c);
            }
        }

        // Helper to decide if a themed selector should be emitted based on observed usage.
        // Supported selector forms:
        //  - tag           (e.g., "h1")
        //  - .class        (e.g., ".text-sm"), optional pseudo ":hover"
        //  - tag.class     (e.g., "h1.text-sm"), optional pseudo ":hover"
        for (sel, props) in eff.iter() {
            if should_emit_selector(sel, &used_tags, &used_classes, &self.used_tag_classes) {
                rules.push((sel.clone(), props.clone()));
            }
        }

        // Also emit dynamic utility properties for used classes
        for class in &used_classes {
            let (bp_key, hover, base) = parse_prefixed_class(class);
            let selector = if hover { format!(".{}:hover", css_escape_class(&base)) } else { format!(".{}", css_escape_class(&base)) };

            // 1) Exact selector in effective theme (e.g. ".x:hover")
            if let Some(props) = eff.get(&selector) {
                let final_sel = wrap_with_media(&selector, bp_key.as_deref(), &bps);
                rules.push((final_sel, props.clone()));
                continue;
            }
            // 2) Dynamic generation for the base class (ignoring hover/breakpoint for props)
            if let Some(dynamic_props) = dynamic_css_properties_for_class(&base, &vars) {
                let sel = if hover { format!(".{}:hover", css_escape_class(&base)) } else { format!(".{}", css_escape_class(&base)) };
                let final_sel = wrap_with_media(&sel, bp_key.as_deref(), &bps);
                rules.push((final_sel, dynamic_props));
                continue;
            }
            // 3) Fallback: class key itself in theme (rare)
            if let Some(props) = eff.get(&base) {
                let final_sel = wrap_with_media(&selector, bp_key.as_deref(), &bps);
                rules.push((final_sel, props.clone()));
            }
        }

        post_process_css(&rules, &vars)
    }

    pub fn rn_styles_for(&self, selector: &str, classes: &[String]) -> IndexMap<String, serde_json::Value> {
        let (eff, vars) = self.effective_theme_all();
        let mut out: IndexMap<String, serde_json::Value> = IndexMap::new();
        if let Some(props) = eff.get(selector) {
            merge_rn_props(&mut out, props, &vars);
        }
        for class in classes {
            let (_bp, _hover, base) = parse_prefixed_class(class);
            // Prefer base selector match from theme
            let sel = class_to_selector(&base);
            if let Some(props) = eff.get(&sel) {
                merge_rn_props(&mut out, props, &vars);
                continue;
            }
            // Dynamic mapping for base class
            if let Some(dynamic_props) = dynamic_css_properties_for_class(&base, &vars) {
                merge_rn_props(&mut out, &dynamic_props, &vars);
                continue;
            }
            if let Some(props) = eff.get(&base) {
                merge_rn_props(&mut out, props, &vars);
            }
        }
        out
    }

    // Previously supported loading YAML at runtime; now defaults are embedded.

    // Build the inheritance chain from current theme upward via `inherits` and default fallback
    fn theme_chain(&self) -> Vec<String> {
        let mut chain = Vec::new();
        // Resolve base names
        let default_name = if self.themes.contains_key(&self.default_theme) {
            self.default_theme.clone()
        } else if let Some((k, _)) = self.themes.first() { k.clone() } else { return chain };
        let mut current_name = if self.themes.contains_key(&self.current_theme) {
            self.current_theme.clone()
        } else { default_name.clone() };
        // push child first
        let mut seen: IndexSet<String> = IndexSet::new();
        while !seen.contains(&current_name) {
            seen.insert(current_name.clone());
            chain.push(current_name.clone());
            // next parent via inherits, else stop
            let inherits = self.themes.get(&current_name).and_then(|t| t.inherits.clone());
            if let Some(p) = inherits {
                current_name = p;
            } else {
                break;
            }
        }
        if !chain.iter().any(|n| n == &default_name) {
            chain.push(default_name);
        }
        chain
    }

    // Compute effective selectors + variables + breakpoints with inheritance.
    // Child overrides parent/default on conflicts (expected for "inherits").
    fn effective_theme_all(&self) -> (SelectorStyles, IndexMap<String, String>) {
        let mut selectors: SelectorStyles = SelectorStyles::new();
        let mut vars: IndexMap<String, String> = IndexMap::new();
        // Start with deprecated globals as the lowest base
        for (k, v) in self.variables.iter() { vars.insert(k.clone(), v.clone()); }
        // Merge default -> parents -> child so child wins on conflicts
        let chain = self.theme_chain();
        for name in chain.into_iter().rev() {
            if let Some(entry) = self.themes.get(&name) {
                // merge selectors: later (child) overrides earlier (parent/default)
                for (sel, props) in entry.selectors.iter() {
                    let e = selectors.entry(sel.clone()).or_default();
                    merge_props(e, props);
                }
                // merge variables
                for (k, v) in entry.variables.iter() {
                    vars.insert(k.clone(), v.clone());
                }
            }
        }
        (selectors, vars)
    }

    // Effective breakpoints with inheritance; child overrides parent/default.
    pub fn effective_breakpoints(&self) -> IndexMap<String, String> {
        let mut bps: IndexMap<String, String> = IndexMap::new();
        // Start with deprecated globals
        for (k, v) in self.breakpoints.iter() { bps.insert(k.clone(), v.clone()); }
        let chain = self.theme_chain();
        for name in chain.into_iter().rev() {
            if let Some(entry) = self.themes.get(&name) {
                for (k, v) in entry.breakpoints.iter() {
                    bps.insert(k.clone(), v.clone());
                }
            }
        }
        bps
    }
}

fn split_tag_class_key(key: &str) -> Option<(String, String)> {
    let mut it = key.splitn(2, '|');
    let t = it.next()?.to_string();
    let c = it.next()?.to_string();
    if t.is_empty() || c.is_empty() { return None; }
    Some((t, c))
}

fn strip_hover_suffix(selector: &str) -> (&str, bool) {
    if let Some(stripped) = selector.strip_suffix(":hover") { (stripped, true) } else { (selector, false) }
}

fn should_emit_selector(sel: &str, used_tags: &IndexSet<String>, used_classes: &IndexSet<String>, used_tag_classes: &IndexSet<String>) -> bool {
    // Optionally handle :hover suffix
    let (base, _hover) = strip_hover_suffix(sel);

    // tag-only
    if is_simple_tag(base) {
        return used_tags.contains(base) || used_tag_classes.iter().any(|k| k.split('|').next() == Some(base));
    }

    // .class-only
    if let Some(class_name) = base.strip_prefix('.') {
        // Normalize potential escaped class names as-is
        return used_classes.contains(class_name) || used_tag_classes.iter().any(|k| k.ends_with(&format!("|{}", class_name)));
    }

    // tag.class
    if let Some((tag, class_name)) = split_tag_class_selector(base) {
        let key = format!("{}|{}", tag, class_name);
        return used_tag_classes.contains(&key) || (used_tags.contains(&tag) && used_classes.contains(&class_name));
    }

    // Other complex selectors are currently ignored
    false
}

fn is_simple_tag(s: &str) -> bool {
    // Match simple HTML tag-ish identifiers
    let mut chars = s.chars();
    match chars.next() { Some(c) if c.is_ascii_alphabetic() => {}, _ => return false }
    chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

fn split_tag_class_selector(s: &str) -> Option<(String, String)> {
    // "tag.class" -> (tag, class)
    let mut parts = s.splitn(2, '.');
    let tag = parts.next()?.to_string();
    let class_name = parts.next()?.to_string();
    if tag.is_empty() || class_name.is_empty() { return None; }
    Some((tag, class_name))
}

// wasm-bindgen exports (only when compiling to wasm32)
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn render_css_for_web(state_json: &str) -> String {
    match serde_json::from_str::<State>(state_json) {
        Ok(s) => s.css_for_web(),
        Err(_) => "".into(),
    }
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn get_rn_styles(state_json: &str, selector: &str, classes_json: &str) -> String {
    let classes: Vec<String> = serde_json::from_str(classes_json).unwrap_or_default();
    match serde_json::from_str::<State>(state_json) {
        Ok(s) => serde_json::to_string(&s.rn_styles_for(selector, &classes)).unwrap_or_else(|_| "{}".into()),
        Err(_) => "{}".into(),
    }
}

/// Android-specific accessor for styles; currently mirrors RN mapping.
/// Kept distinct to allow future Android-only adjustments without changing RN/web.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn get_android_styles(state_json: &str, selector: &str, classes_json: &str) -> String {
    get_rn_styles(state_json, selector, classes_json)
}

// Expose crate version to JS via wasm-bindgen
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn get_version() -> String {
    // CARGO_PKG_VERSION is provided at compile time
    env!("CARGO_PKG_VERSION").to_string()
}

// Plain Rust accessor for crate version used by Android JNI glue
pub fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Return the embedded default state as a JSON string.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn get_default_state_json() -> String {
    let st = bundled_state();
    match serde_json::to_string(&st.to_json()) {
        Ok(s) => s,
        Err(_) => "{}".to_string(),
    }
}

/// Register a theme from JSON. On duplicate, replace the theme's selectors, inheritance, and variables.
/// Expected JSON format: `{ "name": "theme-name", "theme": { "inherits": "parent", "selectors": {...}, "variables": {...}, "breakpoints": {...} } }`
/// Returns the updated state as JSON, or "{}" on error.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn register_theme_json(state_json: &str, theme_json: &str) -> String {
    match (serde_json::from_str::<State>(state_json), serde_json::from_str::<serde_json::Value>(theme_json)) {
        (Ok(mut state), Ok(theme_obj)) => {
            if let (Some(name), Some(theme_entry)) = (theme_obj.get("name"), theme_obj.get("theme")) {
                if let Ok(entry) = serde_json::from_value::<ThemeEntry>(theme_entry.clone()) {
                    let theme_name = name.as_str().unwrap_or("").to_string();
                    if !theme_name.is_empty() {
                        state.themes.insert(theme_name, entry);
                    }
                }
            }
            match serde_json::to_string(&state.to_json()) {
                Ok(s) => s,
                Err(_) => "{}".to_string(),
            }
        }
        _ => "{}".to_string(),
    }
}

/// Set the default and current theme. Returns the updated state as JSON.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn set_theme_json(state_json: &str, theme_name: &str) -> String {
    match serde_json::from_str::<State>(state_json) {
        Ok(mut state) => {
            if state.themes.contains_key(theme_name) {
                state.default_theme = theme_name.to_string();
                state.current_theme = theme_name.to_string();
            }
            match serde_json::to_string(&state.to_json()) {
                Ok(s) => s,
                Err(_) => "{}".to_string(),
            }
        }
        _ => "{}".to_string(),
    }
}

/// Get all theme keys and names as JSON array: [{ "key": "default", "name": "Default Theme" }, ...]
/// Returns array of themes from the state JSON.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn get_theme_list_json(state_json: &str) -> String {
    match serde_json::from_str::<State>(state_json) {
        Ok(state) => {
            let themes: Vec<serde_json::Value> = state.themes.iter().map(|(key, entry)| {
                json!({
                    "key": key,
                    "name": entry.name.as_ref().unwrap_or(key)
                })
            }).collect();
            serde_json::to_string(&themes).unwrap_or_else(|_| "[]".to_string())
        }
        _ => "[]".to_string(),
    }
}

fn merge_props(into: &mut CssProps, from: &CssProps) {
    for (k, v) in from.iter() {
        into.insert(k.clone(), v.clone());
    }
}

// merge_indexmap removed — unused

fn css_props_string(props: &CssProps, vars: &IndexMap<String, String>) -> String {
    let mut buf = String::new();
    for (k, v) in props.iter() {
        buf.push_str(k);
        buf.push(':');
        let val = if v.is_string() {
            let s = v.as_str().unwrap();
            resolve_vars(s, vars)
        } else {
            v.to_string()
        };
        buf.push_str(&val);
        if !val.ends_with(';') {
            buf.push(';');
        }
    }
    buf
}

// Support var(--name) and var(name) with dotted paths
static RE_VAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"var\(\s*-{0,2}([a-zA-Z0-9_.-]+)\s*\)").unwrap());

// Tailwind color palette - embedded from tailwind-colors.html
static TAILWIND_COLORS: Lazy<IndexMap<&'static str, IndexMap<&'static str, &'static str>>> = Lazy::new(|| {
    let mut colors = IndexMap::new();
    
    let mut slate = IndexMap::new();
    slate.insert("50", "#f8fafc"); slate.insert("100", "#f1f5f9"); slate.insert("200", "#e2e8f0");
    slate.insert("300", "#cbd5e1"); slate.insert("400", "#94a3b8"); slate.insert("500", "#64748b");
    slate.insert("600", "#475569"); slate.insert("700", "#334155"); slate.insert("800", "#1e293b");
    slate.insert("900", "#0f172a"); slate.insert("950", "#020617");
    colors.insert("slate", slate);
    
    let mut gray = IndexMap::new();
    gray.insert("50", "#f9fafb"); gray.insert("100", "#f3f4f6"); gray.insert("200", "#e5e7eb");
    gray.insert("300", "#d1d5db"); gray.insert("400", "#9ca3af"); gray.insert("500", "#6b7280");
    gray.insert("600", "#4b5563"); gray.insert("700", "#374151"); gray.insert("800", "#1f2937");
    gray.insert("900", "#111827"); gray.insert("950", "#030712");
    colors.insert("gray", gray);
    
    let mut zinc = IndexMap::new();
    zinc.insert("50", "#fafafa"); zinc.insert("100", "#f4f4f5"); zinc.insert("200", "#e4e4e7");
    zinc.insert("300", "#d4d4d8"); zinc.insert("400", "#a1a1aa"); zinc.insert("500", "#71717a");
    zinc.insert("600", "#52525b"); zinc.insert("700", "#3f3f46"); zinc.insert("800", "#27272a");
    zinc.insert("900", "#18181b"); zinc.insert("950", "#09090b");
    colors.insert("zinc", zinc);
    
    let mut neutral = IndexMap::new();
    neutral.insert("50", "#fafafa"); neutral.insert("100", "#f5f5f5"); neutral.insert("200", "#e5e5e5");
    neutral.insert("300", "#d4d4d4"); neutral.insert("400", "#a3a3a3"); neutral.insert("500", "#737373");
    neutral.insert("600", "#525252"); neutral.insert("700", "#404040"); neutral.insert("800", "#262626");
    neutral.insert("900", "#171717"); neutral.insert("950", "#0a0a0a");
    colors.insert("neutral", neutral);
    
    let mut stone = IndexMap::new();
    stone.insert("50", "#fafaf9"); stone.insert("100", "#f5f5f4"); stone.insert("200", "#e7e5e4");
    stone.insert("300", "#d6d3d1"); stone.insert("400", "#a8a29e"); stone.insert("500", "#78716c");
    stone.insert("600", "#57534e"); stone.insert("700", "#44403c"); stone.insert("800", "#292524");
    stone.insert("900", "#1c1917"); stone.insert("950", "#0c0a09");
    colors.insert("stone", stone);
    
    let mut red = IndexMap::new();
    red.insert("50", "#fef2f2"); red.insert("100", "#fee2e2"); red.insert("200", "#fecaca");
    red.insert("300", "#fca5a5"); red.insert("400", "#f87171"); red.insert("500", "#ef4444");
    red.insert("600", "#dc2626"); red.insert("700", "#b91c1c"); red.insert("800", "#991b1b");
    red.insert("900", "#7f1d1d"); red.insert("950", "#450a0a");
    colors.insert("red", red);
    
    let mut orange = IndexMap::new();
    orange.insert("50", "#fff7ed"); orange.insert("100", "#ffedd5"); orange.insert("200", "#fed7aa");
    orange.insert("300", "#fdba74"); orange.insert("400", "#fb923c"); orange.insert("500", "#f97316");
    orange.insert("600", "#ea580c"); orange.insert("700", "#c2410c"); orange.insert("800", "#9a3412");
    orange.insert("900", "#7c2d12"); orange.insert("950", "#431407");
    colors.insert("orange", orange);
    
    let mut amber = IndexMap::new();
    amber.insert("50", "#fffbeb"); amber.insert("100", "#fef3c7"); amber.insert("200", "#fde68a");
    amber.insert("300", "#fcd34d"); amber.insert("400", "#fbbf24"); amber.insert("500", "#f59e0b");
    amber.insert("600", "#d97706"); amber.insert("700", "#b45309"); amber.insert("800", "#92400e");
    amber.insert("900", "#78350f"); amber.insert("950", "#451a03");
    colors.insert("amber", amber);
    
    let mut blue = IndexMap::new();
    blue.insert("50", "#eff6ff"); blue.insert("100", "#dbeafe"); blue.insert("200", "#bfdbfe");
    blue.insert("300", "#93c5fd"); blue.insert("400", "#60a5fa"); blue.insert("500", "#3b82f6");
    blue.insert("600", "#2563eb"); blue.insert("700", "#1d4ed8"); blue.insert("800", "#1e40af");
    blue.insert("900", "#1e3a8a"); blue.insert("950", "#0b1c52");
    colors.insert("blue", blue);
    
    let mut lime = IndexMap::new();
    lime.insert("50", "#f7fee7"); lime.insert("100", "#ecfccb"); lime.insert("200", "#d9f99d");
    lime.insert("300", "#bef264"); lime.insert("400", "#a3e635"); lime.insert("500", "#84cc16");
    lime.insert("600", "#65a30d"); lime.insert("700", "#4d7c0f"); lime.insert("800", "#3f6212");
    lime.insert("900", "#365314"); lime.insert("950", "#1a2e05");
    colors.insert("lime", lime);
    
    let mut green = IndexMap::new();
    green.insert("50", "#f0fdf4"); green.insert("100", "#dcfce7"); green.insert("200", "#bbf7d0");
    green.insert("300", "#86efac"); green.insert("400", "#4ade80"); green.insert("500", "#22c55e");
    green.insert("600", "#16a34a"); green.insert("700", "#15803d"); green.insert("800", "#166534");
    green.insert("900", "#14532d"); green.insert("950", "#052e16");
    colors.insert("green", green);
    
    let mut emerald = IndexMap::new();
    emerald.insert("50", "#ecfdf5"); emerald.insert("100", "#d1fae5"); emerald.insert("200", "#a7f3d0");
    emerald.insert("300", "#6ee7b7"); emerald.insert("400", "#34d399"); emerald.insert("500", "#10b981");
    emerald.insert("600", "#059669"); emerald.insert("700", "#047857"); emerald.insert("800", "#065f46");
    emerald.insert("900", "#064e3b"); emerald.insert("950", "#022c22");
    colors.insert("emerald", emerald);
    
    let mut teal = IndexMap::new();
    teal.insert("50", "#f0fdfa"); teal.insert("100", "#ccfbf1"); teal.insert("200", "#99f6e4");
    teal.insert("300", "#5eead4"); teal.insert("400", "#2dd4bf"); teal.insert("500", "#14b8a6");
    teal.insert("600", "#0d9488"); teal.insert("700", "#0f766e"); teal.insert("800", "#115e59");
    teal.insert("900", "#134e4a"); teal.insert("950", "#042f2e");
    colors.insert("teal", teal);
    
    let mut cyan = IndexMap::new();
    cyan.insert("50", "#ecfeff"); cyan.insert("100", "#cffafe"); cyan.insert("200", "#a5f3fc");
    cyan.insert("300", "#67e8f9"); cyan.insert("400", "#22d3ee"); cyan.insert("500", "#06b6d4");
    cyan.insert("600", "#0891b2"); cyan.insert("700", "#0e7490"); cyan.insert("800", "#155e75");
    cyan.insert("900", "#164e63"); cyan.insert("950", "#083344");
    colors.insert("cyan", cyan);
    
    let mut sky = IndexMap::new();
    sky.insert("50", "#f0f9ff"); sky.insert("100", "#e0f2fe"); sky.insert("200", "#bae6fd");
    sky.insert("300", "#7dd3fc"); sky.insert("400", "#38bdf8"); sky.insert("500", "#0ea5e9");
    sky.insert("600", "#0284c7"); sky.insert("700", "#0369a1"); sky.insert("800", "#075985");
    sky.insert("900", "#0c4a6e"); sky.insert("950", "#082f49");
    colors.insert("sky", sky);
    
    let mut blue = IndexMap::new();
    blue.insert("50", "#eff6ff"); blue.insert("100", "#dbeafe"); blue.insert("200", "#bfdbfe");
    blue.insert("300", "#93c5fd"); blue.insert("400", "#60a5fa"); blue.insert("500", "#3b82f6");
    blue.insert("600", "#2563eb"); blue.insert("700", "#1d4ed8"); blue.insert("800", "#1e40af");
    blue.insert("900", "#1e3a8a"); blue.insert("950", "#172554");
    colors.insert("blue", blue);
    
    let mut indigo = IndexMap::new();
    indigo.insert("50", "#eef2ff"); indigo.insert("100", "#e0e7ff"); indigo.insert("200", "#c7d2fe");
    indigo.insert("300", "#a5b4fc"); indigo.insert("400", "#818cf8"); indigo.insert("500", "#6366f1");
    indigo.insert("600", "#4f46e5"); indigo.insert("700", "#4338ca"); indigo.insert("800", "#3730a3");
    indigo.insert("900", "#312e81"); indigo.insert("950", "#1e1b4b");
    colors.insert("indigo", indigo);
    
    let mut violet = IndexMap::new();
    violet.insert("50", "#f5f3ff"); violet.insert("100", "#ede9fe"); violet.insert("200", "#ddd6fe");
    violet.insert("300", "#c4b5fd"); violet.insert("400", "#a78bfa"); violet.insert("500", "#8b5cf6");
    violet.insert("600", "#7c3aed"); violet.insert("700", "#6d28d9"); violet.insert("800", "#5b21b6");
    violet.insert("900", "#4c1d95"); violet.insert("950", "#2e1065");
    colors.insert("violet", violet);
    
    let mut purple = IndexMap::new();
    purple.insert("50", "#faf5ff"); purple.insert("100", "#f3e8ff"); purple.insert("200", "#e9d5ff");
    purple.insert("300", "#d8b4fe"); purple.insert("400", "#c084fc"); purple.insert("500", "#a855f7");
    purple.insert("600", "#9333ea"); purple.insert("700", "#7e22ce"); purple.insert("800", "#6b21a8");
    purple.insert("900", "#581c87"); purple.insert("950", "#3b0764");
    colors.insert("purple", purple);
    
    let mut fuchsia = IndexMap::new();
    fuchsia.insert("50", "#fdf4ff"); fuchsia.insert("100", "#fae8ff"); fuchsia.insert("200", "#f5d0fe");
    fuchsia.insert("300", "#f0abfc"); fuchsia.insert("400", "#e879f9"); fuchsia.insert("500", "#d946ef");
    fuchsia.insert("600", "#c026d3"); fuchsia.insert("700", "#a21caf"); fuchsia.insert("800", "#86198f");
    fuchsia.insert("900", "#701a75"); fuchsia.insert("950", "#4a044e");
    colors.insert("fuchsia", fuchsia);
    
    let mut pink = IndexMap::new();
    pink.insert("50", "#fdf2f8"); pink.insert("100", "#fce7f3"); pink.insert("200", "#fbcfe8");
    pink.insert("300", "#f9a8d4"); pink.insert("400", "#f472b6"); pink.insert("500", "#ec4899");
    pink.insert("600", "#db2777"); pink.insert("700", "#be185d"); pink.insert("800", "#9d174d");
    pink.insert("900", "#831843"); pink.insert("950", "#500724");
    colors.insert("pink", pink);
    
    let mut rose = IndexMap::new();
    rose.insert("50", "#fff1f2"); rose.insert("100", "#ffe4e6"); rose.insert("200", "#fecdd3");
    rose.insert("300", "#fda4af"); rose.insert("400", "#fb7185"); rose.insert("500", "#f43f5e");
    rose.insert("600", "#e11d48"); rose.insert("700", "#be123c"); rose.insert("800", "#9f1239");
    rose.insert("900", "#881337"); rose.insert("950", "#4c0519");
    colors.insert("rose", rose);
    
    colors
});

fn resolve_vars(input: &str, vars: &IndexMap<String, String>) -> String {
    let mut out = input.to_string();
    for cap in RE_VAR.captures_iter(input) {
        if let Some(name) = cap.get(1) {
            let key = name.as_str();
            if let Some(val) = vars.get(key) {
                // replace both var(--name) and var(name)
                out = out.replace(&format!("var(--{})", key), val);
                out = out.replace(&format!("var({})", key), val);
            }
        }
    }
    if out.starts_with('$') {
        if let Some(val) = vars.get(&out[1..]) {
            return val.clone();
        }
    }
    out
}

fn camel_case(name: &str) -> String {
    let mut out = String::new();
    let mut upper = false;
    for ch in name.chars() {
        if ch == '-' {
            upper = true;
            continue;
        }
        if upper {
            out.extend(ch.to_uppercase());
            upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

fn css_value_to_rn(
    value: &serde_json::Value,
    vars: &IndexMap<String, String>,
) -> serde_json::Value {
    match value {
        serde_json::Value::String(s) => {
            let s2 = resolve_vars(s, vars);
            if let Some(n) = s2.strip_suffix("px") {
                if let Ok(parsed) = n.trim().parse::<f64>() {
                    return json!(parsed);
                }
            }
            json!(s2)
        }
        _ => value.clone(),
    }
}

fn merge_rn_props(
    into: &mut IndexMap<String, serde_json::Value>,
    css_props: &CssProps,
    vars: &IndexMap<String, String>,
) {
    for (k, v) in css_props.iter() {
        let rn_key = match k.as_str() {
            // Minimal explicit mappings
            "background-color" => "backgroundColor".to_string(),
            "text-align" => "textAlign".to_string(),
            _ => camel_case(k),
        };
        let rn_val = css_value_to_rn(v, vars);
        into.insert(rn_key, rn_val);
    }
}

fn dynamic_css_properties_for_class(class: &str, vars: &IndexMap<String, String>) -> Option<CssProps> {
    // Display utilities
    match class {
        "block" => { let mut p = CssProps::new(); p.insert("display".into(), json!("block")); return Some(p); }
        "inline-block" => { let mut p = CssProps::new(); p.insert("display".into(), json!("inline-block")); return Some(p); }
        "inline" => { let mut p = CssProps::new(); p.insert("display".into(), json!("inline")); return Some(p); }
        "inline-flex" => { let mut p = CssProps::new(); p.insert("display".into(), json!("inline-flex")); return Some(p); }
        "grid" => { let mut p = CssProps::new(); p.insert("display".into(), json!("grid")); return Some(p); }
        "hidden" => { let mut p = CssProps::new(); p.insert("display".into(), json!("none")); return Some(p); }
        _ => {}
    }
    // Flexbox shorthands
    match class {
        "flex" => { let mut p = CssProps::new(); p.insert("display".into(), json!("flex")); return Some(p); }
        "flex-row" => { let mut p = CssProps::new(); p.insert("display".into(), json!("flex")); p.insert("flex-direction".into(), json!("row")); return Some(p); }
        "flex-col" => { let mut p = CssProps::new(); p.insert("display".into(), json!("flex")); p.insert("flex-direction".into(), json!("column")); return Some(p); }
        "flex-1" => { let mut p = CssProps::new(); p.insert("flex".into(), json!(1)); return Some(p); }
        _ => {}
    }
    if let Some(rest) = class.strip_prefix("items-") {
        let mut p = CssProps::new();
        let v = match rest { "start" => "flex-start", "end" => "flex-end", "center" => "center", "stretch" => "stretch", other => other };
        p.insert("align-items".into(), json!(v));
        return Some(p);
    }
    if let Some(rest) = class.strip_prefix("justify-") {
        let mut p = CssProps::new();
        let v = match rest { "start" => "flex-start", "end" => "flex-end", "center" => "center", "between" => "space-between", "around" => "space-around", "evenly" => "space-evenly", other => other };
        p.insert("justify-content".into(), json!(v));
        return Some(p);
    }
    if let Some(value) = class.strip_prefix("p-") {
        return parse_tailwind_spacing(value, &|px| padding_props(&["padding"], px));
    }
    if let Some(value) = class.strip_prefix("px-") {
        return parse_tailwind_spacing(value, &|px| padding_props(&["padding-left", "padding-right"], px));
    }
    if let Some(value) = class.strip_prefix("py-") {
        return parse_tailwind_spacing(value, &|px| padding_props(&["padding-top", "padding-bottom"], px));
    }
    for &(prefix, prop) in &[("pt-", "padding-top"), ("pr-", "padding-right"), ("pb-", "padding-bottom"), ("pl-", "padding-left")] {
        if let Some(value) = class.strip_prefix(prefix) {
            return parse_tailwind_spacing(value, &|px| padding_props(&[prop], px));
        }
    }
    // Margin utilities
    if let Some(value) = class.strip_prefix("m-") {
        return parse_tailwind_spacing(value, &|px| margin_props(&["margin"], px));
    }
    if let Some(value) = class.strip_prefix("mx-") {
        return parse_tailwind_spacing(value, &|px| margin_props(&["margin-left", "margin-right"], px));
    }
    if let Some(value) = class.strip_prefix("my-") {
        return parse_tailwind_spacing(value, &|px| margin_props(&["margin-top", "margin-bottom"], px));
    }
    for &(prefix, prop) in &[("mt-", "margin-top"), ("mr-", "margin-right"), ("mb-", "margin-bottom"), ("ml-", "margin-left")] {
        if let Some(value) = class.strip_prefix(prefix) {
            return parse_tailwind_spacing(value, &|px| margin_props(&[prop], px));
        }
    }
    // Gap utilities (works in RN 0.71+ with Flexbox)
    if let Some(value) = class.strip_prefix("gap-") {
        if !value.starts_with("x-") && !value.starts_with("y-") {
            return parse_tailwind_spacing(value, &|px| {
                let mut props = CssProps::new();
                props.insert("gap".into(), json!(format!("{}px", px)));
                props
            });
        }
    }
    if let Some(value) = class.strip_prefix("gap-x-") {
        return parse_tailwind_spacing(value, &|px| {
            let mut props = CssProps::new();
            props.insert("column-gap".into(), json!(format!("{}px", px)));
            props
        });
    }
    if let Some(value) = class.strip_prefix("gap-y-") {
        return parse_tailwind_spacing(value, &|px| {
            let mut props = CssProps::new();
            props.insert("row-gap".into(), json!(format!("{}px", px)));
            props
        });
    }
    // Space utilities (space-x-*, space-y-*)
    if let Some(value) = class.strip_prefix("space-x-") {
        return parse_tailwind_spacing(value, &|px| {
            let mut props = CssProps::new();
            // In CSS, this is typically done with :not(:last-child) selector
            // For now, we'll set it as a custom property that can be used
            props.insert("--space-x".into(), json!(format!("{}px", px)));
            props
        });
    }
    if let Some(value) = class.strip_prefix("space-y-") {
        return parse_tailwind_spacing(value, &|px| {
            let mut props = CssProps::new();
            props.insert("--space-y".into(), json!(format!("{}px", px)));
            props
        });
    }
    // Font weight utilities
    match class {
        "font-thin" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("100")); return Some(p); }
        "font-extralight" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("200")); return Some(p); }
        "font-light" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("300")); return Some(p); }
        "font-normal" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("400")); return Some(p); }
        "font-medium" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("500")); return Some(p); }
        "font-semibold" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("600")); return Some(p); }
        "font-bold" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("700")); return Some(p); }
        "font-extrabold" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("800")); return Some(p); }
        "font-black" => { let mut p = CssProps::new(); p.insert("font-weight".into(), json!("900")); return Some(p); }
        _ => {}
    }
    // Font family utilities
    match class {
        "font-sans" => { let mut p = CssProps::new(); p.insert("font-family".into(), json!("system-ui, -apple-system, sans-serif")); return Some(p); }
        "font-serif" => { let mut p = CssProps::new(); p.insert("font-family".into(), json!("Georgia, serif")); return Some(p); }
        "font-mono" => { let mut p = CssProps::new(); p.insert("font-family".into(), json!("ui-monospace, monospace")); return Some(p); }
        _ => {}
    }
    // Text size utilities
    match class {
        "text-xs" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("12px")); p.insert("line-height".into(), json!("16px")); return Some(p); }
        "text-sm" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("14px")); p.insert("line-height".into(), json!("20px")); return Some(p); }
        "text-base" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("16px")); p.insert("line-height".into(), json!("24px")); return Some(p); }
        "text-lg" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("18px")); p.insert("line-height".into(), json!("28px")); return Some(p); }
        "text-xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("20px")); p.insert("line-height".into(), json!("28px")); return Some(p); }
        "text-2xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("24px")); p.insert("line-height".into(), json!("32px")); return Some(p); }
        "text-3xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("30px")); p.insert("line-height".into(), json!("36px")); return Some(p); }
        "text-4xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("36px")); p.insert("line-height".into(), json!("40px")); return Some(p); }
        "text-5xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("48px")); p.insert("line-height".into(), json!("1")); return Some(p); }
        "text-6xl" => { let mut p = CssProps::new(); p.insert("font-size".into(), json!("60px")); p.insert("line-height".into(), json!("1")); return Some(p); }
        _ => {}
    }
    // Text alignment
    match class {
        "text-left" => { let mut p = CssProps::new(); p.insert("text-align".into(), json!("left")); return Some(p); }
        "text-center" => { let mut p = CssProps::new(); p.insert("text-align".into(), json!("center")); return Some(p); }
        "text-right" => { let mut p = CssProps::new(); p.insert("text-align".into(), json!("right")); return Some(p); }
        "text-justify" => { let mut p = CssProps::new(); p.insert("text-align".into(), json!("justify")); return Some(p); }
        _ => {}
    }
    // Overflow utilities
    match class {
        "overflow-auto" => { let mut p = CssProps::new(); p.insert("overflow".into(), json!("auto")); return Some(p); }
        "overflow-hidden" => { let mut p = CssProps::new(); p.insert("overflow".into(), json!("hidden")); return Some(p); }
        "overflow-visible" => { let mut p = CssProps::new(); p.insert("overflow".into(), json!("visible")); return Some(p); }
        "overflow-scroll" => { let mut p = CssProps::new(); p.insert("overflow".into(), json!("scroll")); return Some(p); }
        "overflow-x-auto" => { let mut p = CssProps::new(); p.insert("overflow-x".into(), json!("auto")); return Some(p); }
        "overflow-x-hidden" => { let mut p = CssProps::new(); p.insert("overflow-x".into(), json!("hidden")); return Some(p); }
        "overflow-x-scroll" => { let mut p = CssProps::new(); p.insert("overflow-x".into(), json!("scroll")); return Some(p); }
        "overflow-y-auto" => { let mut p = CssProps::new(); p.insert("overflow-y".into(), json!("auto")); return Some(p); }
        "overflow-y-hidden" => { let mut p = CssProps::new(); p.insert("overflow-y".into(), json!("hidden")); return Some(p); }
        "overflow-y-scroll" => { let mut p = CssProps::new(); p.insert("overflow-y".into(), json!("scroll")); return Some(p); }
        _ => {}
    }
    // Shadow utilities (basic cross-platform support)
    match class {
        "shadow-sm" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 1px 2px 0 rgba(0, 0, 0, 0.05)")); return Some(p); }
        "shadow" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1)")); return Some(p); }
        "shadow-md" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1)")); return Some(p); }
        "shadow-lg" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)")); return Some(p); }
        "shadow-xl" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)")); return Some(p); }
        "shadow-2xl" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("0 25px 50px -12px rgba(0, 0, 0, 0.25)")); return Some(p); }
        "shadow-none" => { let mut p = CssProps::new(); p.insert("box-shadow".into(), json!("none")); return Some(p); }
        _ => {}
    }
    // Parse arbitrary values like bg-[var(--primary)], text-[#ff0000], etc.
    if let Some(arb_value) = parse_arbitrary_value(class) {
        return Some(arb_value);
    }
    // text-{color}-{shade}
    if let Some(rest) = class.strip_prefix("text-") {
        if let Some(hex) = get_tailwind_color(rest) {
            let mut props = CssProps::new();
            props.insert("color".into(), json!(hex));
            return Some(props);
        }
    }
    // bg-{color}-{shade}
    if let Some(rest) = class.strip_prefix("bg-") {
        if let Some(hex) = get_tailwind_color(rest) {
            let mut props = CssProps::new();
            props.insert("background-color".into(), json!(hex));
            return Some(props);
        }
    }
    // divide-{color}-{shade} (sets border-color for child dividers)
    if let Some(rest) = class.strip_prefix("divide-") {
        if let Some(hex) = get_tailwind_color(rest) {
            let mut props = CssProps::new();
            props.insert("border-color".into(), json!(hex));
            return Some(props);
        }
    }
    if class == "border" {
        return Some(border_props(None, 1, vars));
    }
    if let Some(rest) = class.strip_prefix("border-") {
        // Parse border-* classes
        // Possible patterns:
        // - border-{color}-{shade} → border-color
        // - border-{side}-{color}-{shade} → border-{side}-color
        // - border-{width} → border-width
        // - border-{side}-{width} → border-{side}-width
        
        let parts: Vec<&str> = rest.split('-').collect();
        
        // Check if first part is a directional side (t, b, l, r, x, y)
        let valid_sides = ["t", "b", "l", "r", "x", "y"];
        let (side, color_or_width_parts) = if parts.len() > 1 && valid_sides.contains(&parts[0]) {
            (Some(parts[0]), &parts[1..])
        } else {
            (None, &parts[..])
        };
        
        // Now check if remaining parts form a color-shade pattern
        if color_or_width_parts.len() == 2 {
            // Could be color-shade like "blue-500"
            let color_shade = color_or_width_parts.join("-");
            if let Some(hex) = get_tailwind_color(&color_shade) {
                let mut props = CssProps::new();
                let prop_name = if let Some(s) = side {
                    format!("border-{}-color", s)
                } else {
                    "border-color".to_string()
                };
                props.insert(prop_name, json!(hex));
                return Some(props);
            }
        }
        
        // Check for simple color without shade (single word color like "black", "white")
        if color_or_width_parts.len() == 1 {
            let potential_color = format!("{}-500", color_or_width_parts[0]);
            if let Some(hex) = get_tailwind_color(&potential_color) {
                let mut props = CssProps::new();
                let prop_name = if let Some(s) = side {
                    format!("border-{}-color", s)
                } else {
                    "border-color".to_string()
                };
                props.insert(prop_name, json!(hex));
                return Some(props);
            }
        }
        
        // Otherwise, check for width (e.g., border-2, border-t-4)
        if color_or_width_parts.len() == 1 {
            if let Ok(width) = color_or_width_parts[0].parse::<i32>() {
                return Some(border_props(side, width, vars));
            }
        }
    }
    // rounded* (border-radius)
    if class == "rounded" { return Some(rounded_props(None, Some("md"))); }
    if let Some(sz) = class.strip_prefix("rounded-") {
        return Some(rounded_props(None, Some(sz)));
    }
    for &(pref, side) in &[("rounded-t", "t"), ("rounded-b", "b"), ("rounded-l", "l"), ("rounded-r", "r")] {
        if class == pref { return Some(rounded_props(Some(side), Some("md"))); }
        if let Some(sz) = class.strip_prefix(&(pref.to_string() + "-")) {
            return Some(rounded_props(Some(side), Some(sz)));
        }
    }
    // cursor-*
    if let Some(cur) = class.strip_prefix("cursor-") {
        let mut props = CssProps::new();
        props.insert("cursor".into(), json!(match cur {
            "pointer" => "pointer",
            "default" => "default",
            "text" => "text",
            "move" => "move",
            "wait" => "wait",
            "not-allowed" => "not-allowed",
            other => other,
        }));
        return Some(props);
    }
    // transition*
    if class == "transition" || class == "transition-all" {
        let mut props = CssProps::new();
        props.insert("transition-property".into(), json!("all"));
        props.insert("transition-duration".into(), json!("150ms"));
        props.insert("transition-timing-function".into(), json!("ease-in-out"));
        return Some(props);
    }
    if class == "transition-none" {
        let mut props = CssProps::new();
        props.insert("transition-property".into(), json!("none"));
        props.insert("transition-duration".into(), json!("0ms"));
        return Some(props);
    }
    if let Some(rest) = class.strip_prefix("transition-") {
        // e.g., transition-colors → limit property; keep default duration/ease
        let mut props = CssProps::new();
        let property = match rest {
            "colors" => "color, background-color, border-color, fill, stroke",
            "opacity" => "opacity",
            "transform" => "transform",
            "shadow" => "box-shadow",
            other => other,
        };
        props.insert("transition-property".into(), json!(property));
        props.insert("transition-duration".into(), json!("150ms"));
        props.insert("transition-timing-function".into(), json!("ease-in-out"));
        return Some(props);
    }
    // width utilities: w-*, w-full, w-screen, w-min, w-max (treat min/max as auto), w-px
    if let Some(val) = class.strip_prefix("w-") {
        return width_like_props("width", val);
    }
    if let Some(val) = class.strip_prefix("min-w-") {
        return width_like_props("min-width", val);
    }
    if let Some(val) = class.strip_prefix("max-w-") {
        return width_like_props("max-width", val);
    }
    // Height utilities
    if let Some(val) = class.strip_prefix("h-") {
        return width_like_props("height", val);
    }
    if let Some(val) = class.strip_prefix("min-h-") {
        return width_like_props("min-height", val);
    }
    if let Some(val) = class.strip_prefix("max-h-") {
        return width_like_props("max-height", val);
    }
    None
}

fn parse_tailwind_spacing<F>(value: &str, builder: &F) -> Option<CssProps>
where
    F: Fn(i32) -> CssProps,
{
    if let Ok(n) = value.parse::<i32>() {
        let px = n * 4;
        return Some(builder(px));
    }
    None
}

fn padding_props(keys: &[&str], px_value: i32) -> CssProps {
    let mut props = CssProps::new();
    let val = format!("{}px", px_value);
    for key in keys {
        props.insert((*key).into(), json!(&val));
    }
    props
}

fn margin_props(keys: &[&str], px_value: i32) -> CssProps {
    let mut props = CssProps::new();
    let val = format!("{}px", px_value);
    for key in keys {
        props.insert((*key).into(), json!(&val));
    }
    props
}

fn border_props(side: Option<&str>, width: i32, _vars: &IndexMap<String, String>) -> CssProps {
    let mut props = CssProps::new();
    let width_str = format!("{}px", width);
    match side {
        None => {
            props.insert("border-width".into(), json!(&width_str));
        }
        Some("t") => {
            props.insert("border-top-width".into(), json!(&width_str));
        }
        Some("b") => {
            props.insert("border-bottom-width".into(), json!(&width_str));
        }
        Some("l") => {
            props.insert("border-left-width".into(), json!(&width_str));
        }
        Some("r") => {
            props.insert("border-right-width".into(), json!(&width_str));
        }
        Some("x") => {
            props.insert("border-left-width".into(), json!(&width_str));
            props.insert("border-right-width".into(), json!(&width_str));
        }
        Some("y") => {
            props.insert("border-top-width".into(), json!(&width_str));
            props.insert("border-bottom-width".into(), json!(&width_str));
        }
        _ => {
            props.insert("border-width".into(), json!(&width_str));
        }
    };
    props.insert("border-color".into(), json!("var(border)"));
    props.insert("border-style".into(), json!("solid"));
    props
}

fn rounded_props(side: Option<&str>, size: Option<&str>) -> CssProps {
    let mut props = CssProps::new();
    let px = match size.unwrap_or("md") {
        "none" => 0,
        "sm" => 2,
        "md" => 4,
        "lg" => 8,
        "xl" => 12,
        "2xl" => 16,
        "3xl" => 24,
        "full" => 9999,
        s => s.parse::<i32>().unwrap_or(4),
    };
    let v = json!(format!("{}px", px));
    match side {
        None => { props.insert("border-radius".into(), v); }
        Some("t") => {
            props.insert("border-top-left-radius".into(), v.clone());
            props.insert("border-top-right-radius".into(), v);
        }
        Some("b") => {
            props.insert("border-bottom-left-radius".into(), v.clone());
            props.insert("border-bottom-right-radius".into(), v);
        }
        Some("l") => { props.insert("border-top-left-radius".into(), v.clone()); props.insert("border-bottom-left-radius".into(), v); }
        Some("r") => { props.insert("border-top-right-radius".into(), v.clone()); props.insert("border-bottom-right-radius".into(), v); }
        _ => { props.insert("border-radius".into(), v); }
    }
    props
}

fn width_like_props(prop: &str, token: &str) -> Option<CssProps> {
    let mut props = CssProps::new();
    let value = match token {
        "full" => Some("100%".to_string()),
        "screen" => Some(if prop == "width" { "100vw" } else { "100vh" }.to_string()),
        "min" => Some("min-content".to_string()),
        "max" => Some("max-content".to_string()),
        "fit" => Some("fit-content".to_string()),
        "auto" => Some("auto".to_string()),
        "px" => Some("1px".to_string()),
        other => {
            // numeric scale n => n*4px, fraction e.g., 1/2 => 50%
            if let Some((a, b)) = other.split_once('/') {
                if let (Ok(na), Ok(nb)) = (a.parse::<f64>(), b.parse::<f64>()) {
                    let pct = (na / nb) * 100.0;
                    Some(format!("{}%", trim_trailing_zeros(pct)))
                } else { None }
            } else if let Ok(n) = other.parse::<i32>() {
                Some(format!("{}px", n * 4))
            } else {
                None
            }
        }
    }?;
    props.insert(prop.into(), json!(value));
    Some(props)
}

fn trim_trailing_zeros(num: f64) -> String {
    let mut s = format!("{:.6}", num);
    while s.contains('.') && s.ends_with('0') { s.pop(); }
    if s.ends_with('.') { s.pop(); }
    s
}

// ---------------- Tailwind subset ----------------

// static RE_NUM: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(?P<prefix>(hover:)?(xs:|sm:|md:|lg:|xl:)*)?(?P<base>.+)$").unwrap());

fn css_escape_class(class: &str) -> String { class.replace(':', "\\:") }

fn class_to_selector(class: &str) -> String {
    let (_bp, hover, base) = parse_prefixed_class(class);
    if hover {
        format!(".{}:hover", css_escape_class(&base))
    } else {
        format!(".{}", css_escape_class(&base))
    }
}

// ------------- helpers for CSS output of media selectors -------------

/// Flatten CSS with potential selectors that include media prelude.
/// This simple post-processor merges entries that use the special selector format
/// "@media (min-width: X) {<sel>" where we will close the block at the end.
/// We group by media and inside concatenate selectors.
pub fn post_process_css(
    raw_rules: &[(String, CssProps)],
    vars: &IndexMap<String, String>,
) -> String {
    // Group into normal rules and media rules
    let mut normal = vec![];
    let mut media_map: IndexMap<String, Vec<(String, CssProps)>> = IndexMap::new();
    for (sel, props) in raw_rules.iter() {
        if let Some((media, inner)) = sel.split_once('{') {
            if media.trim_start().starts_with("@media ") && inner.ends_with('}') {
                let inner_sel = inner.trim_end_matches('}').to_string();
                media_map
                    .entry(media.trim().to_string())
                    .or_default()
                    .push((inner_sel, props.clone()));
                continue;
            }
        }
        normal.push((sel.clone(), props.clone()));
    }
    let mut out = String::new();
    for (sel, props) in normal {
        out.push_str(&sel);
        out.push('{');
        out.push_str(&css_props_string(&props, vars));
        out.push_str("}\n");
    }
    for (media, entries) in media_map {
        out.push_str(&media);
        out.push('{');
        for (sel, props) in entries {
            out.push_str(&sel);
            out.push('{');
            out.push_str(&css_props_string(&props, vars));
            out.push_str("}");
        }
        out.push_str("}\n");
    }
    out
}

// -------- Prefix parsing (hover:, breakpoint:) --------

fn parse_prefixed_class(class: &str) -> (Option<String>, bool, String) {
    // Split by ':' to find prefixes like md:hover:block
    let parts: Vec<&str> = class.split(':').collect();
    if parts.len() == 1 {
        return (None, false, class.to_string());
    }
    let mut bp: Option<String> = None;
    let mut hover = false;
    for &p in &parts[..parts.len() - 1] {
        match p {
            "hover" => hover = true,
            "xs" | "sm" | "md" | "lg" | "xl" => bp = Some(p.to_string()),
            _ => {}
        }
    }
    let base = parts.last().unwrap().to_string();
    (bp, hover, base)
}

fn wrap_with_media(selector: &str, bp_key: Option<&str>, bps: &IndexMap<String, String>) -> String {
    if let Some(k) = bp_key {
        if let Some(val) = bps.get(k) {
            return format!("@media (min-width: {}) {{{}}}", val, selector);
        }
    }
    selector.to_string()
}

/// Get a Tailwind color hex value from a string like "slate-200" or "blue-500"
fn get_tailwind_color(color_shade: &str) -> Option<String> {
    let parts: Vec<&str> = color_shade.split('-').collect();
    if parts.len() != 2 {
        return None;
    }
    let color_name = parts[0];
    let shade = parts[1];
    
    TAILWIND_COLORS
        .get(color_name)
        .and_then(|shades| shades.get(shade))
        .map(|&hex| hex.to_string())
}

/// Parse arbitrary values like bg-[var(--primary)], text-[#ff0000], border-[hsl(200,50%,50%)]
fn parse_arbitrary_value(class: &str) -> Option<CssProps> {
    // Match pattern: prefix-[value]
    if let Some(bracket_start) = class.find('[') {
        if !class.ends_with(']') {
            return None;
        }
        let prefix = &class[..bracket_start];
        let value = &class[bracket_start + 1..class.len() - 1];
        
        let mut props = CssProps::new();
        match prefix {
            "bg" => {
                props.insert("background-color".into(), json!(value));
                return Some(props);
            }
            "text" => {
                props.insert("color".into(), json!(value));
                return Some(props);
            }
            "border" => {
                props.insert("border-color".into(), json!(value));
                return Some(props);
            }
            "divide" => {
                props.insert("border-color".into(), json!(value));
                return Some(props);
            }
            _ => return None,
        }
    }
    None
}

// re-export minimal API for CLI
pub mod api {
    pub use super::{SelectorStyles, State};
}

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

    #[test]
    fn default_theme_has_p2() {
        let mut st = State::new_default();
        let css = st.css_for_web();
        assert!(css.contains(".p-2{"));
        assert!(css.contains("padding:8px"));
    }

    #[test]
    fn rn_conversion() {
        let st = State::new_default();
        let out = st.rn_styles_for("button", &[]);
        assert!(out.get("backgroundColor").is_some());
    }

    #[test]
    fn embedded_defaults_and_version() {
        // default_state should contain the default theme and some variables
        let st = State::default_state();
        assert!(st.themes.contains_key("default"));
        let def = st.themes.get("default").unwrap();
        assert!(def.variables.contains_key("primary"));

        // Version should compile and be non-empty (env! evaluated at compile-time)
        let v = get_version();
        assert!(!v.is_empty());
    }

    #[test]
    fn border_color_with_direction() {
        let mut st = State::new_default();
        
        // Test border-b-blue-500 (border-bottom with blue color shade 500)
        st.register_tailwind_classes(["border-b-blue-500".to_string()]);
        let css = st.css_for_web();
        assert!(css.contains(".border-b-blue-500{"));
        assert!(css.contains("border-bottom-color:#3b82f6") || css.contains("border-b-color:#3b82f6"));
        
        // Test border-t-red-500
        st.register_tailwind_classes(["border-t-red-500".to_string()]);
        let css = st.css_for_web();
        assert!(css.contains(".border-t-red-500{"));
        
        // Test border-blue-500 (all borders)
        st.register_tailwind_classes(["border-blue-500".to_string()]);
        let css = st.css_for_web();
        assert!(css.contains(".border-blue-500{"));
        assert!(css.contains("border-color:#3b82f6"));
    }

    #[test]
    fn border_width_with_direction() {
        let mut st = State::new_default();
        
        // Test border-b-2 (border-bottom width 2px)
        st.register_tailwind_classes(["border-b-2".to_string()]);
        let css = st.css_for_web();
        assert!(css.contains(".border-b-2{"));
        assert!(css.contains("border-bottom-width:2px"));
        
        // Test border-2 (all borders width 2px)
        st.register_tailwind_classes(["border-2".to_string()]);
        let css = st.css_for_web();
        assert!(css.contains(".border-2{"));
        assert!(css.contains("border-width:2px"));
    }

    #[test]
    fn display_flex_hover_breakpoint() {
        let mut st = State::new_default();
        st.register_tailwind_classes([
            "block".into(),
            "inline-flex".into(),
            "hidden".into(),
            "md:flex".into(),
            "md:hover:block".into(),
        ]);
        let css = st.css_for_web();
        assert!(css.contains(".block{"));
        assert!(css.contains("display:block"));
        assert!(css.contains(".inline-flex{"));
        assert!(css.contains("display:inline-flex"));
        assert!(css.contains(".hidden{"));
        assert!(css.contains("display:none"));
        // breakpoint rule
        assert!(css.contains("@media (min-width: 768px)"));
        assert!(css.contains(".flex{display:flex"));
        // hover inside media (substring check)
        assert!(css.contains(":hover{display:block"));

        // RN resolves base class styles ignoring prefixes
        let rn = st.rn_styles_for("div", &["md:flex".into()]);
        assert_eq!(rn.get("display").and_then(|v| v.as_str()), Some("flex"));
    }
}

#[cfg(all(target_os = "android", feature = "android"))]
#[cfg(feature = "android")]
mod android_jni;

mod bridge_common;
mod ffi;

pub use ffi::*;

#[cfg(target_vendor = "apple")]
mod ios_ffi;