verter_core 0.0.1-beta.1

Vue 3 SFC compiler - transforms Vue Single File Components to render functions with TypeScript support
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
//! Raw template data extracted during compilation.
//!
//! These are core-native types with no dependency on `verter_analysis`.
//! `verter_host` converts them into `verter_analysis::TemplateAnalysisSnapshot`.

use crate::ast::types::{AstNodeKind, ElementNode, TemplateAst};
use crate::common::Span;
use crate::template::code_gen::binding::BindingType;
use crate::template::oxc::types::{OxcNodeData, OxcParsedAst};
use crate::types::NodeId;
use rustc_hash::FxHashMap;

/// Raw template data extracted during compilation.
/// `verter_host` converts this to `verter_analysis::TemplateAnalysisSnapshot`.
#[derive(Debug, Default)]
pub struct RawTemplateData {
    pub components: Vec<RawComponentUsage>,
    pub binding_occurrences: Vec<RawBindingOccurrence>,
    pub elements: Vec<RawElementData>,
    pub slot_definitions: Vec<RawSlotDef>,
    pub template_refs: Vec<RawTemplateRef>,
    pub event_handlers: Vec<RawEventHandler>,
    pub v_for_directives: Vec<RawVForData>,
    pub v_model_directives: Vec<RawVModelData>,
    pub if_chains: Vec<RawIfChain>,
    pub comment_directives: Vec<RawCommentDirective>,
    pub max_nesting_depth: u16,
}

/// A component usage in the template.
#[derive(Debug, Clone)]
pub struct RawComponentUsage {
    pub tag_name: String,
    pub is_dynamic: bool,
    pub props: Vec<RawPropData>,
    pub has_spread: bool,
    pub slots_used: Vec<String>,
    /// Static class names from `class="foo bar"`.
    pub static_classes: Vec<String>,
    /// Whether `:class="..."` is present.
    pub has_dynamic_class: bool,
    /// Raw `:class` expression text (for dynamic class name extraction by verter_host).
    pub dynamic_class_expr: Option<String>,
    pub span: Span,
}

/// A single prop passed to a component or element.
#[derive(Debug, Clone)]
pub struct RawPropData {
    pub name: String,
    pub is_bound: bool,
    pub expression: Option<String>,
    pub referenced_bindings: Vec<String>,
    /// Whether all referenced bindings resolve to static (const) types.
    /// `None` = unknown (parse error, complex expression).
    pub all_bindings_static: Option<bool>,
    pub from_spread: bool,
    /// Byte span of the prop attribute in the SFC source.
    pub span: Span,
    /// Byte span of just the prop name (e.g., `bar` in `:bar="val"`).
    /// For bound props, covers the directive argument; for static props, covers
    /// the attribute name up to `=`.
    pub name_span: Span,
    /// True when this is a same-name shorthand (`:bar` with no expression,
    /// equivalent to `:bar="bar"`).
    pub is_same_name_shorthand: bool,
}

/// A script binding referenced at a specific position in the template.
#[derive(Debug, Clone)]
pub struct RawBindingOccurrence {
    pub name: String,
    pub span: Span,
    /// Whether this binding exists in the script bindings map.
    pub is_in_bindings_map: bool,
    /// Usage kind: 0=interpolation, 1=directive, 2=event, 3=component, 4=ref, 5=iterator
    pub usage_kind: u8,
}

/// A text or interpolation segment within an element's content.
#[derive(Debug, Clone)]
pub enum RawTextSegment {
    /// Literal text.
    Text { span: Span, is_entity: bool },
    /// Interpolation expression (e.g., `{{ count }}`).
    Interpolation {
        /// Full span including `{{ }}` delimiters.
        span: Span,
        /// Inner expression span (excludes `{{ }}` and whitespace).
        expression_span: Span,
    },
}

/// Raw element data for linter/analysis.
#[derive(Debug, Clone)]
pub struct RawElementData {
    pub tag: String,
    pub is_component: bool,
    pub is_self_closing: bool,
    pub has_v_if: bool,
    pub has_v_else: bool,
    pub has_v_else_if: bool,
    pub v_if_condition: Option<String>,
    pub has_v_show: bool,
    pub has_v_html: bool,
    pub has_v_text: bool,
    /// Whether this element has non-whitespace text or interpolation children.
    pub has_text_content: bool,
    /// Whether this element has non-whitespace literal text children (NOT interpolation).
    pub has_bare_text: bool,
    /// Whether this element has direct child elements (non-text, non-comment children).
    pub has_element_children: bool,
    pub nesting_depth: u16,
    pub parent_tag: Option<String>,
    /// Index of the parent element in `RawTemplateData::elements`. `None` for root elements.
    pub parent_index: Option<u32>,
    pub span: Span,
    /// Byte offset end of the opening tag only (past the `>`).
    pub tag_span_end: u32,
    /// Byte offset of the `<` in the closing tag (or same as `tag_span_end` for self-closing).
    pub content_end: u32,
    pub attributes: Vec<RawAttributeData>,
    pub directives: Vec<RawDirectiveData>,
    /// Index into `RawTemplateData::v_for_directives` if this element has v-for.
    pub v_for_idx: Option<usize>,
    /// Index into `RawTemplateData::v_model_directives` if this element has v-model.
    pub v_model_idx: Option<usize>,
    /// Ordered text + interpolation children (excludes element/comment children).
    pub text_children: Vec<RawTextSegment>,
}

/// A static or dynamic attribute on an element (non-directive).
#[derive(Debug, Clone)]
pub struct RawAttributeData {
    pub name: String,
    pub value: Option<String>,
    pub is_dynamic: bool,
    pub span: Span,
    /// Byte offset end of the attribute name.
    pub name_end: u32,
    /// Inner value span (excludes quotes). `None` for boolean attributes.
    pub value_span: Option<Span>,
}

