css2xr 0.1.0

A lightweight, pure Rust HTML/CSS layout engine for WebXR (Flexbox, Grid, Animation).
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
//! XR CSS Engine - WebXR向けCSS/HTMLパーサー
//!
//! HTML/CSSを解析してXR空間に配置可能な要素データを生成
//!
//! WASM対応: wasm-pack build --target web

use wasm_bindgen::prelude::*;

// ============================================================================
// WASM Exports
// ============================================================================

/// HTML/CSSを処理してJSON文字列を返す (WASM用)
#[wasm_bindgen]
pub fn process_to_json(html: &str, css: &str, vw: f32, vh: f32) -> String {
    let elements = process(html, css, vw, vh);
    to_json(&elements)
}

// ============================================================================
// Types
// ============================================================================

#[derive(Clone, Copy)]
struct Length { value: f32, is_auto: bool, is_pct: bool }

impl Default for Length {
    fn default() -> Self { Self { value: 0.0, is_auto: true, is_pct: false } }
}

impl Length {
    fn px(v: f32) -> Self { Self { value: v, is_auto: false, is_pct: false } }
    fn auto() -> Self { Self { value: 0.0, is_auto: true, is_pct: false } }
    fn parse(s: &str) -> Self {
        let s = s.trim();
        if s == "auto" { return Self::auto(); }
        let is_pct = s.ends_with('%');
        let v = s.trim_end_matches("px").trim_end_matches('%').parse().unwrap_or(0.0);
        Self { value: v, is_auto: false, is_pct }
    }
    fn to_px(&self, parent: f32) -> f32 {
        if self.is_auto { 0.0 } else if self.is_pct { self.value / 100.0 * parent } else { self.value }
    }
}

#[derive(Clone, Copy, Default)]
struct Color { r: u8, g: u8, b: u8, a: f32 }

impl Color {
    fn parse(s: &str) -> Self {
        let s = s.trim();
        match s {
            "transparent" => Self { r: 0, g: 0, b: 0, a: 0.0 },
            "black" => Self { r: 0, g: 0, b: 0, a: 1.0 },
            "white" => Self { r: 255, g: 255, b: 255, a: 1.0 },
            "red" => Self { r: 255, g: 0, b: 0, a: 1.0 },
            "green" => Self { r: 0, g: 128, b: 0, a: 1.0 },
            "blue" => Self { r: 0, g: 0, b: 255, a: 1.0 },
            "gray" | "grey" => Self { r: 128, g: 128, b: 128, a: 1.0 },
            _ if s.starts_with('#') && s.len() == 7 => Self {
                r: u8::from_str_radix(&s[1..3], 16).unwrap_or(0),
                g: u8::from_str_radix(&s[3..5], 16).unwrap_or(0),
                b: u8::from_str_radix(&s[5..7], 16).unwrap_or(0),
                a: 1.0,
            },
            _ if s.starts_with("rgba(") => {
                let inner = s.trim_start_matches("rgba(").trim_end_matches(')');
                let p: Vec<&str> = inner.split(',').collect();
                if p.len() == 4 {
                    Self {
                        r: p[0].trim().parse().unwrap_or(0),
                        g: p[1].trim().parse().unwrap_or(0),
                        b: p[2].trim().parse().unwrap_or(0),
                        a: p[3].trim().parse().unwrap_or(1.0),
                    }
                } else { Self::default() }
            }
            _ => Self::default(),
        }
    }
    fn to_gl(&self) -> [f32; 4] {
        [self.r as f32 / 255.0, self.g as f32 / 255.0, self.b as f32 / 255.0, self.a]
    }
}

#[derive(Clone, Copy, Default, PartialEq)]
enum Display { #[default] Block, Flex, Grid, None }

#[derive(Clone, Copy, Default, PartialEq)]
enum Position { #[default] Static, Relative, Absolute }

#[derive(Clone, Copy, Default, PartialEq)]
enum FlexDir { #[default] Row, Column }

#[derive(Clone, Copy, Default, PartialEq)]
enum Justify { #[default] Start, End, Center, Between, Around }

#[derive(Clone, Copy, Default, PartialEq)]
enum Align { #[default] Stretch, Start, End, Center }

// アニメーション関連の型
#[derive(Clone, Copy, Default, PartialEq)]
enum TimingFn { #[default] Linear, Ease, EaseIn, EaseOut, EaseInOut }

#[derive(Clone, Copy, Default, PartialEq)]
enum AnimDirection { #[default] Normal, Reverse, Alternate, AlternateReverse }

#[derive(Clone, Copy, Default, PartialEq)]
enum FillMode { #[default] None, Forwards, Backwards, Both }

#[derive(Clone, Default)]
struct Animation {
    name: String,
    duration: f32,      // seconds
    delay: f32,         // seconds
    timing: TimingFn,
    iteration: f32,     // 回数 (infinite = f32::INFINITY)
    direction: AnimDirection,
    fill: FillMode,
}

#[derive(Clone, Default)]
struct Transition {
    property: String,   // "all" or specific property
    duration: f32,
    delay: f32,
    timing: TimingFn,
}

#[derive(Clone, Copy, Default)]
struct Transform {
    translate_x: f32,
    translate_y: f32,
    translate_z: f32,
    rotate_x: f32,      // degrees
    rotate_y: f32,
    rotate_z: f32,
    scale_x: f32,
    scale_y: f32,
    scale_z: f32,
}

impl Transform {
    fn identity() -> Self {
        Self {
            scale_x: 1.0, scale_y: 1.0, scale_z: 1.0,
            ..Default::default()
        }
    }
}

#[derive(Clone, Copy, Default, PartialEq)]
enum Cursor { #[default] Default, Pointer, Move, Text, NotAllowed }

#[derive(Clone, Copy, Default)]
struct Style {
    display: Display, position: Position,
    width: Length, height: Length,
    padding: [Length; 4], margin: [Length; 4], 
    // Position offsets (top, right, bottom, left)
    pos_offset: [Length; 4],
    // Flexbox
    flex_dir: FlexDir, justify: Justify, align: Align, gap: Length, 
    flex_grow: f32, flex_shrink: f32,
    // Grid
    grid_cols: Vec4, grid_rows: Vec4,
    grid_col: (i32, i32), grid_row: (i32, i32),
    // Visual
    bg: Color, color: Color, opacity: f32, radius: f32, font_size: f32,
    z_index: i32,
    // Transform
    transform: Transform,
    // Interaction
    cursor: Cursor,
    pointer_events: bool, // true = auto, false = none
}

// アニメーション情報は別途保持(Copyできないため)
#[derive(Clone, Default)]
struct StyleExt {
    animation: Option<Animation>,
    transition: Option<Transition>,
}

// 固定サイズ配列でトラックサイズを保持(簡易実装)
#[derive(Clone, Copy, Default)]
struct Vec4 {
    values: [f32; 4],
    count: usize,
}

impl Style {
    fn apply(&mut self, p: &str, v: &str) {
        match p {
            "display" => self.display = match v.trim() { 
                "flex" => Display::Flex, 
                "grid" => Display::Grid,
                "none" => Display::None, 
                _ => Display::Block 
            },
            "position" => self.position = match v.trim() {
                "relative" => Position::Relative,
                "absolute" => Position::Absolute,
                _ => Position::Static
            },
            "width" => self.width = Length::parse(v),
            "height" => self.height = Length::parse(v),
            "padding" => { let l = Length::parse(v); self.padding = [l; 4]; }
            "padding-top" => self.padding[0] = Length::parse(v),
            "padding-right" => self.padding[1] = Length::parse(v),
            "padding-bottom" => self.padding[2] = Length::parse(v),
            "padding-left" => self.padding[3] = Length::parse(v),
            "margin" => { let l = Length::parse(v); self.margin = [l; 4]; }
            "margin-top" => self.margin[0] = Length::parse(v),
            "margin-right" => self.margin[1] = Length::parse(v),
            "margin-bottom" => self.margin[2] = Length::parse(v),
            "margin-left" => self.margin[3] = Length::parse(v),
            // Position offsets
            "top" => self.pos_offset[0] = Length::parse(v),
            "right" => self.pos_offset[1] = Length::parse(v),
            "bottom" => self.pos_offset[2] = Length::parse(v),
            "left" => self.pos_offset[3] = Length::parse(v),
            "z-index" => self.z_index = v.trim().parse().unwrap_or(0),
            // Flexbox
            "flex-direction" => self.flex_dir = if v.contains("column") { FlexDir::Column } else { FlexDir::Row },
            "justify-content" => self.justify = match v.trim() {
                "flex-end" | "end" => Justify::End, "center" => Justify::Center,
                "space-between" => Justify::Between, "space-around" => Justify::Around, _ => Justify::Start
            },
            "align-items" => self.align = match v.trim() {
                "flex-start" | "start" => Align::Start, "flex-end" | "end" => Align::End,
                "center" => Align::Center, _ => Align::Stretch
            },
            "gap" => self.gap = Length::parse(v),
            "flex-grow" => self.flex_grow = v.trim().parse().unwrap_or(0.0),
            "flex-shrink" => self.flex_shrink = v.trim().parse().unwrap_or(1.0),
            "flex" => {
                let parts: Vec<&str> = v.trim().split_whitespace().collect();
                if let Some(g) = parts.get(0) { self.flex_grow = g.parse().unwrap_or(0.0); }
                if let Some(s) = parts.get(1) { self.flex_shrink = s.parse().unwrap_or(1.0); }
            }
            // Grid container
            "grid-template-columns" => self.grid_cols = Self::parse_tracks(v),
            "grid-template-rows" => self.grid_rows = Self::parse_tracks(v),
            // Grid item
            "grid-column" => self.grid_col = Self::parse_grid_placement(v),
            "grid-row" => self.grid_row = Self::parse_grid_placement(v),
            // Visual
            "background-color" | "background" => self.bg = Color::parse(v),
            "color" => self.color = Color::parse(v),
            "opacity" => self.opacity = v.trim().parse().unwrap_or(1.0),
            "border-radius" => self.radius = v.trim().trim_end_matches("px").parse().unwrap_or(0.0),
            "font-size" => self.font_size = v.trim().trim_end_matches("px").parse().unwrap_or(16.0),
            // Transform
            "transform" => self.transform = Self::parse_transform(v),
            // Interaction
            "cursor" => self.cursor = match v.trim() {
                "pointer" => Cursor::Pointer,
                "move" => Cursor::Move,
                "text" => Cursor::Text,
                "not-allowed" => Cursor::NotAllowed,
                _ => Cursor::Default,
            },
            "pointer-events" => self.pointer_events = v.trim() != "none",
            _ => {}
        }
    }
    