/// A directive on an element.
#[derive(Debug, Clone)]
pub struct RawDirectiveData {
    /// Normalized directive name: `"on"`, `"bind"`, `"if"`, `"for"`, `"model"`, etc.
    pub name: String,
    /// Raw directive as written in source: `"@click"`, `":class"`, `"v-if"`, etc.
    pub raw_name: String,
    pub argument: Option<String>,
    pub modifiers: Vec<String>,
    pub expression: Option<String>,
    pub span: Span,
    /// Byte offset end of the directive name (e.g., end of `v-show` or `@` or `:`).
    pub name_end: u32,
    /// Argument span (e.g., `click` in `@click`).
    pub arg_span: Option<Span>,
    /// Inner expression/value span (excludes quotes).
    pub expression_span: Option<Span>,
    /// Modifier spans (e.g., `stop`, `prevent` in `@click.stop.prevent`).
    pub modifier_spans: Vec<Span>,
}

/// A slot defined in this component's template.
#[derive(Debug, Clone)]
pub struct RawSlotDef {
    pub name: String,
    pub has_bindings: bool,
    /// Prop names from `:prop` bindings on the `<slot>` element.
    pub binding_names: Vec<String>,
    /// Expression text for each binding (parallel to `binding_names`).
    /// E.g. for `:item="row"`, the expression is `"row"`.
    /// For shorthand `:item`, the expression equals the arg name `"item"`.
    pub binding_expressions: Vec<String>,
    /// SFC-absolute spans of each binding's value expression (parallel to `binding_names`).
    pub binding_value_spans: Vec<Span>,
    /// Whether the `<slot>` element has fallback (default) content children.
    pub has_fallback_content: bool,
    pub span: Span,
}

/// A template ref attribute.
#[derive(Debug, Clone)]
pub struct RawTemplateRef {
    pub name: String,
    pub is_dynamic: bool,
    pub target_tag: String,
    pub span: Span,
}

/// An event handler in the template.
#[derive(Debug, Clone)]
pub struct RawEventHandler {
    pub event_name: String,
    pub handler_expression: Option<String>,
    pub is_inline: bool,
    /// The tag name of the element this handler is on.
    pub target_tag: String,
    pub span: Span,
}

/// v-for directive data.
#[derive(Debug, Clone)]
pub struct RawVForData {
    pub variable: String,
    pub index: Option<String>,
    pub iterable: String,
    pub has_key: bool,
    pub key_expression: Option<String>,
    pub key_uses_index: bool,
    pub span: Span,
}

/// v-model directive data.
#[derive(Debug, Clone)]
pub struct RawVModelData {
    pub binding_name: String,
    pub modifiers: Vec<String>,
    pub target_is_component: bool,
    pub target_tag: String,
    pub span: Span,
}

/// A v-if/v-else-if chain.
#[derive(Debug, Clone)]
pub struct RawIfChain {
    pub conditions: Vec<(String, u32, u32)>,
}

/// A comment directive (e.g., `<!-- @verter:disable no-v-html -->`).
#[derive(Debug, Clone)]
pub struct RawCommentDirective {
    pub kind: u8, // 0=disable, 1=disable-next-line, 2=enable, 3=todo, 4=fixme, 5=deprecated, 6=ignore-start, 7=ignore-end, 8=level
    pub rule_or_message: Option<String>,
    pub span: Span,
    pub affects_next_line: bool,
}

// ── Extraction ────────────────────────────────────────────────────

/// Immutable context for template data extraction.
struct ExtractCtx<'a> {
    ast: &'a TemplateAst,
    oxc_ast: &'a OxcParsedAst<'a>,
    source: &'a str,
    bindings: &'a FxHashMap<&'a str, BindingType>,
}

/// Extract raw template data from a compiled template AST.
///
/// Called after script codegen (bindings available) and after OXC expression
/// parsing, but independent of the template codegen backend (VDOM/Vapor).
pub fn extract_raw_template_data(
    ast: &TemplateAst,
    oxc_ast: &OxcParsedAst<'_>,
    source: &str,
    bindings: &FxHashMap<&str, BindingType>,
) -> RawTemplateData {
    let mut data = RawTemplateData::default();
    let mut max_depth: u16 = 0;
    let ctx = ExtractCtx {
        ast,
        oxc_ast,
        source,
        bindings,
    };

    // Track v-if chains: when we see v-if, start a new chain.
    // v-else-if/v-else extend the current chain.
    let mut current_if_chain: Option<RawIfChain> = None;

    // Walk the root children
    if let Some(ref content) = ast.root.content {
        for &child_id in &content.children {
            walk_node_for_extraction(
                &ctx,
                child_id,
                0, // depth
                None,
                None, // parent_element_index
                &mut data,
                &mut max_depth,
                &mut current_if_chain,
            );
        }
    }

    // Flush any pending if-chain
    if let Some(chain) = current_if_chain.take() {
        if chain.conditions.len() > 1 {
            data.if_chains.push(chain);
        }
    }

    data.max_nesting_depth = max_depth;
    data
}

#[allow(clippy::too_many_arguments)]
fn walk_node_for_extraction(
    ctx: &ExtractCtx<'_>,
    node_id: NodeId,
    depth: u16,
    parent_tag: Option<&str>,
    parent_element_index: Option<u32>,
    data: &mut RawTemplateData,
    max_depth: &mut u16,
    current_if_chain: &mut Option<RawIfChain>,
) {
    let node = &ctx.ast.nodes[node_id.0];
    let oxc_data = &ctx.oxc_ast.data[node_id.0];

    match &node.kind {
        AstNodeKind::Element(el) => {
            let current_depth = depth + 1;
            if current_depth > *max_depth {
                *max_depth = current_depth;
            }

            let tag_name = extract_tag_name(el, ctx.source);
            let span_start = el.tag_open.start;
            let span_end = el
                .tag_close
                .as_ref()
                .map(|tc| tc.end)
                .unwrap_or(el.tag_open.end);
            let tag_span_end = el.tag_open.end;

            let this_element_index = data.elements.len() as u32;
            extract_element_data(
                ctx.ast,
                el,
                &tag_name,
                depth,
                parent_tag,
                parent_element_index,
                span_start,
                span_end,
                tag_span_end,
                ctx.source,
                data,
            );
            handle_if_chain(el, ctx.source, span_start, span_end, current_if_chain, data);

            if el.tag_type.is_component() {
                extract_component_usage(ctx, el, oxc_data, &tag_name, span_start, span_end, data);
            }

            if el.tag_type.is_slot_outlet() {
                extract_slot_def(el, ctx.source, span_start, span_end, data);
            }

            // Static ref is in v_ref, dynamic :ref is in props as v-bind
            if el.v_ref.is_some()
                || el.prop_flag.has(crate::ast::types::PropFlags::HasRef)
                || el
                    .prop_flag
                    .has(crate::ast::types::PropFlags::HasDynamicBinding)
            {
                extract_template_ref(el, ctx.source, &tag_name, span_start, span_end, data);
            }

            if el
                .prop_flag
                .has(crate::ast::types::PropFlags::HasEventListener)
            {
                extract_event_handlers(el, ctx.source, &tag_name, span_start, span_end, data);
            }

            if let Some(ref v_for_prop) = el.v_for {
                extract_v_for(
                    el, v_for_prop, oxc_data, ctx.source, span_start, span_end, data,
                );
                if let Some(elem) = data.elements.last_mut() {
                    elem.v_for_idx = Some(data.v_for_directives.len() - 1);
                }
            }

            if el.prop_flag.has(crate::ast::types::PropFlags::HasModel) {
                extract_v_model(el, ctx.source, &tag_name, span_start, span_end, data);
                if let Some(elem) = data.elements.last_mut() {
                    elem.v_model_idx = Some(data.v_model_directives.len() - 1);
                }
            }

            extract_binding_occurrences(oxc_data, ctx.bindings, data);

            // Recurse into children
            if let Some(ref content) = el.content {
                let mut child_if_chain: Option<RawIfChain> = None;
                for &child_id in &content.children {
                    walk_node_for_extraction(
                        ctx,
                        child_id,
                        current_depth,
                        Some(&tag_name),
                        Some(this_element_index),
                        data,
                        max_depth,
                        &mut child_if_chain,
                    );
                }
                if let Some(chain) = child_if_chain.take() {
                    if chain.conditions.len() > 1 {
                        data.if_chains.push(chain);
                    }
                }
            }
        }
        AstNodeKind::Interpolation(_interp) => {
            flush_if_chain(current_if_chain, data);

            if let OxcNodeData::Interpolation(ref oxc_expr) = oxc_data {
                if let Some(ref result) = oxc_expr.bindings {
                    for binding in &result.bindings {
                        if !binding.ignore {
                            data.binding_occurrences.push(RawBindingOccurrence {
                                name: binding.name.to_string(),
                                span: Span::new(
                                    binding.pos,
                                    binding.pos + binding.name.len() as u32,
                                ),
                                is_in_bindings_map: ctx.bindings.contains_key(binding.name),
                                usage_kind: 0, // interpolation
                            });
                        }
                    }
                }
            }
        }
        AstNodeKind::Comment(comment) => {
            let content_str =
                &ctx.source[comment.content_start as usize..comment.content_end as usize];
            let trimmed = content_str.trim();
            if let Some(directive) = parse_comment_directive(trimmed, comment.start, comment.end) {
                data.comment_directives.push(directive);
            }
        }
        AstNodeKind::Text(_) => {
            flush_if_chain(current_if_chain, data);
        }
    }
}

/// Check whether an element has at least one text child with non-whitespace content.
/// Whitespace-only text nodes (indentation, newlines) are not considered "text content"
/// for lint purposes, matching Vue's whitespace condensation behavior.
fn has_non_whitespace_text(ast: &TemplateAst, el: &ElementNode, source: &str) -> bool {
    if !el
        .children_flag
        .has(crate::ast::types::ChildrenFlags::HasText)
    {
        return false;
    }
    let Some(ref content) = el.content else {
        return false;
    };
    for &child_id in &content.children {
        if let AstNodeKind::Text(ref text) = ast.nodes[child_id.0].kind {
            let s = text.start as usize;
            let e = text.end as usize;
            if s < e && e <= source.len() {
                let text_content = &source[s..e];
                if !text_content.trim().is_empty() {
                    return true;
                }
            }
        }
    }
    false
}

/// Extract text and interpolation children from an element's content.
fn extract_text_children(ast: &TemplateAst, el: &ElementNode) -> Vec<RawTextSegment> {
    let Some(ref content) = el.content else {
        return Vec::new();
    };
    let mut segments = Vec::new();
    for &child_id in &content.children {
        match &ast.nodes[child_id.0].kind {
            AstNodeKind::Text(text) => {
                segments.push(RawTextSegment::Text {
                    span: Span::new(text.start, text.end),
                    is_entity: text.is_entity,
                });
            }
            AstNodeKind::Interpolation(interp) => {
                segments.push(RawTextSegment::Interpolation {
                    span: Span::new(interp.start, interp.end),
                    expression_span: Span::new(interp.inner_start, interp.inner_end),
                });
            }
            _ => {} // Skip element/comment children
        }
    }
    segments
}

fn extract_tag_name(el: &ElementNode, source: &str) -> String {
    let start = el.tag_open.start as usize + 1; // skip '<'
    let end = el.tag_open.name_end as usize;
    source[start..end].to_string()
}