    fn parse_transform(v: &str) -> Transform {
        let mut t = Transform::identity();
        let v = v.trim();
        
        // 各transform関数をパース
        let mut i = 0;
        let chars: Vec<char> = v.chars().collect();
        
        while i < chars.len() {
            // 関数名を取得
            let fn_start = i;
            while i < chars.len() && chars[i] != '(' { i += 1; }
            if i >= chars.len() { break; }
            let fn_name: String = chars[fn_start..i].iter().collect();
            let fn_name = fn_name.trim();
            i += 1; // skip '('
            
            // 引数を取得
            let arg_start = i;
            let mut paren_depth = 1;
            while i < chars.len() && paren_depth > 0 {
                if chars[i] == '(' { paren_depth += 1; }
                if chars[i] == ')' { paren_depth -= 1; }
                i += 1;
            }
            let args: String = chars[arg_start..i-1].iter().collect();
            let args: Vec<f32> = args.split(',')
                .map(|s| s.trim().trim_end_matches("px").trim_end_matches("deg").parse().unwrap_or(0.0))
                .collect();
            
            match fn_name {
                "translateX" => if let Some(&x) = args.get(0) { t.translate_x = x; }
                "translateY" => if let Some(&y) = args.get(0) { t.translate_y = y; }
                "translateZ" => if let Some(&z) = args.get(0) { t.translate_z = z; }
                "translate" => {
                    if let Some(&x) = args.get(0) { t.translate_x = x; }
                    if let Some(&y) = args.get(1) { t.translate_y = y; }
                }
                "translate3d" => {
                    if let Some(&x) = args.get(0) { t.translate_x = x; }
                    if let Some(&y) = args.get(1) { t.translate_y = y; }
                    if let Some(&z) = args.get(2) { t.translate_z = z; }
                }
                "rotateX" => if let Some(&x) = args.get(0) { t.rotate_x = x; }
                "rotateY" => if let Some(&y) = args.get(0) { t.rotate_y = y; }
                "rotateZ" | "rotate" => if let Some(&z) = args.get(0) { t.rotate_z = z; }
                "rotate3d" => {
                    // rotate3d(x, y, z, angle) - 簡易対応
                    if let Some(&angle) = args.get(3) {
                        t.rotate_z = angle; // 簡易: Z軸回転として扱う
                    }
                }
                "scaleX" => if let Some(&x) = args.get(0) { t.scale_x = x; }
                "scaleY" => if let Some(&y) = args.get(0) { t.scale_y = y; }
                "scaleZ" => if let Some(&z) = args.get(0) { t.scale_z = z; }
                "scale" => {
                    if let Some(&s) = args.get(0) { 
                        t.scale_x = s; 
                        t.scale_y = args.get(1).copied().unwrap_or(s);
                    }
                }
                "scale3d" => {
                    if let Some(&x) = args.get(0) { t.scale_x = x; }
                    if let Some(&y) = args.get(1) { t.scale_y = y; }
                    if let Some(&z) = args.get(2) { t.scale_z = z; }
                }
                _ => {}
            }
            
            // 次の関数へ
            while i < chars.len() && chars[i].is_whitespace() { i += 1; }
        }
        
        t
    }
    
    fn parse_tracks(v: &str) -> Vec4 {
        let mut result = Vec4::default();
        for (i, part) in v.split_whitespace().enumerate() {
            if i >= 4 { break; }
            // "1fr" -> 1.0, "100px" -> 100.0, "repeat(3, 1fr)" は未対応
            let val = if part.ends_with("fr") {
                part.trim_end_matches("fr").parse().unwrap_or(1.0) * -1.0 // 負数でfr表示
            } else {
                part.trim_end_matches("px").parse().unwrap_or(0.0)
            };
            result.values[i] = val;
            result.count = i + 1;
        }
        result
    }
    