#[allow(clippy::too_many_arguments)]
fn extract_element_data(
    ast: &TemplateAst,
    el: &ElementNode,
    tag_name: &str,
    depth: u16,
    parent_tag: Option<&str>,
    parent_element_index: Option<u32>,
    span_start: u32,
    span_end: u32,
    tag_span_end: u32,
    source: &str,
    data: &mut RawTemplateData,
) {
    use crate::ast::types::ElementNodeConditionKind;

    let mut attributes = Vec::new();
    let mut directives = Vec::new();

    // Extract from el.props (non-cached directives and static attributes)
    for prop in &el.props {
        let prop_end = prop_span_end(prop, source);
        if prop.is_directive {
            let raw_name = &source[prop.start as usize..prop.name_end as usize];
            let (name, normalized_raw) = normalize_directive_name(raw_name);
            let argument = prop
                .arg_start
                .zip(prop.arg_end)
                .map(|(s, e)| source[s as usize..e as usize].to_string());
            let modifiers: Vec<String> = prop
                .modifiers
                .iter()
                .map(|m| m.slice(source).to_string())
                .collect();
            let expression = prop
                .value_start
                .zip(prop.value_end)
                .map(|(s, e)| source[s as usize..e as usize].to_string());
            let expression_span = prop
                .value_start
                .zip(prop.value_end)
                .map(|(s, e)| Span::new(s, e));
            let arg_span = prop
                .arg_start
                .zip(prop.arg_end)
                .map(|(s, e)| Span::new(s, e));
            let modifier_spans: Vec<Span> = prop.modifiers.iter().copied().collect();
            directives.push(RawDirectiveData {
                name,
                raw_name: normalized_raw,
                argument,
                modifiers,
                expression,
                span: Span::new(prop.start, prop_end),
                name_end: prop.name_end,
                arg_span,
                expression_span,
                modifier_spans,
            });
        } else {
            let name = source[prop.start as usize..prop.name_end as usize].to_string();
            let value = prop
                .value_start
                .zip(prop.value_end)
                .map(|(s, e)| source[s as usize..e as usize].to_string());
            let value_span = prop
                .value_start
                .zip(prop.value_end)
                .map(|(s, e)| Span::new(s, e));
            attributes.push(RawAttributeData {
                name,
                value,
                is_dynamic: false,
                span: Span::new(prop.start, prop_end),
                name_end: prop.name_end,
                value_span,
            });
        }
    }

    // Extract cached directives (not in el.props)
    if let Some(ref cond) = el.v_condition {
        let expression = cond
            .prop
            .value_start
            .zip(cond.prop.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());
        let (name, raw_name) = match cond.kind {
            ElementNodeConditionKind::If => ("if".to_string(), "v-if".to_string()),
            ElementNodeConditionKind::ElseIf => ("else-if".to_string(), "v-else-if".to_string()),
            ElementNodeConditionKind::Else => ("else".to_string(), "v-else".to_string()),
        };
        let cond_expression_span = cond
            .prop
            .value_start
            .zip(cond.prop.value_end)
            .map(|(s, e)| Span::new(s, e));
        directives.push(RawDirectiveData {
            name,
            raw_name,
            argument: None,
            modifiers: Vec::new(),
            expression,
            span: Span::new(cond.prop.start, prop_span_end(&cond.prop, source)),
            name_end: cond.prop.name_end,
            arg_span: None,
            expression_span: cond_expression_span,
            modifier_spans: Vec::new(),
        });
    }

    if let Some(ref v_for) = el.v_for {
        let expression = v_for
            .value_start
            .zip(v_for.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());
        let vfor_expression_span = v_for
            .value_start
            .zip(v_for.value_end)
            .map(|(s, e)| Span::new(s, e));
        directives.push(RawDirectiveData {
            name: "for".to_string(),
            raw_name: "v-for".to_string(),
            argument: None,
            modifiers: Vec::new(),
            expression,
            span: Span::new(v_for.start, prop_span_end(v_for, source)),
            name_end: v_for.name_end,
            arg_span: None,
            expression_span: vfor_expression_span,
            modifier_spans: Vec::new(),
        });
    }

    if let Some(ref v_slot) = el.v_slot {
        let raw_name_str = &source[v_slot.start as usize..v_slot.name_end as usize];
        let argument = v_slot
            .arg_start
            .zip(v_slot.arg_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());
        let expression = v_slot
            .value_start
            .zip(v_slot.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());
        let slot_arg_span = v_slot
            .arg_start
            .zip(v_slot.arg_end)
            .map(|(s, e)| Span::new(s, e));
        let slot_expression_span = v_slot
            .value_start
            .zip(v_slot.value_end)
            .map(|(s, e)| Span::new(s, e));
        directives.push(RawDirectiveData {
            name: "slot".to_string(),
            raw_name: raw_name_str.to_string(),
            argument,
            modifiers: Vec::new(),
            expression,
            span: Span::new(v_slot.start, prop_span_end(v_slot, source)),
            name_end: v_slot.name_end,
            arg_span: slot_arg_span,
            expression_span: slot_expression_span,
            modifier_spans: Vec::new(),
        });
    }

    if let Some(ref v_once) = el.v_once {
        directives.push(RawDirectiveData {
            name: "once".to_string(),
            raw_name: "v-once".to_string(),
            argument: None,
            modifiers: Vec::new(),
            expression: None,
            span: Span::new(v_once.start, prop_span_end(v_once, source)),
            name_end: v_once.name_end,
            arg_span: None,
            expression_span: None,
            modifier_spans: Vec::new(),
        });
    }

    if let Some(ref v_ref) = el.v_ref {
        // Static ref="x" — treated as attribute
        let value = v_ref
            .value_start
            .zip(v_ref.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());
        let ref_value_span = v_ref
            .value_start
            .zip(v_ref.value_end)
            .map(|(s, e)| Span::new(s, e));
        attributes.push(RawAttributeData {
            name: "ref".to_string(),
            value,
            is_dynamic: false,
            span: Span::new(v_ref.start, prop_span_end(v_ref, source)),
            name_end: v_ref.name_end,
            value_span: ref_value_span,
        });
    }

    // Compute content_end and text_children
    let content_end = el.content.as_ref().map_or(tag_span_end, |c| c.end);
    let text_children = extract_text_children(ast, el);

    data.elements.push(RawElementData {
        tag: tag_name.to_string(),
        is_component: el.tag_type.is_component(),
        is_self_closing: el.is_self_closing,
        has_v_if: el
            .v_condition
            .as_ref()
            .is_some_and(|c| c.kind == ElementNodeConditionKind::If),
        has_v_else: el
            .v_condition
            .as_ref()
            .is_some_and(|c| c.kind == ElementNodeConditionKind::Else),
        has_v_else_if: el
            .v_condition
            .as_ref()
            .is_some_and(|c| c.kind == ElementNodeConditionKind::ElseIf),
        v_if_condition: el.v_condition.as_ref().and_then(|c| {
            if c.kind == ElementNodeConditionKind::Else {
                return None;
            }
            c.prop
                .value_start
                .zip(c.prop.value_end)
                .and_then(|(s, e)| source.get(s as usize..e as usize))
                .map(|s| s.to_string())
        }),
        has_v_show: el.prop_flag.has(crate::ast::types::PropFlags::HasShow),
        has_v_html: el.prop_flag.has(crate::ast::types::PropFlags::HasVHtml),
        has_v_text: el.prop_flag.has(crate::ast::types::PropFlags::HasVText),
        has_bare_text: has_non_whitespace_text(ast, el, source),
        has_text_content: has_non_whitespace_text(ast, el, source)
            || el
                .children_flag
                .has(crate::ast::types::ChildrenFlags::HasInterpolation),
        has_element_children: el
            .children_flag
            .has(crate::ast::types::ChildrenFlags::HasElement),
        nesting_depth: depth,
        parent_tag: parent_tag.map(|s| s.to_string()),
        parent_index: parent_element_index,
        span: Span::new(span_start, span_end),
        tag_span_end,
        content_end,
        attributes,
        directives,
        v_for_idx: None,
        v_model_idx: None,
        text_children,
    });
}

/// Compute the end position of a prop span.
fn prop_span_end(prop: &crate::types::NodeProp, source: &str) -> u32 {
    // value_end is "before the closing quote", so +1 for the quote itself
    if let Some(ve) = prop.value_end {
        // Check if there's a quote character after value_end
        let ve_usize = ve as usize;
        if ve_usize < source.len() {
            let next = source.as_bytes()[ve_usize];
            if next == b'"' || next == b'\'' {
                return ve + 1;
            }
        }
        return ve;
    }
    let mut end = prop.name_end;
    if let Some(ae) = prop.arg_end {
        end = end.max(ae);
    }
    for m in &prop.modifiers {
        end = end.max(m.end);
    }
    end
}

/// Normalize a directive raw name to (canonical_name, raw_name_for_display).
fn normalize_directive_name(raw: &str) -> (String, String) {
    match raw {
        "@" => ("on".to_string(), "@".to_string()),
        ":" => ("bind".to_string(), ":".to_string()),
        "#" => ("slot".to_string(), "#".to_string()),
        _ if raw.starts_with("v-") => {
            let name = raw[2..].to_string();
            (name, raw.to_string())
        }
        _ => (raw.to_string(), raw.to_string()),
    }
}

fn handle_if_chain(
    el: &ElementNode,
    source: &str,
    span_start: u32,
    span_end: u32,
    current_if_chain: &mut Option<RawIfChain>,
    data: &mut RawTemplateData,
) {
    use crate::ast::types::ElementNodeConditionKind;

    match &el.v_condition {
        Some(cond) => match cond.kind {
            ElementNodeConditionKind::If => {
                // Flush previous chain
                flush_if_chain(current_if_chain, data);
                // Start new chain
                let expr = cond
                    .prop
                    .value_start
                    .zip(cond.prop.value_end)
                    .map(|(s, e)| source[s as usize..e as usize].to_string())
                    .unwrap_or_default();
                *current_if_chain = Some(RawIfChain {
                    conditions: vec![(expr, span_start, span_end)],
                });
            }
            ElementNodeConditionKind::ElseIf => {
                let expr = cond
                    .prop
                    .value_start
                    .zip(cond.prop.value_end)
                    .map(|(s, e)| source[s as usize..e as usize].to_string())
                    .unwrap_or_default();
                if let Some(ref mut chain) = current_if_chain {
                    chain.conditions.push((expr, span_start, span_end));
                }
            }
            ElementNodeConditionKind::Else => {
                if let Some(ref mut chain) = current_if_chain {
                    chain
                        .conditions
                        .push(("".to_string(), span_start, span_end));
                }
                // v-else ends the chain
                flush_if_chain(current_if_chain, data);
            }
        },
        None => {
            // Non-conditional elements break the if-chain
            flush_if_chain(current_if_chain, data);
        }
    }
}

fn flush_if_chain(current_if_chain: &mut Option<RawIfChain>, data: &mut RawTemplateData) {
    if let Some(chain) = current_if_chain.take() {
        if chain.conditions.len() > 1 {
            data.if_chains.push(chain);
        }
    }
}