    fn parse_grid_placement(v: &str) -> (i32, i32) {
        // "1", "1 / 3", "1 / span 2"
        let parts: Vec<&str> = v.split('/').map(|s| s.trim()).collect();
        let start: i32 = parts.get(0).and_then(|s| s.parse().ok()).unwrap_or(1);
        let end_or_span = parts.get(1).unwrap_or(&"");
        
        if end_or_span.starts_with("span") {
            let span: i32 = end_or_span.trim_start_matches("span").trim().parse().unwrap_or(1);
            (start, span)
        } else if let Ok(end) = end_or_span.parse::<i32>() {
            (start, end - start)
        } else {
            (start, 1)
        }
    }
}

// ============================================================================
// DOM
// ============================================================================

#[derive(Clone, Default)]
struct EventHandlers {
    onclick: Option<String>,
    onmouseenter: Option<String>,
    onmouseleave: Option<String>,
    onpointerdown: Option<String>,
    onpointerup: Option<String>,
}

struct Node {
    tag: String, classes: Vec<String>, id: Option<String>,
    attrs: Vec<(String, String)>,
    inline: Vec<(String, String)>, children: Vec<usize>, text: Option<String>,
    events: EventHandlers,
}

fn parse_html(html: &str) -> Vec<Node> {
    let mut nodes: Vec<Node> = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    let c: Vec<char> = html.chars().collect();
    let (mut i, n) = (0, c.len());
    
    while i < n {
        if c[i] == '<' {
            if i + 1 < n && c[i + 1] == '/' {
                while i < n && c[i] != '>' { i += 1; }
                i += 1; stack.pop(); continue;
            }
            if i + 3 < n && c[i+1] == '!' && c[i+2] == '-' {
                while i + 2 < n && !(c[i] == '-' && c[i+1] == '-' && c[i+2] == '>') { i += 1; }
                i += 3; continue;
            }
            i += 1;
            let ts = i;
            while i < n && !c[i].is_whitespace() && c[i] != '>' && c[i] != '/' { i += 1; }
            let tag: String = c[ts..i].iter().collect::<String>().to_lowercase();
            
            let mut node = Node { 
                tag: tag.clone(), classes: vec![], id: None, attrs: vec![], 
                inline: vec![], children: vec![], text: None,
                events: EventHandlers::default(),
            };
            
            while i < n && c[i] != '>' && c[i] != '/' {
                while i < n && c[i].is_whitespace() { i += 1; }
                if i >= n || c[i] == '>' || c[i] == '/' { break; }
                let as_ = i;
                while i < n && c[i] != '=' && c[i] != '>' && !c[i].is_whitespace() { i += 1; }
                let aname: String = c[as_..i].iter().collect();
                let aval = if i < n && c[i] == '=' {
                    i += 1;
                    if i < n && (c[i] == '"' || c[i] == '\'') {
                        let q = c[i]; i += 1;
                        let vs = i;
                        while i < n && c[i] != q { i += 1; }
                        let v: String = c[vs..i].iter().collect();
                        i += 1; v
                    } else { String::new() }
                } else { String::new() };
                
                // 全属性を保存
                node.attrs.push((aname.clone(), aval.clone()));
                
                match aname.to_lowercase().as_str() {
                    "class" => node.classes = aval.split_whitespace().map(|s| s.into()).collect(),
                    "id" => node.id = Some(aval),
                    "style" => {
                        for d in aval.split(';') {
                            if let Some(p) = d.find(':') {
                                node.inline.push((d[..p].trim().into(), d[p+1..].trim().into()));
                            }
                        }
                    }
                    // イベントハンドラ
                    "onclick" => node.events.onclick = Some(aval),
                    "onmouseenter" => node.events.onmouseenter = Some(aval),
                    "onmouseleave" => node.events.onmouseleave = Some(aval),
                    "onpointerdown" => node.events.onpointerdown = Some(aval),
                    "onpointerup" => node.events.onpointerup = Some(aval),
                    // data-* イベント (XR用)
                    "data-onclick" => node.events.onclick = Some(aval),
                    "data-action" => node.events.onclick = Some(aval),
                    _ => {}
                }
            }
            while i < n && c[i] != '>' { i += 1; }
            let sc = i > 0 && c[i-1] == '/';
            i += 1;
            let nid = nodes.len();
            if let Some(&p) = stack.last() { nodes[p].children.push(nid); }
            nodes.push(node);
            if !sc && !["br","hr","img","input","meta","link"].contains(&tag.as_str()) { stack.push(nid); }
        } else {
            let ts = i;
            while i < n && c[i] != '<' { i += 1; }
            let t: String = c[ts..i].iter().collect::<String>().trim().into();
            if !t.is_empty() && !stack.is_empty() {
                nodes[*stack.last().unwrap()].text = Some(t);
            }
        }
    }
    nodes
}

// ============================================================================
// CSS
// ============================================================================

struct Rule { sel: String, decls: Vec<(String, String)>, spec: u32 }

// キーフレーム定義
#[derive(Clone, Default)]
struct Keyframe {
    percent: f32, // 0.0 - 1.0
    props: Vec<(String, String)>,
}

#[derive(Clone, Default)]
struct KeyframeAnimation {
    name: String,
    keyframes: Vec<Keyframe>,
}

fn parse_css(css: &str) -> (Vec<Rule>, Vec<KeyframeAnimation>) {
    let mut rules = Vec::new();
    let mut keyframe_anims = Vec::new();
    let css = css.split("/*").map(|s| s.split("*/").last().unwrap_or("")).collect::<String>();
    let c: Vec<char> = css.chars().collect();
    let (mut i, n) = (0, c.len());
    
    while i < n {
        while i < n && c[i].is_whitespace() { i += 1; }
        if i >= n { break; }
        
        // @keyframes パース
        if i + 10 < n && c[i..i+10].iter().collect::<String>() == "@keyframes" {
            i += 10;
            while i < n && c[i].is_whitespace() { i += 1; }
            
            // アニメーション名を取得
            let name_start = i;
            while i < n && c[i] != '{' && !c[i].is_whitespace() { i += 1; }
            let anim_name: String = c[name_start..i].iter().collect();
            
            while i < n && c[i] != '{' { i += 1; }
            i += 1; // skip '{'
            
            let mut keyframes = Vec::new();
            
            // キーフレーム内をパース
            while i < n {
                while i < n && c[i].is_whitespace() { i += 1; }
                if i >= n || c[i] == '}' { i += 1; break; }
                
                // パーセント/from/to を取得
                let percent_start = i;
                while i < n && c[i] != '{' { i += 1; }
                let percent_str: String = c[percent_start..i].iter().collect();
                let percent_str = percent_str.trim();
                
                let percent = if percent_str == "from" {
                    0.0
                } else if percent_str == "to" {
                    1.0
                } else {
                    percent_str.trim_end_matches('%').parse::<f32>().unwrap_or(0.0) / 100.0
                };
                
                i += 1; // skip '{'
                
                // プロパティを取得
                let props_start = i;
                while i < n && c[i] != '}' { i += 1; }
                let props_str: String = c[props_start..i].iter().collect();
                i += 1; // skip '}'
                
                let props: Vec<_> = props_str.split(';').filter_map(|d| {
                    let d = d.trim();
                    d.find(':').map(|p| (d[..p].trim().into(), d[p+1..].trim().into()))
                }).collect();
                
                if !props.is_empty() {
                    keyframes.push(Keyframe { percent, props });
                }
            }
            
            keyframes.sort_by(|a, b| a.percent.partial_cmp(&b.percent).unwrap());
            keyframe_anims.push(KeyframeAnimation { name: anim_name.trim().into(), keyframes });
            continue;
        }
        
        // 他の@ルールをスキップ
        if c[i] == '@' { 
            while i < n && c[i] != '{' { i += 1; }
            i += 1;
            let mut depth = 1;
            while i < n && depth > 0 {
                if c[i] == '{' { depth += 1; }
                if c[i] == '}' { depth -= 1; }
                i += 1;
            }
            continue; 
        }
        
        let ss = i;
        while i < n && c[i] != '{' { i += 1; }
        let sel: String = c[ss..i].iter().collect::<String>().trim().into();
        i += 1;
        let ds = i;
        while i < n && c[i] != '}' { i += 1; }
        let decl: String = c[ds..i].iter().collect();
        i += 1;
        let decls: Vec<_> = decl.split(';').filter_map(|d| {
            let d = d.trim();
            d.find(':').map(|p| (d[..p].trim().into(), d[p+1..].trim().into()))
        }).collect();
        if !decls.is_empty() {
            let spec = sel.chars().fold(0u32, |a, c| a + if c == '#' { 100 } else if c == '.' { 10 } else { 0 });
            for s in sel.split(',') { rules.push(Rule { sel: s.trim().into(), decls: decls.clone(), spec }); }
        }
    }
    (rules, keyframe_anims)
}

fn matches(sel: &str, node: &Node) -> bool {
    // 子孫セレクタの場合は最後の部分のみ評価
    let last = sel.split_whitespace().last().unwrap_or(sel);
    
    let mut remaining = last.to_string();
    
    // IDセレクタ (#id) を抽出
    let mut required_id: Option<String> = None;
    if let Some(hash_pos) = remaining.find('#') {
        let after = &remaining[hash_pos + 1..];
        let end = after.find(|c: char| c == '.' || c == '[' || c == '#').unwrap_or(after.len());
        required_id = Some(after[..end].to_string());
        remaining = format!("{}{}", &remaining[..hash_pos], &after[end..]);
    }
    
    // 属性セレクタ ([attr] or [attr=value]) を抽出
    let mut required_attrs: Vec<(String, Option<String>)> = vec![];
    while let Some(start) = remaining.find('[') {
        if let Some(rel_end) = remaining[start..].find(']') {
            let end = start + rel_end;
            let content = &remaining[start + 1..end];
            
            if let Some(eq) = content.find('=') {
                let name = content[..eq].to_string();
                let val = content[eq + 1..].trim_matches('"').trim_matches('\'').to_string();
                required_attrs.push((name, Some(val)));
            } else {
                required_attrs.push((content.to_string(), None));
            }
            remaining = format!("{}{}", &remaining[..start], &remaining[end + 1..]);
        } else {
            break;
        }
    }
    
    // クラスセレクタ (.class1.class2) を抽出
    let mut required_classes: Vec<String> = vec![];
    let mut tag_name: Option<String> = None;
    
    // 先頭がタグ名かクラスか判定
    if !remaining.is_empty() && !remaining.starts_with('.') {
        // タグ名あり
        if let Some(dot_pos) = remaining.find('.') {
            let t = remaining[..dot_pos].to_string();
            if !t.is_empty() {
                tag_name = Some(t);
            }
            remaining = remaining[dot_pos..].to_string();
        } else {
            // クラスなし、タグ名のみ
            if !remaining.is_empty() {
                tag_name = Some(remaining.clone());
            }
            remaining.clear();
        }
    }
    
    // 残りは全て.class形式
    for part in remaining.split('.') {
        if !part.is_empty() {
            required_classes.push(part.to_string());
        }
    }
    
    // マッチング
    // タグ
    if let Some(ref t) = tag_name {
        if t != "*" && t != &node.tag {
            return false;
        }
    }
    
    // ID
    if let Some(ref id) = required_id {
        if node.id.as_ref() != Some(id) {
            return false;
        }
    }
    
    // クラス(全て持っている必要あり)
    for c in &required_classes {
        if !node.classes.iter().any(|nc| nc == c) {
            return false;
        }
    }
    
    // 属性
    for (name, val) in &required_attrs {
        let found = node.attrs.iter().any(|(k, v)| {
            k == name && (val.is_none() || val.as_ref() == Some(v))
        });
        if !found {
            return false;
        }
    }
    
    true
}

// ============================================================================
// Layout
// ============================================================================

#[derive(Clone, Copy, Default)]
struct Layout { x: f32, y: f32, w: f32, h: f32 }

fn compute(nodes: &[Node], styles: &[Style], idx: usize, aw: f32, _ah: f32, out: &mut [Layout]) -> (f32, f32) {
    let s = &styles[idx];
    if s.display == Display::None { return (0.0, 0.0); }
    
    let p = [s.padding[0].to_px(aw), s.padding[1].to_px(aw), s.padding[2].to_px(aw), s.padding[3].to_px(aw)];
    let m = [s.margin[0].to_px(aw), s.margin[1].to_px(aw), s.margin[2].to_px(aw), s.margin[3].to_px(aw)];
    
    // 幅の計算: 固定値があればそれを使用
    let explicit_w = if s.width.is_auto { None } else { Some(s.width.to_px(aw)) };
    let content_w = explicit_w.unwrap_or((aw - p[1] - p[3] - m[1] - m[3]).max(0.0));
    
    // 子要素のサイズを先に計算
    let node = &nodes[idx];
    let mut csz: Vec<(usize, f32, f32, f32)> = vec![]; // (idx, w, h, flex_grow)
    for &c in &node.children { 
        let (w, h) = compute(nodes, styles, c, content_w, 10000.0, out);
        let child_m = &styles[c].margin;
        let mw = child_m[1].to_px(content_w) + child_m[3].to_px(content_w);
        let mh = child_m[0].to_px(content_w) + child_m[2].to_px(content_w);
        csz.push((c, w + mw, h + mh, styles[c].flex_grow)); 
    }
    
    // テキストサイズ
    let tw = node.text.as_ref().map(|t| t.len() as f32 * s.font_size * 0.6).unwrap_or(0.0);
    let th = if node.text.is_some() { s.font_size * 1.4 } else { 0.0 };
    
    // 内部コンテンツサイズを計算
    let (iw, ih) = if s.display == Display::Flex {
        let g = s.gap.to_px(content_w);
        let gap_total = g * csz.len().saturating_sub(1) as f32;
        if s.flex_dir == FlexDir::Row {
            let children_w: f32 = csz.iter().map(|(_, w, _, _)| w).sum();
            let children_h: f32 = csz.iter().map(|(_, _, h, _)| *h).fold(0.0f32, |a, b| a.max(b));
            (children_w + gap_total + tw, children_h.max(th))
        } else {
            let children_w: f32 = csz.iter().map(|(_, w, _, _)| *w).fold(0.0f32, |a, b| a.max(b));
            let children_h: f32 = csz.iter().map(|(_, _, h, _)| *h).sum();
            (children_w.max(tw), children_h + gap_total + th)
        }
    } else {
        // Block layout
        let children_w: f32 = csz.iter().map(|(_, w, _, _)| *w).fold(0.0f32, |a, b| a.max(b));
        let children_h: f32 = csz.iter().map(|(_, _, h, _)| *h).sum();
        (children_w.max(tw), children_h + th)
    };
    
    // 最終サイズ (marginは含まない - 親がmarginを加算する)
    let fw = if let Some(w) = explicit_w { 
        w + p[1] + p[3] 
    } else {
        // width: auto の場合
        if iw > 0.0 || tw > 0.0 {
            (iw + p[1] + p[3]).min(aw - m[1] - m[3])
        } else {
            aw - m[1] - m[3] // ブロック要素は親の幅いっぱいに広がる
        }
    };
    let fh = if s.height.is_auto { 
        ih + p[0] + p[2] 
    } else { 
        s.height.to_px(aw) + p[0] + p[2] 
    };
    
    out[idx] = Layout { x: 0.0, y: 0.0, w: fw, h: fh };
    (fw, fh)
}

fn position(nodes: &[Node], styles: &[Style], idx: usize, x: f32, y: f32, parent_layout: Option<&Layout>, out: &mut [Layout]) {
    let s = &styles[idx];
    if s.display == Display::None { return; }
    
    // 自身のmarginを考慮して位置を設定
    let m = [s.margin[0].to_px(out[idx].w), s.margin[1].to_px(out[idx].w), 
             s.margin[2].to_px(out[idx].w), s.margin[3].to_px(out[idx].w)];
    
    // position: absolute/relative の処理
    let (final_x, final_y) = match s.position {
        Position::Absolute => {
            // absoluteは親のcontaining blockを基準
            if let Some(pl) = parent_layout {
                let top = if !s.pos_offset[0].is_auto { s.pos_offset[0].to_px(pl.h) } else { 0.0 };
                let left = if !s.pos_offset[3].is_auto { s.pos_offset[3].to_px(pl.w) } else { 0.0 };
                let right = if !s.pos_offset[1].is_auto { s.pos_offset[1].to_px(pl.w) } else { 0.0 };
                let bottom = if !s.pos_offset[2].is_auto { s.pos_offset[2].to_px(pl.h) } else { 0.0 };
                
                // rightが指定されている場合
                let ax = if !s.pos_offset[3].is_auto {
                    pl.x + left
                } else if !s.pos_offset[1].is_auto {
                    pl.x + pl.w - out[idx].w - right
                } else {
                    x + m[3]
                };
                
                // bottomが指定されている場合
                let ay = if !s.pos_offset[0].is_auto {
                    pl.y + top
                } else if !s.pos_offset[2].is_auto {
                    pl.y + pl.h - out[idx].h - bottom
                } else {
                    y + m[0]
                };
                
                (ax, ay)
            } else {
                (x + m[3], y + m[0])
            }
        }
        Position::Relative => {
            // relativeは通常位置からのオフセット
            let top = s.pos_offset[0].to_px(out[idx].h);
            let left = s.pos_offset[3].to_px(out[idx].w);
            (x + m[3] + left, y + m[0] + top)
        }
        Position::Static => (x + m[3], y + m[0])
    };
    
    out[idx].x = final_x;
    out[idx].y = final_y;
    
    let l = out[idx];
    let p = [s.padding[0].to_px(l.h), s.padding[1].to_px(l.w), s.padding[2].to_px(l.h), s.padding[3].to_px(l.w)];
    let (cw, ch) = (l.w - p[1] - p[3], l.h - p[0] - p[2]);
    let node = &nodes[idx];
    let g = s.gap.to_px(l.w);
    
    // 子要素の情報を収集(position:absoluteは別扱い)
    let mut normal_kids: Vec<_> = vec![];
    let mut absolute_kids: Vec<_> = vec![];
    
    for &c in &node.children {
        let cs = &styles[c];
        let cm = [cs.margin[0].to_px(cw), cs.margin[1].to_px(cw), cs.margin[2].to_px(cw), cs.margin[3].to_px(cw)];
        let w_with_m = out[c].w + cm[1] + cm[3];
        let h_with_m = out[c].h + cm[0] + cm[2];
        
        if cs.position == Position::Absolute {
            absolute_kids.push((c, w_with_m, h_with_m, cs.flex_grow, cs.flex_shrink, cs.grid_col, cs.grid_row));
        } else {
            normal_kids.push((c, w_with_m, h_with_m, cs.flex_grow, cs.flex_shrink, cs.grid_col, cs.grid_row));
        }
    }
    
    // Grid layout
    if s.display == Display::Grid && !normal_kids.is_empty() {
        let col_tracks = compute_grid_tracks(&s.grid_cols, cw, g);
        let row_tracks = compute_grid_tracks(&s.grid_rows, ch, g);
        
        let mut grid_cursor_col = 0;
        let mut grid_cursor_row = 0;
        
        for (c, _kw, _kh, _, _, grid_col, grid_row) in &normal_kids {
            let cs = &styles[*c];
            let cm = [cs.margin[0].to_px(cw), cs.margin[1].to_px(cw), cs.margin[2].to_px(cw), cs.margin[3].to_px(cw)];
            
            // grid-column, grid-row が指定されていればそれを使用
            let (col_start, col_span) = if grid_col.0 > 0 { (grid_col.0 as usize - 1, grid_col.1.max(1) as usize) } else { (grid_cursor_col, 1) };
            let (row_start, row_span) = if grid_row.0 > 0 { (grid_row.0 as usize - 1, grid_row.1.max(1) as usize) } else { (grid_cursor_row, 1) };
            
            // 位置計算
            let cx = l.x + p[3] + col_tracks.iter().take(col_start).map(|(_, pos)| pos).sum::<f32>() + cm[3];
            let cy = l.y + p[0] + row_tracks.iter().take(row_start).map(|(_, pos)| pos).sum::<f32>() + cm[0];
            
            // サイズ更新(グリッドセルに合わせる)
            let cell_w: f32 = col_tracks.iter().skip(col_start).take(col_span).map(|(size, _)| size).sum::<f32>() 
                + g * (col_span.saturating_sub(1)) as f32 - cm[1] - cm[3];
            let cell_h: f32 = row_tracks.iter().skip(row_start).take(row_span).map(|(size, _)| size).sum::<f32>()
                + g * (row_span.saturating_sub(1)) as f32 - cm[0] - cm[2];
            
            out[*c].w = cell_w.max(0.0);
            out[*c].h = cell_h.max(0.0);
            
            position(nodes, styles, *c, cx - cm[3], cy - cm[0], Some(&l), out);
            
            // カーソル更新(自動配置用)
            grid_cursor_col = col_start + col_span;
            if grid_cursor_col >= col_tracks.len().max(1) {
                grid_cursor_col = 0;
                grid_cursor_row += 1;
            }
        }
    } else if s.display == Display::Flex && !normal_kids.is_empty() {
        // Flexbox layout
        let kids = &normal_kids;
        let tot: f32 = if s.flex_dir == FlexDir::Row { 
            kids.iter().map(|(_, w, _, _, _, _, _)| w).sum() 
        } else { 
            kids.iter().map(|(_, _, h, _, _, _, _)| h).sum() 
        };
        let gaps = g * kids.len().saturating_sub(1) as f32;
        let main = if s.flex_dir == FlexDir::Row { cw } else { ch };
        let rem = main - tot - gaps;
        
        let total_grow: f32 = kids.iter().map(|(_, _, _, fg, _, _, _)| fg).sum();
        let total_shrink: f32 = kids.iter().map(|(_, _, _, _, fs, _, _)| fs).sum();
        
        let adjusted_sizes: Vec<f32> = kids.iter().map(|(_, w, h, fg, fs, _, _)| {
            let base = if s.flex_dir == FlexDir::Row { *w } else { *h };
            if rem > 0.0 && total_grow > 0.0 {
                base + (rem * fg / total_grow)
            } else if rem < 0.0 && total_shrink > 0.0 {
                (base + rem * fs / total_shrink).max(0.0)
            } else {
                base
            }
        }).collect();
        
        let (mut pos, extra) = if total_grow > 0.0 || rem < 0.0 {
            (0.0, 0.0)
        } else {
            match s.justify {
                Justify::Start => (0.0, 0.0), 
                Justify::End => (rem.max(0.0), 0.0), 
                Justify::Center => (rem.max(0.0) / 2.0, 0.0),
                Justify::Between if kids.len() > 1 => (0.0, rem.max(0.0) / (kids.len() - 1) as f32),
                Justify::Between => (0.0, 0.0),
                Justify::Around => (rem.max(0.0) / kids.len() as f32 / 2.0, rem.max(0.0) / kids.len() as f32),
            }
        };
        
        for (i, (c, _kw, kh, _, _, _, _)) in kids.iter().enumerate() {
            let cs = &styles[*c];
            let cm = [cs.margin[0].to_px(cw), cs.margin[1].to_px(cw), cs.margin[2].to_px(cw), cs.margin[3].to_px(cw)];
            let adj_size = adjusted_sizes[i];
            
            let (cx, cy) = if s.flex_dir == FlexDir::Row {
                let cr = match s.align { 
                    Align::Start => 0.0, 
                    Align::End => ch - kh, 
                    Align::Center => (ch - kh) / 2.0, 
                    Align::Stretch => 0.0 
                };
                (l.x + p[3] + pos + cm[3], l.y + p[0] + cr + cm[0])
            } else {
                let kw = out[*c].w + cm[1] + cm[3];
                let cr = match s.align { 
                    Align::Start => 0.0, 
                    Align::End => cw - kw, 
                    Align::Center => (cw - kw) / 2.0, 
                    Align::Stretch => 0.0 
                };
                (l.x + p[3] + cr + cm[3], l.y + p[0] + pos + cm[0])
            };
            
            if total_grow > 0.0 && rem > 0.0 {
                if s.flex_dir == FlexDir::Row {
                    out[*c].w = adj_size - cm[1] - cm[3];
                } else {
                    out[*c].h = adj_size - cm[0] - cm[2];
                }
            }
            
            position(nodes, styles, *c, cx - cm[3], cy - cm[0], Some(&l), out);
            pos += adj_size + g + extra;
        }
    } else if !normal_kids.is_empty() {
        // Block layout
        let mut cur_y = l.y + p[0];
        for (c, _kw, kh, _, _, _, _) in normal_kids {
            position(nodes, styles, c, l.x + p[3], cur_y, Some(&l), out);
            cur_y += kh;
        }
    }
    
    // position: absoluteの子を処理
    for (c, _, _, _, _, _, _) in absolute_kids {
        position(nodes, styles, c, l.x, l.y, Some(&l), out);
    }
}

// Gridトラックのサイズと累積位置を計算
fn compute_grid_tracks(tracks: &Vec4, available: f32, gap: f32) -> Vec<(f32, f32)> {
    if tracks.count == 0 {
        return vec![(available, available + gap)];
    }
    
    let mut result = Vec::with_capacity(tracks.count);
    let mut total_fr = 0.0;
    let mut fixed_size = 0.0;
    
    for i in 0..tracks.count {
        let v = tracks.values[i];
        if v < 0.0 {
            total_fr += -v; // frは負数で格納
        } else {
            fixed_size += v;
        }
    }
    
    let gap_total = gap * (tracks.count.saturating_sub(1)) as f32;
    let fr_space = (available - fixed_size - gap_total).max(0.0);
    let fr_unit = if total_fr > 0.0 { fr_space / total_fr } else { 0.0 };
    
    let mut pos = 0.0;
    for i in 0..tracks.count {
        let v = tracks.values[i];
        let size = if v < 0.0 { -v * fr_unit } else { v };
        result.push((size, size + gap));
        pos += size + gap;
    }
    
    result
}

// ============================================================================
// Output
// ============================================================================

#[derive(Debug, Clone, Default)]
pub struct XrTransform {
    pub translate: [f32; 3],  // x, y, z
    pub rotate: [f32; 3],     // x, y, z (degrees)
    pub scale: [f32; 3],      // x, y, z
}

#[derive(Debug, Clone)]
pub struct XrKeyframe {
    pub percent: f32,
    pub opacity: Option<f32>,
    pub transform: Option<XrTransform>,
    pub bg: Option<[f32; 4]>,
}

#[derive(Debug, Clone)]
pub struct XrAnimation {
    pub name: String,
    pub duration: f32,
    pub delay: f32,
    pub iteration: f32,      // f32::INFINITY for infinite
    pub direction: String,   // "normal", "reverse", "alternate", "alternate-reverse"
    pub timing: String,      // "linear", "ease", etc.
    pub keyframes: Vec<XrKeyframe>,
}

#[derive(Debug, Clone, Default)]
pub struct XrEvents {
    pub click: Option<String>,      // onclick handler名 or JS
    pub hover: Option<String>,      // onmouseenter
    pub pointer_down: Option<String>,
    pub pointer_up: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct XrHitBox {
    pub x: f32, pub y: f32, pub z: f32,  // 中心座標
    pub w: f32, pub h: f32, pub d: f32,  // 幅、高さ、奥行き
}

#[derive(Debug, Clone)]
pub struct XrElement {
    pub id: usize,
    pub x: f32, pub y: f32, pub w: f32, pub h: f32,
    pub bg: [f32; 4], pub color: [f32; 4],
    pub opacity: f32, pub radius: f32, pub font_size: f32,
    pub text: Option<String>,
    pub transform: XrTransform,
    pub animation: Option<XrAnimation>,
    pub events: XrEvents,
    pub interactive: bool,  // クリック可能かどうか
    pub cursor: String,     // "pointer", "default", etc.
}

pub fn process(html: &str, css: &str, vw: f32, vh: f32) -> Vec<XrElement> {
    let nodes = parse_html(html);
    if nodes.is_empty() { return vec![]; }
    
    let (rules, keyframe_anims) = parse_css(css);
    let mut styles: Vec<Style> = nodes.iter().map(|_| Style { 
        opacity: 1.0, 
        font_size: 16.0, 
        transform: Transform::identity(),
        ..Default::default() 
    }).collect();
    let mut style_exts: Vec<StyleExt> = nodes.iter().map(|_| StyleExt::default()).collect();
    
    for (i, node) in nodes.iter().enumerate() {
        let mut m: Vec<_> = rules.iter().filter(|r| matches(&r.sel, node)).collect();
        m.sort_by_key(|r| r.spec);
        for r in m { 
            for (p, v) in &r.decls { 
                styles[i].apply(p, v);
                // アニメーション関連のパース
                if p == "animation" || p == "animation-name" {
                    style_exts[i].animation = Some(parse_animation_shorthand(v));
                }
            } 
        }
        for (p, v) in &node.inline { 
            styles[i].apply(p, v); 
            if p == "animation" || p == "animation-name" {
                style_exts[i].animation = Some(parse_animation_shorthand(v));
            }
        }
    }
    
    let mut layouts = vec![Layout::default(); nodes.len()];
    
    // ルートノードを検出
    let mut is_child = vec![false; nodes.len()];
    for node in &nodes {
        for &c in &node.children {
            is_child[c] = true;
        }
    }
    
    // 各ルートノードを処理
    let mut cur_y = 0.0;
    for i in 0..nodes.len() {
        if !is_child[i] {
            compute(&nodes, &styles, i, vw, vh, &mut layouts);
            position(&nodes, &styles, i, 0.0, cur_y, None, &mut layouts);
            cur_y += layouts[i].h;
        }
    }
    
    nodes.iter().enumerate().filter_map(|(i, node)| {
        let s = &styles[i]; 
        let l = &layouts[i];
        let ext = &style_exts[i];
        
        if s.display == Display::None || (s.bg.a <= 0.0 && node.text.is_none()) { return None; }
        
        // アニメーション情報を構築
        let animation = ext.animation.as_ref().and_then(|anim| {
            // 対応するキーフレームを探す
            let kf_anim = keyframe_anims.iter().find(|k| k.name == anim.name)?;
            
            let keyframes: Vec<XrKeyframe> = kf_anim.keyframes.iter().map(|kf| {
                let mut opacity = None;
                let mut transform = None;
                let mut bg = None;
                
                for (prop, val) in &kf.props {
                    match prop.as_str() {
                        "opacity" => opacity = val.parse().ok(),
                        "transform" => {
                            let t = Style::parse_transform(val);
                            transform = Some(XrTransform {
                                translate: [t.translate_x, t.translate_y, t.translate_z],
                                rotate: [t.rotate_x, t.rotate_y, t.rotate_z],
                                scale: [t.scale_x, t.scale_y, t.scale_z],
                            });
                        }
                        "background" | "background-color" => {
                            let c = Color::parse(val);
                            bg = Some(c.to_gl());
                        }
                        _ => {}
                    }
                }
                
                XrKeyframe { percent: kf.percent, opacity, transform, bg }
            }).collect();
            
            Some(XrAnimation {
                name: anim.name.clone(),
                duration: anim.duration,
                delay: anim.delay,
                iteration: anim.iteration,
                direction: match anim.direction {
                    AnimDirection::Normal => "normal",
                    AnimDirection::Reverse => "reverse",
                    AnimDirection::Alternate => "alternate",
                    AnimDirection::AlternateReverse => "alternate-reverse",
                }.into(),
                timing: match anim.timing {
                    TimingFn::Linear => "linear",
                    TimingFn::Ease => "ease",
                    TimingFn::EaseIn => "ease-in",
                    TimingFn::EaseOut => "ease-out",
                    TimingFn::EaseInOut => "ease-in-out",
                }.into(),
                keyframes,
            })
        });
        
        // イベント情報を構築
        let has_events = node.events.onclick.is_some() 
            || node.events.onmouseenter.is_some()
            || node.events.onpointerdown.is_some();
        
        let events = XrEvents {
            click: node.events.onclick.clone(),
            hover: node.events.onmouseenter.clone(),
            pointer_down: node.events.onpointerdown.clone(),
            pointer_up: node.events.onpointerup.clone(),
        };
        
        let cursor_str = match s.cursor {
            Cursor::Pointer => "pointer",
            Cursor::Move => "move",
            Cursor::Text => "text",
            Cursor::NotAllowed => "not-allowed",
            Cursor::Default => "default",
        }.to_string();
        
        Some(XrElement {
            id: i, x: l.x, y: l.y, w: l.w, h: l.h,
            bg: s.bg.to_gl(), color: s.color.to_gl(),
            opacity: s.opacity, radius: s.radius, font_size: s.font_size,
            text: node.text.clone(),
            transform: XrTransform {
                translate: [s.transform.translate_x, s.transform.translate_y, s.transform.translate_z],
                rotate: [s.transform.rotate_x, s.transform.rotate_y, s.transform.rotate_z],
                scale: [s.transform.scale_x, s.transform.scale_y, s.transform.scale_z],
            },
            animation,
            events,
            interactive: has_events || s.cursor == Cursor::Pointer,
            cursor: cursor_str,
        })
    }).collect()
}

fn parse_animation_shorthand(v: &str) -> Animation {
    let mut anim = Animation::default();
    let parts: Vec<&str> = v.split_whitespace().collect();
    
    for (i, part) in parts.iter().enumerate() {
        if i == 0 {
            // 最初は名前
            anim.name = part.to_string();
        } else if part.ends_with('s') || part.ends_with("ms") {
            // duration or delay
            let val = if part.ends_with("ms") {
                part.trim_end_matches("ms").parse::<f32>().unwrap_or(0.0) / 1000.0
            } else {
                part.trim_end_matches('s').parse::<f32>().unwrap_or(0.0)
            };
            if anim.duration == 0.0 {
                anim.duration = val;
            } else {
                anim.delay = val;
            }
        } else if *part == "infinite" {
            anim.iteration = f32::INFINITY;
        } else if let Ok(n) = part.parse::<f32>() {
            anim.iteration = n;
        } else {
            match *part {
                "linear" => anim.timing = TimingFn::Linear,
                "ease" => anim.timing = TimingFn::Ease,
                "ease-in" => anim.timing = TimingFn::EaseIn,
                "ease-out" => anim.timing = TimingFn::EaseOut,
                "ease-in-out" => anim.timing = TimingFn::EaseInOut,
                "reverse" => anim.direction = AnimDirection::Reverse,
                "alternate" => anim.direction = AnimDirection::Alternate,
                "alternate-reverse" => anim.direction = AnimDirection::AlternateReverse,
                "forwards" => anim.fill = FillMode::Forwards,
                "backwards" => anim.fill = FillMode::Backwards,
                "both" => anim.fill = FillMode::Both,
                _ => {}
            }
        }
    }
    
    if anim.iteration == 0.0 { anim.iteration = 1.0; }
    anim
}

pub fn to_json(elements: &[XrElement]) -> String {
    let mut o = String::from("[");
    for (i, e) in elements.iter().enumerate() {
        if i > 0 { o.push(','); }
        
        // transform文字列
        let transform_str = format!(
            r#","transform":{{"translate":[{:.1},{:.1},{:.1}],"rotate":[{:.1},{:.1},{:.1}],"scale":[{:.2},{:.2},{:.2}]}}"#,
            e.transform.translate[0], e.transform.translate[1], e.transform.translate[2],
            e.transform.rotate[0], e.transform.rotate[1], e.transform.rotate[2],
            e.transform.scale[0], e.transform.scale[1], e.transform.scale[2]
        );
        
        // animation文字列
        let anim_str = e.animation.as_ref().map(|a| {
            let keyframes_str: Vec<String> = a.keyframes.iter().map(|kf| {
                let mut props = vec![format!(r#""percent":{:.2}"#, kf.percent)];
                if let Some(op) = kf.opacity {
                    props.push(format!(r#""opacity":{:.2}"#, op));
                }
                if let Some(ref t) = kf.transform {
                    props.push(format!(
                        r#""transform":{{"translate":[{:.1},{:.1},{:.1}],"rotate":[{:.1},{:.1},{:.1}],"scale":[{:.2},{:.2},{:.2}]}}"#,
                        t.translate[0], t.translate[1], t.translate[2],
                        t.rotate[0], t.rotate[1], t.rotate[2],
                        t.scale[0], t.scale[1], t.scale[2]
                    ));
                }
                if let Some(ref bg) = kf.bg {
                    props.push(format!(r#""bg":[{:.3},{:.3},{:.3},{:.3}]"#, bg[0], bg[1], bg[2], bg[3]));
                }
                format!("{{{}}}", props.join(","))
            }).collect();
            
            format!(
                r#","animation":{{"name":"{}","duration":{:.2},"delay":{:.2},"iteration":{},"direction":"{}","timing":"{}","keyframes":[{}]}}"#,
                a.name, a.duration, a.delay,
                if a.iteration.is_infinite() { "\"infinite\"".to_string() } else { format!("{:.1}", a.iteration) },
                a.direction, a.timing,
                keyframes_str.join(",")
            )
        }).unwrap_or_default();
        
        // 基本情報(閉じ括弧なし)
        o.push_str(&format!(
            r#"{{"id":{},"x":{:.1},"y":{:.1},"w":{:.1},"h":{:.1},"bg":[{:.3},{:.3},{:.3},{:.3}],"color":[{:.3},{:.3},{:.3},{:.3}],"opacity":{:.2},"radius":{:.1},"fontSize":{:.1}{}{}{}"#,
            e.id, e.x, e.y, e.w, e.h, e.bg[0], e.bg[1], e.bg[2], e.bg[3],
            e.color[0], e.color[1], e.color[2], e.color[3], e.opacity, e.radius, e.font_size,
            e.text.as_ref().map(|t| format!(r#","text":"{}""#, t.replace('"', "\\\""))).unwrap_or_default(),
            transform_str,
            anim_str
        ));
        
        // イベント情報を追加
        if e.interactive {
            o.push_str(&format!(r#","interactive":true,"cursor":"{}""#, e.cursor));
            
            let mut events_parts = vec![];
            if let Some(ref c) = e.events.click {
                events_parts.push(format!(r#""click":"{}""#, c.replace('"', "\\\"")));
            }
            if let Some(ref h) = e.events.hover {
                events_parts.push(format!(r#""hover":"{}""#, h.replace('"', "\\\"")));
            }
            if let Some(ref pd) = e.events.pointer_down {
                events_parts.push(format!(r#""pointerDown":"{}""#, pd.replace('"', "\\\"")));
            }
            if let Some(ref pu) = e.events.pointer_up {
                events_parts.push(format!(r#""pointerUp":"{}""#, pu.replace('"', "\\\"")));
            }
            
            if !events_parts.is_empty() {
                o.push_str(&format!(r#","events":{{{}}}"#, events_parts.join(",")));
            }
        }
        
        o.push('}');
    }
    o.push(']'); o
}



#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_basic() {
        let html = r#"<div class="box">Hello</div>"#;
        let css = r#".box { background: red; width: 100px; height: 50px; }"#;
        let els = process(html, css, 200.0, 200.0);
        assert_eq!(els.len(), 1);
        assert_eq!(els[0].w, 100.0);
        assert_eq!(els[0].h, 50.0);
    }
    
    #[test]
    fn test_flex_column() {
        let html = r#"<div class="outer"><div class="inner">A</div><div class="inner">B</div></div>"#;
        let css = r#".outer { display: flex; flex-direction: column; width: 200px; background: red; padding: 10px; } .inner { height: 30px; background: blue; }"#;
        let els = process(html, css, 400.0, 400.0);
        
        println!("Elements: {:?}", els.len());
        for e in &els {
            println!("  id={} w={} h={} bg={:?}", e.id, e.w, e.h, e.bg);
        }
        
        // outer should contain both inner elements
        let outer = els.iter().find(|e| e.id == 0).unwrap();
        // height should be: padding(10) + inner(30) + inner(30) + padding(10) = 80
        assert!(outer.h >= 80.0, "outer height {} should be >= 80", outer.h);
    }
    
    #[test]
    fn test_nested_flex() {
        let html = r#"<div class="col"><div class="row"><div class="box">A</div></div><div class="row"><div class="box">B</div></div></div>"#;
        let css = r#".col { display: flex; flex-direction: column; gap: 10px; background: gray; padding: 10px; } .row { display: flex; background: blue; } .box { width: 50px; height: 50px; background: red; }"#;
        let els = process(html, css, 400.0, 400.0);
        
        // Find rows and check Y positions are different
        let rows: Vec<_> = els.iter().filter(|e| e.bg[2] > 0.9).collect(); // blue
        if rows.len() >= 2 {
            assert!(rows[0].y != rows[1].y, "rows should have different Y positions");
        }
    }
    
    #[test]
    fn test_color() {
        let c = Color::parse("#ff0000");
        assert_eq!(c.r, 255);
        assert_eq!(c.g, 0);
        let c2 = Color::parse("rgba(100, 150, 200, 0.5)");
        assert_eq!(c2.r, 100);
        assert!((c2.a - 0.5).abs() < 0.01);
    }
    
    #[test]
    fn test_margin() {
        let html = r#"<div class="outer"><div class="inner">A</div></div>"#;
        let css = r#".outer { width: 200px; height: 100px; background: red; } .inner { margin: 10px; width: 50px; height: 30px; background: blue; }"#;
        let els = process(html, css, 300.0, 200.0);
        
        let inner = els.iter().find(|e| e.id == 1).unwrap();
        // inner should be at (10, 10) due to margin
        assert_eq!(inner.x, 10.0, "inner x should be 10 (margin-left)");
        assert_eq!(inner.y, 10.0, "inner y should be 10 (margin-top)");
    }
    
    #[test]
    fn test_flex_grow() {
        let html = r#"<div class="row"><div class="a">A</div><div class="b">B</div></div>"#;
        let css = r#".row { display: flex; width: 300px; background: gray; } .a { flex-grow: 1; height: 30px; background: red; } .b { width: 100px; height: 30px; background: blue; }"#;
        let els = process(html, css, 400.0, 200.0);
        
        let a = els.iter().find(|e| e.text.as_deref() == Some("A")).unwrap();
        let b = els.iter().find(|e| e.text.as_deref() == Some("B")).unwrap();
        
        // A should grow to fill remaining space (300 - 100 = 200)
        assert!(a.w >= 190.0, "A width {} should be ~200 (flex-grow)", a.w);
        assert_eq!(b.w, 100.0, "B width should be 100");
    }
    
    #[test]
    fn test_multi_class_selector() {
        // matchesの単体テスト
        let node = Node {
            tag: "div".into(),
            classes: vec!["box".into(), "red".into(), "large".into()],
            id: None,
            attrs: vec![],
            inline: vec![],
            children: vec![],
            text: Some("C".into()),
            events: EventHandlers::default(),
        };
        
        assert!(matches(".box", &node), ".box should match");
        assert!(matches(".box.red", &node), ".box.red should match");
        assert!(matches(".box.red.large", &node), ".box.red.large should match");
        assert!(!matches(".blue", &node), ".blue should NOT match");
        
        // process全体のテスト
        let html = r#"<div class="box red">A</div><div class="box blue">B</div><div class="box red large">C</div>"#;
        let css = r#".box { width: 50px; height: 50px; } .box.red { background: red; } .box.blue { background: blue; } .box.red.large { width: 100px; }"#;
        let els = process(html, css, 400.0, 200.0);
        
        let a = els.iter().find(|e| e.text.as_deref() == Some("A")).unwrap();
        let b = els.iter().find(|e| e.text.as_deref() == Some("B")).unwrap();
        let c = els.iter().find(|e| e.text.as_deref() == Some("C")).unwrap();
        
        assert!(a.bg[0] > 0.9, "A should be red");
        assert_eq!(a.w, 50.0, "A width should be 50");
        assert!(b.bg[2] > 0.9, "B should be blue");
        assert_eq!(b.w, 50.0, "B width should be 50");
        assert_eq!(c.w, 100.0, "C width should be 100");
    }
    
    #[test]
    fn test_attribute_selector() {
        let html = r#"<div data-xr="panel">A</div><div>B</div><div data-xr="button">C</div>"#;
        let css = r#"[data-xr] { background: green; width: 100px; height: 50px; } [data-xr="button"] { background: blue; }"#;
        let els = process(html, css, 400.0, 200.0);
        
        let a = els.iter().find(|e| e.text.as_deref() == Some("A")).unwrap();
        let c = els.iter().find(|e| e.text.as_deref() == Some("C")).unwrap();
        
        // A: [data-xr] -> green
        assert!(a.bg[1] > 0.4, "A should be green");
        assert_eq!(a.w, 100.0, "A width should be 100");
        // C: [data-xr="button"] -> blue (overrides green)
        assert!(c.bg[2] > 0.9, "C should be blue");
    }
    
    #[test]
    fn test_css_grid() {
        let html = r#"<div class="grid"><div class="a">A</div><div class="b">B</div><div class="c">C</div><div class="d">D</div></div>"#;
        let css = r#".grid { display: grid; grid-template-columns: 100px 100px; grid-template-rows: 50px 50px; gap: 10px; width: 210px; height: 110px; background: gray; } .a, .b, .c, .d { background: blue; }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let a = els.iter().find(|e| e.text.as_deref() == Some("A")).unwrap();
        let b = els.iter().find(|e| e.text.as_deref() == Some("B")).unwrap();
        let c = els.iter().find(|e| e.text.as_deref() == Some("C")).unwrap();
        let d = els.iter().find(|e| e.text.as_deref() == Some("D")).unwrap();
        
        // A: (0,0), B: (110,0), C: (0,60), D: (110,60)
        assert_eq!(a.w, 100.0, "A width should be 100");
        assert_eq!(a.h, 50.0, "A height should be 50");
        assert!(b.x > a.x, "B should be right of A");
        assert!(c.y > a.y, "C should be below A");
        assert!(d.x > c.x && d.y > b.y, "D should be at (1,1)");
    }
    
    #[test]
    fn test_position_absolute() {
        let html = r#"<div class="container"><div class="box">A</div><div class="abs">B</div></div>"#;
        let css = r#".container { position: relative; width: 200px; height: 150px; background: gray; } .box { width: 50px; height: 50px; background: blue; } .abs { position: absolute; top: 10px; right: 10px; width: 40px; height: 40px; background: red; }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let container = els.iter().find(|e| e.id == 0).unwrap();
        let abs = els.iter().find(|e| e.text.as_deref() == Some("B")).unwrap();
        
        // absolute positioned element should be at top-right of container
        let expected_x = container.x + container.w - 40.0 - 10.0; // right: 10px
        let expected_y = container.y + 10.0; // top: 10px
        
        assert!((abs.x - expected_x).abs() < 1.0, "abs x={} should be near {}", abs.x, expected_x);
        assert!((abs.y - expected_y).abs() < 1.0, "abs y={} should be near {}", abs.y, expected_y);
    }
    
    #[test]
    fn test_position_relative() {
        let html = r#"<div class="box">A</div>"#;
        let css = r#".box { position: relative; top: 20px; left: 30px; width: 50px; height: 50px; background: blue; }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let a = &els[0];
        
        // relative: normal position + offset
        assert_eq!(a.x, 30.0, "x should be 30 (left offset)");
        assert_eq!(a.y, 20.0, "y should be 20 (top offset)");
    }
    
    #[test]
    fn test_transform() {
        let html = r#"<div class="box">A</div>"#;
        let css = r#".box { width: 50px; height: 50px; background: blue; transform: translateX(10px) translateY(20px) rotate(45deg) scale(1.5); }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let a = &els[0];
        
        assert_eq!(a.transform.translate[0], 10.0, "translateX should be 10");
        assert_eq!(a.transform.translate[1], 20.0, "translateY should be 20");
        assert_eq!(a.transform.rotate[2], 45.0, "rotateZ should be 45");
        assert_eq!(a.transform.scale[0], 1.5, "scaleX should be 1.5");
        assert_eq!(a.transform.scale[1], 1.5, "scaleY should be 1.5");
    }
    
    #[test]
    fn test_animation() {
        let html = r#"<div class="box">A</div>"#;
        let css = r#"
            @keyframes fadeIn {
                0% { opacity: 0; }
                100% { opacity: 1; }
            }
            .box { 
                width: 50px; height: 50px; background: blue; 
                animation: fadeIn 2s ease-in-out infinite;
            }
        "#;
        let els = process(html, css, 400.0, 300.0);
        
        let a = &els[0];
        assert!(a.animation.is_some(), "should have animation");
        
        let anim = a.animation.as_ref().unwrap();
        assert_eq!(anim.name, "fadeIn");
        assert_eq!(anim.duration, 2.0);
        assert!(anim.iteration.is_infinite(), "iteration should be infinite");
        assert_eq!(anim.timing, "ease-in-out");
        assert_eq!(anim.keyframes.len(), 2);
        
        // keyframe 0%
        assert_eq!(anim.keyframes[0].percent, 0.0);
        assert_eq!(anim.keyframes[0].opacity, Some(0.0));
        
        // keyframe 100%
        assert_eq!(anim.keyframes[1].percent, 1.0);
        assert_eq!(anim.keyframes[1].opacity, Some(1.0));
    }
    
    #[test]
    fn test_events() {
        let html = r#"<div class="btn" onclick="handleClick()">Click me</div>"#;
        let css = r#".btn { width: 100px; height: 40px; background: blue; cursor: pointer; }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let btn = &els[0];
        
        assert!(btn.interactive, "button should be interactive");
        assert_eq!(btn.cursor, "pointer");
        assert_eq!(btn.events.click, Some("handleClick()".to_string()));
    }
    
    #[test]
    fn test_data_action() {
        let html = r#"<div class="btn" data-action="navigate('home')">Home</div>"#;
        let css = r#".btn { width: 100px; height: 40px; background: green; }"#;
        let els = process(html, css, 400.0, 300.0);
        
        let btn = &els[0];
        
        assert!(btn.interactive, "button should be interactive");
        assert_eq!(btn.events.click, Some("navigate('home')".to_string()));
    }
}