fn extract_component_usage(
    ctx: &ExtractCtx<'_>,
    el: &ElementNode,
    oxc_data: &OxcNodeData<'_>,
    tag_name: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    let source = ctx.source;
    let bindings = ctx.bindings;
    let is_dynamic = tag_name == "component";
    let has_spread = el.has_spread();

    let mut props = Vec::new();
    let mut slots_used = Vec::new();

    let oxc_el = match oxc_data {
        OxcNodeData::Element(ref el) => Some(el.as_ref()),
        _ => None,
    };

    for (i, prop) in el.props.iter().enumerate() {
        let base = &source[prop.start as usize..prop.name_end as usize];
        let arg = prop
            .arg_start
            .zip(prop.arg_end)
            .map(|(s, e)| &source[s as usize..e as usize]);

        if prop.is_directive {
            // Skip structural directives (v-if, v-else, v-else-if, v-for are cached, not in props,
            // but v-slot/# may still be here)
            match base {
                "v-if" | "v-else-if" | "v-else" | "v-for" => continue,
                "v-slot" | "#" => {
                    let slot_name = arg.unwrap_or("default");
                    let slot_name = if slot_name.is_empty() {
                        "default".to_string()
                    } else {
                        slot_name.to_string()
                    };
                    if !slots_used.contains(&slot_name) {
                        slots_used.push(slot_name);
                    }
                    continue;
                }
                "@" | "v-on" => continue, // Event handlers — skip
                ":" | "v-bind" => {
                    // Check for key (skip), ref (skip), spread (skip)
                    match arg {
                        Some("key") => continue,
                        Some("ref") => continue, // :ref is not a prop — it's a template ref
                        None => continue,        // v-bind spread — already captured by has_spread
                        _ => {}                  // Regular bound prop — fall through
                    }
                }
                _ => continue, // Other directives (v-model, v-show, etc.) — skip
            }
        } else {
            // Non-directive attribute — skip "key" (static key)
            if base == "key" {
                continue;
            }
        }

        // At this point we have either:
        // - A non-directive attribute (base = prop name)
        // - A v-bind/:  directive with an arg (the prop name is in arg)
        let is_bound = prop.is_directive;
        let actual_name = if is_bound {
            arg.unwrap_or(base).to_string()
        } else {
            base.to_string()
        };

        let expression = prop
            .value_start
            .zip(prop.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());

        // Extract referenced bindings from OXC data
        let mut referenced = Vec::new();
        let mut all_static = if is_bound { Some(true) } else { None };

        if is_bound {
            if let Some(oxc_el) = oxc_el {
                for oxc_prop in &oxc_el.props {
                    if oxc_prop.prop_index == i {
                        if let Some(ref exp) = oxc_prop.exp {
                            if let Some(ref result) = exp.bindings {
                                for b in &result.bindings {
                                    if !b.ignore {
                                        referenced.push(b.name.to_string());
                                        if let Some(ref mut is_static) = all_static {
                                            let bt = bindings.get(b.name);
                                            let binding_is_static = bt.is_some_and(|bt| {
                                                matches!(
                                                    bt.reactivity_level(),
                                                    crate::template::code_gen::binding::ReactivityLevel::Static
                                                )
                                            });
                                            if !binding_is_static {
                                                *is_static = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        // Compute the full span of this prop attribute.
        // span_start = prop.start (the beginning of the attribute name or directive prefix)
        // span_end = past the closing quote of the value, or name_end if no value
        let prop_span_end = prop
            .value_end
            .map(|ve| ve + 1) // +1 to skip past the closing quote
            .unwrap_or(prop.name_end);

        // Compute name_span: for bound props use the directive argument span,
        // for static props use start..name_end (the attribute name before `=`).
        let name_span = if is_bound {
            prop.arg_start
                .zip(prop.arg_end)
                .map(|(s, e)| Span::new(s, e))
                .unwrap_or(Span::new(prop.start, prop.name_end))
        } else {
            Span::new(prop.start, prop.name_end)
        };

        // Same-name shorthand: `:bar` with no expression (spread props are handled separately)
        let is_same_name_shorthand = is_bound && expression.is_none();

        props.push(RawPropData {
            name: actual_name,
            is_bound,
            expression,
            referenced_bindings: referenced,
            all_bindings_static: all_static,
            from_spread: false,
            span: Span::new(prop.start, prop_span_end),
            name_span,
            is_same_name_shorthand,
        });
    }

    // Add a spread prop entry if v-bind spread exists
    if has_spread {
        props.push(RawPropData {
            name: String::new(),
            is_bound: true,
            expression: None,
            referenced_bindings: Vec::new(),
            all_bindings_static: None,
            from_spread: true,
            span: Span::new(0, 0),
            name_span: Span::new(0, 0),
            is_same_name_shorthand: false,
        });
    }

    // Extract static classes, dynamic class flag, and dynamic class expression from attributes
    let mut static_classes = Vec::new();
    let mut has_dynamic_class = false;
    let mut dynamic_class_expr: Option<String> = None;
    for prop in el.props.iter() {
        let base = &source[prop.start as usize..prop.name_end as usize];
        let arg = prop
            .arg_start
            .zip(prop.arg_end)
            .map(|(s, e)| &source[s as usize..e as usize]);
        if !prop.is_directive && base == "class" {
            // Static class attribute: class="foo bar"
            if let Some((vs, ve)) = prop.value_start.zip(prop.value_end) {
                let value = &source[vs as usize..ve as usize];
                for cls in value.split_whitespace() {
                    if !cls.is_empty() {
                        static_classes.push(cls.to_string());
                    }
                }
            }
        } else if prop.is_directive {
            // Check for :class or v-bind:class
            let is_class_binding = if base == ":" || base == "v-bind" {
                arg == Some("class")
            } else {
                base == ":class"
            };
            if is_class_binding {
                has_dynamic_class = true;
                // Store the expression value for dynamic class name extraction
                if let Some((vs, ve)) = prop.value_start.zip(prop.value_end) {
                    dynamic_class_expr = Some(source[vs as usize..ve as usize].to_string());
                }
            }
        }
    }

    data.components.push(RawComponentUsage {
        tag_name: tag_name.to_string(),
        is_dynamic,
        props,
        has_spread,
        slots_used,
        static_classes,
        has_dynamic_class,
        dynamic_class_expr,
        span: Span::new(span_start, span_end),
    });
}

fn extract_slot_def(
    el: &ElementNode,
    source: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    // Find the "name" attribute on the <slot> element
    let mut name = "default".to_string();
    let mut has_bindings = false;
    let mut binding_names = Vec::new();
    let mut binding_expressions = Vec::new();
    let mut binding_value_spans = Vec::new();

    for prop in &el.props {
        if prop.is_directive {
            let base = &source[prop.start as usize..prop.name_end as usize];
            // Slot bindings: v-bind / : with an arg (scoped slots pass data via v-bind)
            if base == ":" || base == "v-bind" {
                let arg = prop
                    .arg_start
                    .zip(prop.arg_end)
                    .map(|(s, e)| &source[s as usize..e as usize]);
                if let Some(arg_name) = arg {
                    has_bindings = true;
                    binding_names.push(arg_name.to_string());
                    // Capture expression text and span
                    if let Some((vs, ve)) = prop.value_start.zip(prop.value_end) {
                        binding_expressions.push(source[vs as usize..ve as usize].to_string());
                        binding_value_spans.push(Span::new(vs, ve));
                    } else {
                        // Shorthand: :item → expression is the arg name itself
                        let (as_, ae) = (prop.arg_start.unwrap(), prop.arg_end.unwrap());
                        binding_expressions.push(arg_name.to_string());
                        binding_value_spans.push(Span::new(as_, ae));
                    }
                }
            }
        } else {
            let attr_name = &source[prop.start as usize..prop.name_end as usize];
            if attr_name == "name" {
                if let Some((s, e)) = prop.value_start.zip(prop.value_end) {
                    name = source[s as usize..e as usize].to_string();
                }
            }
        }
    }

    let has_fallback_content = el
        .content
        .as_ref()
        .map(|c| !c.children.is_empty())
        .unwrap_or(false);

    data.slot_definitions.push(RawSlotDef {
        name,
        has_bindings,
        binding_names,
        binding_expressions,
        binding_value_spans,
        has_fallback_content,
        span: Span::new(span_start, span_end),
    });
}

fn extract_template_ref(
    el: &ElementNode,
    source: &str,
    tag_name: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    // Static ref="foo" is cached in el.v_ref (taken out of props by the parser).
    if let Some(ref v_ref) = el.v_ref {
        let name = v_ref
            .value_start
            .zip(v_ref.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string())
            .unwrap_or_default();
        data.template_refs.push(RawTemplateRef {
            name,
            is_dynamic: false,
            target_tag: tag_name.to_string(),
            span: Span::new(span_start, span_end),
        });
        return;
    }

    // Dynamic :ref="expr" or v-bind:ref="expr" — stored as a directive prop
    // where the base name is ":" or "v-bind" and the arg is "ref".
    for prop in &el.props {
        if !prop.is_directive {
            continue;
        }
        let base = &source[prop.start as usize..prop.name_end as usize];
        if base != ":" && base != "v-bind" {
            continue;
        }
        if let (Some(arg_s), Some(arg_e)) = (prop.arg_start, prop.arg_end) {
            let arg = &source[arg_s as usize..arg_e as usize];
            if arg == "ref" {
                let name = prop
                    .value_start
                    .zip(prop.value_end)
                    .map(|(s, e)| source[s as usize..e as usize].to_string())
                    .unwrap_or_default();
                data.template_refs.push(RawTemplateRef {
                    name,
                    is_dynamic: true,
                    target_tag: tag_name.to_string(),
                    span: Span::new(span_start, span_end),
                });
                return;
            }
        }
    }
}

fn extract_event_handlers(
    el: &ElementNode,
    source: &str,
    tag_name: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    for prop in &el.props {
        if !prop.is_directive {
            continue;
        }
        let base = &source[prop.start as usize..prop.name_end as usize];
        // Event handlers are directives with base "@" or "v-on" and an arg.
        if base != "@" && base != "v-on" {
            continue;
        }
        // The event name is in arg_start..arg_end (e.g., "click" for @click).
        let event_name = if let (Some(arg_s), Some(arg_e)) = (prop.arg_start, prop.arg_end) {
            &source[arg_s as usize..arg_e as usize]
        } else {
            continue; // v-on without arg is a spread, not an event handler
        };

        let handler_expr = prop
            .value_start
            .zip(prop.value_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string());

        let is_inline = handler_expr.as_ref().is_some_and(|e| !is_simple_handler(e));

        data.event_handlers.push(RawEventHandler {
            event_name: event_name.to_string(),
            handler_expression: handler_expr,
            is_inline,
            target_tag: tag_name.to_string(),
            span: Span::new(span_start, span_end),
        });
    }
}

/// Check if a handler expression is a simple reference (not inline).
fn is_simple_handler(expr: &str) -> bool {
    let trimmed = expr.trim();
    // Simple: single identifier, or member expression (foo.bar, foo?.bar)
    trimmed
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || b == b'$' || b == b'?')
        && !trimmed.is_empty()
}

fn extract_v_for(
    el: &ElementNode,
    v_for_prop: &crate::types::NodeProp,
    oxc_data: &OxcNodeData<'_>,
    source: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    let oxc_el = match oxc_data {
        OxcNodeData::Element(ref el) => Some(el.as_ref()),
        _ => None,
    };

    // Parse the v-for expression
    let mut variable = String::new();
    let mut index = None;
    let mut iterable = String::new();

    if let Some(oxc_el) = oxc_el {
        if let Some(ref vfor) = oxc_el.v_for {
            // Extract locals (variable, index)
            for (i, local) in vfor.parsed.locals.iter().enumerate() {
                let local_str = local.slice(source);
                if i == 0 {
                    variable = local_str.to_string();
                } else if i == 1 {
                    index = Some(local_str.to_string());
                }
            }
            // First reference is typically the iterable
            if let Some(reference) = vfor.parsed.references.first() {
                iterable = reference.slice(source).to_string();
            }
            // Fallback: literal iterables (arrays, objects, `as const`) have no
            // identifier references. Extract the full iterable text from source.
            if iterable.is_empty() {
                if let Some(ve) = v_for_prop.value_end {
                    let right_start = vfor.parsed.result.right_offset as usize;
                    let right_end = ve as usize;
                    if right_start < right_end && right_end <= source.len() {
                        iterable = source[right_start..right_end].trim().to_string();
                    }
                }
            }
        }
    }

    // Fallback: parse from raw value
    if variable.is_empty() {
        if let Some((s, e)) = v_for_prop.value_start.zip(v_for_prop.value_end) {
            let raw = &source[s as usize..e as usize];
            // Simple parse: "item in items" or "(item, index) in items"
            if let Some(in_pos) = raw.find(" in ").or_else(|| raw.find(" of ")) {
                let left = raw[..in_pos].trim();
                iterable = raw[in_pos + 4..].trim().to_string();
                let left = left.trim_start_matches('(').trim_end_matches(')');
                let mut parts = left.split(',');
                if let Some(v) = parts.next() {
                    variable = v.trim().to_string();
                }
                if let Some(i) = parts.next() {
                    index = Some(i.trim().to_string());
                }
            }
        }
    }

    // Check for :key
    let has_key = el
        .prop_flag
        .has(crate::ast::types::PropFlags::HasDynamicKey);
    let mut key_expression = None;
    let mut key_uses_index = false;

    if has_key {
        for prop in &el.props {
            if !prop.is_directive {
                continue;
            }
            let base = &source[prop.start as usize..prop.name_end as usize];
            if base != ":" && base != "v-bind" {
                continue;
            }
            let arg = prop
                .arg_start
                .zip(prop.arg_end)
                .map(|(s, e)| &source[s as usize..e as usize]);
            if arg == Some("key") {
                if let Some((s, e)) = prop.value_start.zip(prop.value_end) {
                    let kexpr = source[s as usize..e as usize].to_string();
                    if let Some(ref idx) = index {
                        key_uses_index = kexpr.contains(idx.as_str());
                    }
                    key_expression = Some(kexpr);
                }
                break;
            }
        }
    }

    data.v_for_directives.push(RawVForData {
        variable,
        index,
        iterable,
        has_key,
        key_expression,
        key_uses_index,
        span: Span::new(span_start, span_end),
    });
}

fn extract_v_model(
    el: &ElementNode,
    source: &str,
    tag_name: &str,
    span_start: u32,
    span_end: u32,
    data: &mut RawTemplateData,
) {
    for prop in &el.props {
        if !prop.is_directive {
            continue;
        }
        let base = &source[prop.start as usize..prop.name_end as usize];
        if base != "v-model" {
            continue;
        }
        // Custom model name is in the arg (e.g., v-model:title → arg="title")
        let binding_name = prop
            .arg_start
            .zip(prop.arg_end)
            .map(|(s, e)| source[s as usize..e as usize].to_string())
            .unwrap_or_else(|| "modelValue".to_string());

        let modifiers: Vec<String> = prop
            .modifiers
            .iter()
            .map(|m| m.slice(source).to_string())
            .collect();

        data.v_model_directives.push(RawVModelData {
            binding_name,
            modifiers,
            target_is_component: el.tag_type.is_component(),
            target_tag: tag_name.to_string(),
            span: Span::new(span_start, span_end),
        });
        break; // Only one v-model per element
    }
}

fn extract_binding_occurrences(
    oxc_data: &OxcNodeData<'_>,
    bindings: &FxHashMap<&str, BindingType>,
    data: &mut RawTemplateData,
) {
    let oxc_el = match oxc_data {
        OxcNodeData::Element(ref el) => el.as_ref(),
        _ => return,
    };

    // Extract from directive value expressions
    for oxc_prop in &oxc_el.props {
        if let Some(ref exp) = oxc_prop.exp {
            if let Some(ref result) = exp.bindings {
                for b in &result.bindings {
                    if !b.ignore {
                        data.binding_occurrences.push(RawBindingOccurrence {
                            name: b.name.to_string(),
                            span: Span::new(b.pos, b.pos + b.name.len() as u32),
                            is_in_bindings_map: bindings.contains_key(b.name),
                            usage_kind: 1, // directive value
                        });
                    }
                }
            }
        }
    }

    // Extract from v-if condition
    if let Some(ref cond) = oxc_el.condition {
        if let Some(ref result) = cond.bindings {
            for b in &result.bindings {
                if !b.ignore {
                    data.binding_occurrences.push(RawBindingOccurrence {
                        name: b.name.to_string(),
                        span: Span::new(b.pos, b.pos + b.name.len() as u32),
                        is_in_bindings_map: bindings.contains_key(b.name),
                        usage_kind: 1, // directive value
                    });
                }
            }
        }
    }
}

fn parse_comment_directive(content: &str, start: u32, end: u32) -> Option<RawCommentDirective> {
    let trimmed = content.trim();

    let (prefix, rest) = if let Some(r) = trimmed.strip_prefix("@verter:") {
        ("@verter:", r)
    } else {
        return None;
    };
    let _ = prefix;

    let rest = rest.trim();
    let (kind, affects_next_line, rule_or_message) =
        if let Some(r) = rest.strip_prefix("disable-next-line") {
            (1, true, Some(r.trim().to_string()))
        } else if let Some(r) = rest.strip_prefix("disable") {
            (0, false, Some(r.trim().to_string()))
        } else if let Some(r) = rest.strip_prefix("enable") {
            (2, false, Some(r.trim().to_string()))
        } else if let Some(r) = rest.strip_prefix("todo") {
            (3, false, Some(r.trim().to_string()))
        } else if let Some(r) = rest.strip_prefix("fixme") {
            (4, false, Some(r.trim().to_string()))
        } else if let Some(r) = rest.strip_prefix("deprecated") {
            (5, false, Some(r.trim().to_string()))
        } else if rest.starts_with("ignore-start") {
            (6, false, None)
        } else if rest.starts_with("ignore-end") {
            (7, false, None)
        } else if let Some(r) = rest.strip_prefix("level") {
            // @verter:level(warn) or @verter:level(error) or @verter:level(off)
            // Extract the argument inside parens, e.g. "level(warn)" → "warn"
            let arg = r.trim();
            let arg = arg.strip_prefix('(').and_then(|s| s.strip_suffix(')'));
            let msg = arg.map(str::trim).map(|s| s.to_string());
            (8, false, msg)
        } else {
            return None;
        };

    let rule_or_message = rule_or_message.and_then(|s| {
        let s = s.trim();
        if s.is_empty() {
            None
        } else {
            Some(s.to_string())
        }
    });

    Some(RawCommentDirective {
        kind,
        rule_or_message,
        span: Span::new(start, end),
        affects_next_line,
    })
}

#[cfg(test)]
#[path = "template_data_tests.rs"]
mod template_data_tests;