semver-analyzer-ts 0.0.4

TypeScript/JavaScript support for the semver-analyzer
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
//! Source-level profile extraction for the v2 SD pipeline.
//!
//! Extracts a `ComponentSourceProfile` from a React component's `.tsx` source
//! file by combining:
//! - JSX render output analysis (elements, attributes, components)
//! - BEM token structure (from `styles.*` references)
//! - React API usage (createPortal, useContext, forwardRef, memo)
//! - Prop default values (from destructuring patterns)
//! - Children slot position (where `{children}` lands in the JSX tree)
//!
//! All extractions are deterministic — no LLM, no confidence scores.

pub mod bem;
pub mod children_slot;
pub mod clone_element;
pub mod diff;
pub mod managed_attrs;
pub mod prop_defaults;
pub mod prop_style;
pub mod react_api;

use bem::{extract_style_tokens, parse_bem_structure, StyleToken};
use children_slot::{has_children_prop, trace_children_slot_both};
// clone_element detection is done inline during the main AST walk
// (via clone_element::try_extract_clone_element_from_call)
use crate::sd_types::ComponentSourceProfile;
use managed_attrs::extract_managed_attributes;
use prop_defaults::extract_prop_defaults;
use prop_style::extract_prop_style_bindings;
use react_api::detect_react_api_usage;
use std::collections::{BTreeMap, BTreeSet};

use oxc_allocator::Allocator;
use oxc_ast::ast::*;
use oxc_parser::Parser;
use oxc_span::SourceType;

/// Extract a `ComponentSourceProfile` from a component's source file.
///
/// `name` is the component name (e.g., "Dropdown").
/// `file` is the relative path (e.g., "packages/react-core/src/components/Dropdown/Dropdown.tsx").
/// `source` is the full source text of the `.tsx` file.
pub fn extract_profile(name: &str, file: &str, source: &str) -> ComponentSourceProfile {
    let mut profile = ComponentSourceProfile {
        name: name.to_string(),
        file: file.to_string(),
        ..Default::default()
    };

    // ── Single-parse AST extraction ─────────────────────────────────
    // Extracts JSX info, styles import path (BEM block), and interface
    // extends clauses from one OXC parse pass.
    let ast_info = extract_source_info(source, name);

    // 1. JSX render output
    profile.rendered_elements = ast_info
        .element_tags
        .iter()
        .filter(|(tag, _)| tag.starts_with(|c: char| c.is_lowercase()))
        .map(|(k, v)| (k.clone(), *v as u32))
        .collect();
    profile.rendered_components = ast_info
        .element_tags
        .keys()
        .filter(|tag| tag.starts_with(|c: char| c.is_uppercase()))
        .map(|tag| crate::sd_types::RenderedComponent {
            name: tag.clone(),
            conditional: !ast_info.unconditional_tags.contains(tag),
        })
        .collect();
    profile.aria_attributes = ast_info
        .aria_attrs
        .iter()
        .map(|((elem, attr), val)| ((elem.clone(), attr.clone()), val.clone()))
        .collect();
    profile.role_attributes = ast_info.role_attrs.clone();
    profile.data_attributes = ast_info
        .data_attrs
        .iter()
        .map(|((elem, attr), val)| ((elem.clone(), attr.clone()), val.clone()))
        .collect();

    // 2. BEM token analysis — use import-derived block as ground truth
    let style_tokens = extract_style_tokens(source);
    for token in &style_tokens {
        match token {
            StyleToken::ClassToken(name) => {
                profile.css_tokens_used.insert(format!("styles.{name}"));
            }
            StyleToken::Modifier(name) => {
                profile
                    .css_tokens_used
                    .insert(format!("styles.modifiers.{name}"));
            }
        }
    }
    let bem = parse_bem_structure(&style_tokens, ast_info.styles_bem_block.as_deref());
    profile.bem_block = bem.block;
    profile.bem_elements = bem.elements;
    profile.bem_modifiers = bem.modifiers;

    // 3. React API usage
    let react_usage = detect_react_api_usage(source);
    profile.uses_portal = react_usage.uses_portal;
    profile.portal_target = react_usage.portal_target;
    profile.consumed_contexts = react_usage.consumed_contexts;
    profile.is_forward_ref = react_usage.is_forward_ref;
    profile.is_memo = react_usage.is_memo;

    // 4. Prop defaults
    profile.prop_defaults = extract_prop_defaults(source);

    // 5. Children slot (single parse for both path and detail)
    profile.has_children_prop = has_children_prop(source);
    let (slot_path, slot_detail) = trace_children_slot_both(source);
    profile.children_slot_path = slot_path;
    profile.children_slot_detail = slot_detail;

    // 6. Props extends — from AST interface declarations
    profile.extends_props = ast_info.extends_props;

    // 7a. All props — from interface body
    profile.all_props = ast_info.all_props;
    profile.required_props = ast_info.required_props;
    profile.prop_types = ast_info.prop_types;

    // 8. Prop-to-style bindings — trace which props gate CSS class application
    profile.prop_style_bindings = extract_prop_style_bindings(source, &profile.all_props);

    // 7. Provided contexts — from AST-detected <XContext.Provider> JSX elements
    profile.provided_contexts = ast_info.context_providers;

    // 7b. Consumed contexts — merge useContext() hook calls (from react_api)
    //     with <XContext.Consumer> JSX elements (from AST).
    //     Class components use <Context.Consumer> render-prop pattern;
    //     function components use useContext() hooks. Both mean "I need this
    //     context provider above me."
    for ctx_name in ast_info.context_consumers {
        if !profile.consumed_contexts.contains(&ctx_name) {
            profile.consumed_contexts.push(ctx_name);
        }
    }

    // 9. Managed attribute bindings — detect prop-overrides-attribute patterns
    profile.managed_attributes =
        extract_managed_attributes(source, name, &profile.all_props, &profile.data_attributes);

    // 10. cloneElement injections — detected during the main AST walk above
    profile.clone_element_injections = ast_info.clone_element_injections;

    profile
}

/// Convert kebab-case to camelCase.
///
/// The CSS file path uses kebab-case (`modal-box`) but the JS token names
/// use camelCase (`modalBox`). This conversion aligns them.
pub(crate) fn kebab_to_camel_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut capitalize_next = false;
    for ch in s.chars() {
        if ch == '-' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(ch.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(ch);
        }
    }
    result
}

// (Props extends extraction is now done via the AST in extract_source_info)

// ── JSX info extraction (reused from jsx_diff, adapted for full source) ─

/// Aggregated information extracted from a full source file's AST.
#[derive(Debug, Default)]
struct FullSourceInfo {
    // ── JSX ─────────────────────────────────────────────────────────
    element_tags: BTreeMap<String, usize>,
    /// Tags that were found in an unconditional rendering context.
    /// If a tag is in `element_tags` but NOT in `unconditional_tags`,
    /// it was only found inside conditional branches (ternary, &&, if).
    unconditional_tags: BTreeSet<String>,
    aria_attrs: BTreeMap<(String, String), String>,
    role_attrs: BTreeMap<String, String>,
    data_attrs: BTreeMap<(String, String), String>,

    // ── React Context (from JSX AST) ────────────────────────────────
    /// Context names provided via `<XContext.Provider>` JSX elements.
    /// Detected from JSX member expressions with `.Provider` property.
    context_providers: Vec<String>,
    /// Context names consumed via `<XContext.Consumer>` JSX elements.
    /// Detected from JSX member expressions with `.Consumer` property.
    context_consumers: Vec<String>,

    // ── Imports ─────────────────────────────────────────────────────
    /// BEM block name derived from the primary `styles` import path.
    /// e.g., `import styles from '@patternfly/react-styles/css/components/Menu/menu'`
    /// → `Some("menu")`
    styles_bem_block: Option<String>,

    // ── Interface extends ───────────────────────────────────────────
    /// Props interfaces that the component's Props type extends.
    /// Extracted from TSInterfaceDeclaration extends clauses.
    extends_props: Vec<String>,

    // ── Interface props ─────────────────────────────────────────────
    /// All prop names from the component's Props interface body.
    all_props: BTreeSet<String>,
    /// Required props (not optional, no `?` marker).
    required_props: BTreeSet<String>,
    /// Prop name → type annotation string.
    prop_types: BTreeMap<String, String>,

    // ── cloneElement ────────────────────────────────────────────────
    /// Props injected via cloneElement, detected during AST walk.
    clone_element_injections: Vec<crate::sd_types::CloneElementInjection>,
}

/// Extract all AST-level info from a full source file in a single parse.
///
/// Collects JSX elements/attributes, the styles import path (for BEM
/// block resolution), and interface extends clauses.
fn extract_source_info(source: &str, component_name: &str) -> FullSourceInfo {
    let allocator = Allocator::default();
    let source_type = SourceType::tsx();
    let parsed = Parser::new(&allocator, source, source_type).parse();

    let mut info = FullSourceInfo::default();

    for stmt in &parsed.program.body {
        // Extract imports, interfaces, and JSX from top-level statements
        extract_from_module_stmt(stmt, source, component_name, &mut info);
    }

    info
}

/// Extract info from a single top-level statement (module-level).
fn extract_from_module_stmt<'a>(
    stmt: &'a Statement<'a>,
    source: &str,
    component_name: &str,
    info: &mut FullSourceInfo,
) {
    match stmt {
        // ── Import declarations ─────────────────────────────────────
        Statement::ImportDeclaration(import) => {
            let src = import.source.value.as_str();

            // Check for styles import from @patternfly/react-styles/css/...
            if src.contains("@patternfly/react-styles/css/") {
                // Check if the default binding is `styles` (not e.g., `breadcrumbStyles`)
                if let Some(specifiers) = &import.specifiers {
                    for spec in specifiers {
                        if let oxc_ast::ast::ImportDeclarationSpecifier::ImportDefaultSpecifier(
                            default_spec,
                        ) = spec
                        {
                            if default_spec.local.name == "styles" {
                                // Extract block from last path segment, converting
                                // kebab-case to camelCase to match JS token names.
                                // e.g., "modal-box" → "modalBox"
                                if let Some(block) = src.rsplit('/').next() {
                                    info.styles_bem_block = Some(kebab_to_camel_case(block));
                                }
                            }
                        }
                    }
                }
            }
        }

        // ── Export named (may contain interface or class declarations) ──
        Statement::ExportNamedDeclaration(export) => {
            if let Some(decl) = &export.declaration {
                extract_from_decl(decl, source, component_name, info);
            }
        }
        Statement::ExportDefaultDeclaration(export) => {
            if let Some(expr) = export.declaration.as_expression() {
                walk_expr_for_jsx(expr, source, info, false);
            }
        }

        // ── Bare declarations (interface, class, function, variable) ──
        Statement::TSInterfaceDeclaration(iface) => {
            extract_extends_from_interface(iface, component_name, source, info);
        }

        // Walk all other statements for JSX
        _ => walk_stmt_for_jsx(stmt, source, info, false),
    }
}

/// Extract info from a declaration (inside export or bare).
fn extract_from_decl<'a>(
    decl: &'a Declaration<'a>,
    source: &str,
    component_name: &str,
    info: &mut FullSourceInfo,
) {
    match decl {
        Declaration::TSInterfaceDeclaration(iface) => {
            extract_extends_from_interface(iface, component_name, source, info);
        }
        Declaration::FunctionDeclaration(f) => {
            if let Some(body) = &f.body {
                walk_stmts_for_jsx(&body.statements, source, info, false);
            }
        }
        Declaration::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                if let Some(init) = &declarator.init {
                    walk_expr_for_jsx(init, source, info, false);
                }
            }
        }
        Declaration::ClassDeclaration(cls) => {
            for item in &cls.body.body {
                match item {
                    ClassElement::MethodDefinition(method) => {
                        if let Some(body) = &method.value.body {
                            walk_stmts_for_jsx(&body.statements, source, info, false);
                        }
                    }
                    ClassElement::PropertyDefinition(prop) => {
                        if let Some(init) = &prop.value {
                            walk_expr_for_jsx(init, source, info, false);
                        }
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }
}

/// Extract extends clause from a TS interface declaration.
///
/// Matches interfaces named `{Component}Props` or `{Component}BaseProps`.
/// Unwraps utility types like `Omit<MenuItemProps, 'ref'>` to extract
/// the underlying props type.
fn extract_extends_from_interface(
    iface: &oxc_ast::ast::TSInterfaceDeclaration,
    component_name: &str,
    source: &str,
    info: &mut FullSourceInfo,
) {
    let iface_name = iface.id.name.as_str();

    // Only extract from the component's own Props interface
    let props_name = format!("{}Props", component_name);
    let base_props_name = format!("{}BaseProps", component_name);
    if iface_name != props_name && iface_name != base_props_name {
        return;
    }

    for heritage in &iface.extends {
        let type_name = resolve_heritage_props_type(heritage);
        if let Some(name) = type_name {
            if name.ends_with("Props") && name != iface_name {
                info.extends_props.push(name);
            }
        }
    }

    // Extract prop names and types from the interface body
    for sig in &iface.body.body {
        if let oxc_ast::ast::TSSignature::TSPropertySignature(prop) = sig {
            if let oxc_ast::ast::PropertyKey::StaticIdentifier(id) = &prop.key {
                let prop_name = id.name.to_string();
                info.all_props.insert(prop_name.clone());

                // Track required props (not optional, no `?` marker)
                if !prop.optional {
                    info.required_props.insert(prop_name.clone());
                }

                // Extract the type annotation if present
                if let Some(type_ann) = &prop.type_annotation {
                    let type_str =
                        &source[type_ann.span.start as usize..type_ann.span.end as usize];
                    // Strip the leading `: ` from the type annotation span
                    let type_str = type_str.trim_start_matches(':').trim();
                    if !type_str.is_empty() {
                        info.prop_types.insert(prop_name, type_str.to_string());
                    }
                }
            }
        }
    }
}

/// Resolve the actual Props type name from a heritage clause.
///
/// Handles:
/// - `MenuProps` → "MenuProps" (direct reference)
/// - `Omit<MenuItemProps, 'ref'>` → "MenuItemProps" (unwrap utility type)
/// - `Partial<MenuProps>` → "MenuProps"
/// - `Pick<MenuProps, 'x' | 'y'>` → "MenuProps"
fn resolve_heritage_props_type(heritage: &oxc_ast::ast::TSInterfaceHeritage) -> Option<String> {
    let expr_name = match &heritage.expression {
        Expression::Identifier(id) => id.name.as_str(),
        _ => return None,
    };

    // Direct Props reference (e.g., `extends MenuProps`)
    if expr_name.ends_with("Props") {
        return Some(expr_name.to_string());
    }

    // Utility type wrapper (e.g., `extends Omit<MenuItemProps, 'ref'>`)
    if matches!(
        expr_name,
        "Omit" | "Partial" | "Pick" | "Required" | "Readonly"
    ) {
        // Extract the first type argument — that's the actual Props type
        if let Some(type_args) = &heritage.type_arguments {
            if let Some(oxc_ast::ast::TSType::TSTypeReference(type_ref)) = type_args.params.first()
            {
                if let oxc_ast::ast::TSTypeName::IdentifierReference(id) = &type_ref.type_name {
                    return Some(id.name.to_string());
                }
            }
        }
    }

    None
}

// ── AST walking for JSX extraction ──────────────────────────────────────
// These mirror the jsx_diff walkers but populate FullSourceInfo.

fn walk_stmts_for_jsx<'a>(
    stmts: &'a [Statement<'a>],
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    for stmt in stmts {
        walk_stmt_for_jsx(stmt, source, info, conditional);
    }
}

fn walk_stmt_for_jsx<'a>(
    stmt: &'a Statement<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    match stmt {
        Statement::ClassDeclaration(cls) => {
            for item in &cls.body.body {
                match item {
                    ClassElement::MethodDefinition(method) => {
                        walk_params_for_jsx(&method.value.params, source, info, conditional);
                        if let Some(body) = &method.value.body {
                            walk_stmts_for_jsx(&body.statements, source, info, conditional);
                        }
                    }
                    ClassElement::PropertyDefinition(prop) => {
                        if let Some(init) = &prop.value {
                            walk_expr_for_jsx(init, source, info, conditional);
                        }
                    }
                    _ => {}
                }
            }
        }
        Statement::FunctionDeclaration(f) => {
            walk_params_for_jsx(&f.params, source, info, conditional);
            if let Some(body) = &f.body {
                walk_stmts_for_jsx(&body.statements, source, info, conditional);
            }
        }
        Statement::ReturnStatement(ret) => {
            if let Some(expr) = &ret.argument {
                walk_expr_for_jsx(expr, source, info, conditional);
            }
        }
        Statement::ExpressionStatement(expr_stmt) => {
            walk_expr_for_jsx(&expr_stmt.expression, source, info, conditional);
        }
        Statement::VariableDeclaration(decl) => {
            for declarator in &decl.declarations {
                walk_binding_defaults_for_jsx(&declarator.id, source, info, conditional);
                if let Some(init) = &declarator.init {
                    walk_expr_for_jsx(init, source, info, conditional);
                }
            }
        }
        Statement::ExportNamedDeclaration(export) => {
            if let Some(decl) = &export.declaration {
                walk_decl_for_jsx(decl, source, info, conditional);
            }
        }
        Statement::ExportDefaultDeclaration(export) => {
            if let Some(expr) = export.declaration.as_expression() {
                walk_expr_for_jsx(expr, source, info, conditional);
            }
        }
        // if/else branches are conditional
        Statement::IfStatement(if_stmt) => {
            walk_stmt_for_jsx(&if_stmt.consequent, source, info, true);
            if let Some(alt) = &if_stmt.alternate {
                walk_stmt_for_jsx(alt, source, info, true);
            }
        }
        Statement::BlockStatement(block) => {
            walk_stmts_for_jsx(&block.body, source, info, conditional);
        }
        _ => {}
    }
}

fn walk_decl_for_jsx<'a>(
    decl: &'a Declaration<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    match decl {
        Declaration::FunctionDeclaration(f) => {
            walk_params_for_jsx(&f.params, source, info, conditional);
            if let Some(body) = &f.body {
                walk_stmts_for_jsx(&body.statements, source, info, conditional);
            }
        }
        Declaration::VariableDeclaration(var_decl) => {
            for declarator in &var_decl.declarations {
                walk_binding_defaults_for_jsx(&declarator.id, source, info, conditional);
                if let Some(init) = &declarator.init {
                    walk_expr_for_jsx(init, source, info, conditional);
                }
            }
        }
        Declaration::ClassDeclaration(cls) => {
            for item in &cls.body.body {
                match item {
                    ClassElement::MethodDefinition(method) => {
                        walk_params_for_jsx(&method.value.params, source, info, conditional);
                        if let Some(body) = &method.value.body {
                            walk_stmts_for_jsx(&body.statements, source, info, conditional);
                        }
                    }
                    ClassElement::PropertyDefinition(prop) => {
                        if let Some(init) = &prop.value {
                            walk_expr_for_jsx(init, source, info, conditional);
                        }
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }
}

/// Walk a binding pattern's destructuring defaults for JSX elements.
///
/// Handles patterns like `const { bar = <Bar /> } = this.props` and
/// function params `({ bar = <Bar /> }) => ...`. When a destructured
/// property has an `AssignmentPattern` with a JSX default value, the
/// JSX element is fed into the normal expression walker so it appears
/// in `rendered_components`.
fn walk_binding_defaults_for_jsx<'a>(
    pattern: &'a BindingPattern<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    if let BindingPattern::ObjectPattern(obj) = pattern {
        for prop in &obj.properties {
            if let BindingPattern::AssignmentPattern(assign) = &prop.value {
                walk_expr_for_jsx(&assign.right, source, info, conditional);
            }
        }
    }
    // Also handle AssignmentPattern wrapping ObjectPattern:
    // ({ variant = 'primary' }: Props = {})
    if let BindingPattern::AssignmentPattern(assign) = pattern {
        if let BindingPattern::ObjectPattern(obj) = &assign.left {
            for prop in &obj.properties {
                if let BindingPattern::AssignmentPattern(inner) = &prop.value {
                    walk_expr_for_jsx(&inner.right, source, info, conditional);
                }
            }
        }
    }
}

/// Walk formal parameters for JSX elements in destructuring defaults.
fn walk_params_for_jsx<'a>(
    params: &'a FormalParameters<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    for param in &params.items {
        walk_binding_defaults_for_jsx(&param.pattern, source, info, conditional);
    }
}

fn walk_expr_for_jsx<'a>(
    expr: &'a Expression<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    match expr {
        Expression::JSXElement(el) => visit_jsx_element_info(el, source, info, conditional),
        Expression::JSXFragment(frag) => {
            for child in &frag.children {
                walk_jsx_child_info(child, source, info, conditional);
            }
        }
        Expression::ParenthesizedExpression(paren) => {
            walk_expr_for_jsx(&paren.expression, source, info, conditional);
        }
        // Ternary: both branches are conditional
        Expression::ConditionalExpression(cond) => {
            walk_expr_for_jsx(&cond.consequent, source, info, true);
            walk_expr_for_jsx(&cond.alternate, source, info, true);
        }
        // && / ||: right side is conditional
        Expression::LogicalExpression(logical) => {
            walk_expr_for_jsx(&logical.right, source, info, true);
        }
        Expression::CallExpression(call) => {
            // Detect cloneElement(child, { prop1, prop2 }) calls
            if let Some(injection) = clone_element::try_extract_clone_element_from_call(call) {
                info.clone_element_injections.push(injection);
            }
            for arg in &call.arguments {
                if let Some(expr) = arg.as_expression() {
                    // .map() callbacks: children rendered in map are unconditional
                    // (the component's purpose is to render them from data)
                    walk_expr_for_jsx(expr, source, info, conditional);
                }
            }
        }
        // TypeScript expression wrappers — transparent to JSX walking.
        // e.g., `ReactDOM.createPortal(<Foo/>, el) as React.ReactElement`
        Expression::TSAsExpression(ts_as) => {
            walk_expr_for_jsx(&ts_as.expression, source, info, conditional);
        }
        Expression::TSSatisfiesExpression(ts_sat) => {
            walk_expr_for_jsx(&ts_sat.expression, source, info, conditional);
        }
        Expression::TSNonNullExpression(ts_nn) => {
            walk_expr_for_jsx(&ts_nn.expression, source, info, conditional);
        }
        Expression::TSTypeAssertion(ts_assert) => {
            walk_expr_for_jsx(&ts_assert.expression, source, info, conditional);
        }
        Expression::TSInstantiationExpression(ts_inst) => {
            walk_expr_for_jsx(&ts_inst.expression, source, info, conditional);
        }
        Expression::ArrowFunctionExpression(arrow) => {
            walk_params_for_jsx(&arrow.params, source, info, conditional);
            walk_stmts_for_jsx(&arrow.body.statements, source, info, conditional);
        }
        Expression::FunctionExpression(func) => {
            walk_params_for_jsx(&func.params, source, info, conditional);
            if let Some(body) = &func.body {
                walk_stmts_for_jsx(&body.statements, source, info, conditional);
            }
        }
        _ => {}
    }
}

fn walk_jsx_child_info<'a>(
    child: &'a JSXChild<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    match child {
        JSXChild::Element(el) => visit_jsx_element_info(el, source, info, conditional),
        JSXChild::Fragment(frag) => {
            for c in &frag.children {
                walk_jsx_child_info(c, source, info, conditional);
            }
        }
        JSXChild::ExpressionContainer(container) => {
            if let Some(expr) = container.expression.as_expression() {
                walk_expr_for_jsx(expr, source, info, conditional);
            }
        }
        _ => {}
    }
}

fn visit_jsx_element_info<'a>(
    el: &'a JSXElement<'a>,
    source: &str,
    info: &mut FullSourceInfo,
    conditional: bool,
) {
    let tag_name = jsx_element_name_str(&el.opening_element.name);

    *info.element_tags.entry(tag_name.clone()).or_insert(0) += 1;
    if !conditional {
        info.unconditional_tags.insert(tag_name.clone());
    }

    // Detect React Context usage from JSX member expressions:
    //   <XContext.Provider ...>  → context_providers += "XContext"
    //   <XContext.Consumer>      → context_consumers += "XContext"
    if let JSXElementName::MemberExpression(member) = &el.opening_element.name {
        let prop = member.property.name.as_str();
        if prop == "Provider" || prop == "Consumer" {
            let ctx_name = jsx_member_obj_str(&member.object);
            let list = if prop == "Provider" {
                &mut info.context_providers
            } else {
                &mut info.context_consumers
            };
            if !list.contains(&ctx_name) {
                list.push(ctx_name);
            }
        }
    }

    // Extract attributes
    for attr_item in &el.opening_element.attributes {
        if let JSXAttributeItem::Attribute(attr) = attr_item {
            let attr_name = jsx_attr_name_str(&attr.name);
            let attr_value = attr
                .value
                .as_ref()
                .map(|v| jsx_attr_value_str(v, source))
                .unwrap_or_default();

            if attr_name.starts_with("aria-") {
                info.aria_attrs
                    .insert((tag_name.clone(), attr_name), attr_value);
            } else if attr_name == "role" {
                info.role_attrs.insert(tag_name.clone(), attr_value);
            } else if attr_name.starts_with("data-") {
                info.data_attrs
                    .insert((tag_name.clone(), attr_name), attr_value);
            }
        }
    }

    // Recurse into children (inherit conditionality from parent)
    for child in &el.children {
        walk_jsx_child_info(child, source, info, conditional);
    }

    // Also recurse into attribute values (for JSX in props)
    for attr_item in &el.opening_element.attributes {
        if let JSXAttributeItem::Attribute(attr) = attr_item {
            if let Some(JSXAttributeValue::ExpressionContainer(container)) = &attr.value {
                if let Some(expr) = container.expression.as_expression() {
                    walk_expr_for_jsx(expr, source, info, conditional);
                }
            }
        }
    }
}

// ── JSX name/value helpers ──────────────────────────────────────────────

fn jsx_element_name_str(name: &JSXElementName) -> String {
    match name {
        JSXElementName::Identifier(id) => id.name.to_string(),
        JSXElementName::IdentifierReference(id) => id.name.to_string(),
        JSXElementName::NamespacedName(ns) => {
            format!("{}:{}", ns.namespace.name, ns.name.name)
        }
        JSXElementName::MemberExpression(member) => {
            format!(
                "{}.{}",
                jsx_member_obj_str(&member.object),
                member.property.name
            )
        }
        JSXElementName::ThisExpression(_) => "this".to_string(),
    }
}

fn jsx_member_obj_str(obj: &JSXMemberExpressionObject) -> String {
    match obj {
        JSXMemberExpressionObject::IdentifierReference(id) => id.name.to_string(),
        JSXMemberExpressionObject::MemberExpression(member) => {
            format!(
                "{}.{}",
                jsx_member_obj_str(&member.object),
                member.property.name
            )
        }
        JSXMemberExpressionObject::ThisExpression(_) => "this".to_string(),
    }
}

fn jsx_attr_name_str(name: &JSXAttributeName) -> String {
    match name {
        JSXAttributeName::Identifier(id) => id.name.to_string(),
        JSXAttributeName::NamespacedName(ns) => {
            format!("{}:{}", ns.namespace.name, ns.name.name)
        }
    }
}

fn jsx_attr_value_str(value: &JSXAttributeValue, source: &str) -> String {
    match value {
        JSXAttributeValue::StringLiteral(s) => s.value.to_string(),
        JSXAttributeValue::ExpressionContainer(container) => {
            let span = container.span;
            source
                .get(span.start as usize..span.end as usize)
                .unwrap_or("")
                .to_string()
        }
        _ => String::new(),
    }
}

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

    #[test]
    fn test_extract_profile_simple() {
        let source = r#"
            import styles from '@patternfly/react-styles/css/components/Menu/menu';
            import { css } from '@patternfly/react-styles';

            export const MenuList = ({ children, className }: MenuListProps) => (
                <ul className={css(styles.menuList, className)}>
                    {children}
                </ul>
            );
        "#;

        let profile = extract_profile(
            "MenuList",
            "packages/react-core/src/components/Menu/MenuList.tsx",
            source,
        );
        assert_eq!(profile.name, "MenuList");
        assert!(profile.rendered_elements.contains_key("ul"));
        assert!(profile.has_children_prop);
        assert_eq!(profile.children_slot_path, vec!["ul"]);
        assert!(profile.css_tokens_used.contains("styles.menuList"));
    }

    #[test]
    fn test_extract_profile_with_portal() {
        let source = r#"
            import * as ReactDOM from 'react-dom';

            class Modal extends React.Component {
                render() {
                    return ReactDOM.createPortal(
                        <ModalContent>{this.props.children}</ModalContent>,
                        this.getElement(this.props.appendTo)
                    );
                }
            }
            export { Modal };
        "#;

        let profile = extract_profile("Modal", "Modal.tsx", source);
        assert!(profile.uses_portal);
        assert!(profile.portal_target.is_some());
    }

    #[test]
    fn test_extract_profile_with_context() {
        let source = r#"
            import { useContext } from 'react';
            import { AccordionItemContext } from './AccordionItemContext';

            export const AccordionContent = ({ children }: Props) => {
                const { isExpanded } = useContext(AccordionItemContext);
                return isExpanded ? <div>{children}</div> : null;
            };
        "#;

        let profile = extract_profile("AccordionContent", "AccordionContent.tsx", source);
        assert!(profile
            .consumed_contexts
            .contains(&"AccordionItemContext".to_string()));
    }

    #[test]
    fn test_extract_extends_props() {
        let source = r#"
            import { MenuListProps, MenuList } from '../Menu';

            export interface DropdownListProps extends MenuListProps {
                children: React.ReactNode;
                className?: string;
            }
        "#;

        let profile = extract_profile("DropdownList", "DropdownList.tsx", source);
        assert_eq!(profile.extends_props, vec!["MenuListProps"]);
    }

    #[test]
    fn test_extract_extends_props_multiple() {
        let source = r#"
            export interface DropdownProps extends MenuProps, OUIAProps {
                children?: React.ReactNode;
            }
        "#;

        let profile = extract_profile("Dropdown", "Dropdown.tsx", source);
        assert_eq!(profile.extends_props, vec!["MenuProps", "OUIAProps"]);
    }

    #[test]
    fn test_extract_extends_props_omit() {
        let source = r#"
            export interface DropdownItemProps extends Omit<MenuItemProps, 'ref'>, OUIAProps {
                children?: React.ReactNode;
            }
        "#;

        let profile = extract_profile("DropdownItem", "DropdownItem.tsx", source);
        assert_eq!(profile.extends_props, vec!["MenuItemProps", "OUIAProps"]);
    }

    #[test]
    fn test_extract_profile_class_component_context() {
        let source = r#"
            import { Component } from 'react';
            import { MenuContext } from './MenuContext';

            export interface MenuProps {
                children?: React.ReactNode;
            }

            class MenuBase extends Component<MenuProps> {
                render() {
                    return (
                        <MenuContext.Provider value={{ menuId: 'test' }}>
                            <div>{this.props.children}</div>
                        </MenuContext.Provider>
                    );
                }
            }

            export const Menu = MenuBase;
        "#;

        let profile = extract_profile("Menu", "Menu.tsx", source);
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "MenuContext.Provider"),
            "Expected MenuContext.Provider in rendered_components, got: {:?}",
            profile.rendered_components
        );
        assert!(
            profile
                .provided_contexts
                .contains(&"MenuContext".to_string()),
            "Expected MenuContext in provided_contexts, got: {:?}",
            profile.provided_contexts
        );
        assert!(
            profile.has_children_prop,
            "Expected has_children_prop=true for class component with children?: React.ReactNode"
        );
    }

    #[test]
    fn test_extract_profile_with_defaults() {
        let source = r#"
            export const Button = ({
                variant = 'primary',
                isDisabled = false,
                children,
            }: ButtonProps) => (
                <button disabled={isDisabled}>{children}</button>
            );
        "#;

        let profile = extract_profile("Button", "Button.tsx", source);
        assert_eq!(
            profile.prop_defaults.get("variant"),
            Some(&"'primary'".to_string())
        );
        assert_eq!(
            profile.prop_defaults.get("isDisabled"),
            Some(&"false".to_string())
        );
    }

    #[test]
    fn test_extract_profile_class_component_consumer() {
        // Class component using <XContext.Consumer> render-prop pattern.
        // This is how Toolbar family components consume context.
        let source = r#"
            import { Component } from 'react';
            import { ToolbarContentContext, ToolbarContext } from './ToolbarUtils';
            import { PageContext } from '../Page/PageContext';

            class ToolbarToggleGroup extends Component<ToolbarToggleGroupProps> {
                render() {
                    return (
                        <PageContext.Consumer>
                            {({ width }) => (
                                <ToolbarContext.Consumer>
                                    {({ isExpanded }) => (
                                        <ToolbarContentContext.Consumer>
                                            {({ expandableContentRef }) => (
                                                <div>{this.props.children}</div>
                                            )}
                                        </ToolbarContentContext.Consumer>
                                    )}
                                </ToolbarContext.Consumer>
                            )}
                        </PageContext.Consumer>
                    );
                }
            }
            export { ToolbarToggleGroup };
        "#;

        let profile = extract_profile("ToolbarToggleGroup", "ToolbarToggleGroup.tsx", source);
        assert!(
            profile
                .consumed_contexts
                .contains(&"ToolbarContentContext".to_string()),
            "Expected ToolbarContentContext in consumed_contexts, got: {:?}",
            profile.consumed_contexts
        );
        assert!(
            profile
                .consumed_contexts
                .contains(&"ToolbarContext".to_string()),
            "Expected ToolbarContext in consumed_contexts, got: {:?}",
            profile.consumed_contexts
        );
        assert!(
            profile
                .consumed_contexts
                .contains(&"PageContext".to_string()),
            "Expected PageContext in consumed_contexts, got: {:?}",
            profile.consumed_contexts
        );
    }

    #[test]
    fn test_extract_profile_class_component_provider_and_consumer() {
        // ToolbarContent: provides ToolbarContentContext, consumes ToolbarContext.
        // This is the "bridge" component that the context nesting inference
        // should detect as a required intermediate.
        let source = r#"
            import { Component } from 'react';
            import { ToolbarContentContext, ToolbarContext } from './ToolbarUtils';

            export interface ToolbarContentProps {
                children?: React.ReactNode;
            }

            class ToolbarContent extends Component<ToolbarContentProps> {
                render() {
                    return (
                        <ToolbarContext.Consumer>
                            {({ clearAllFilters }) => (
                                <ToolbarContentContext.Provider
                                    value={{
                                        expandableContentRef: this.expandableContentRef,
                                        isExpanded: this.props.isExpanded,
                                    }}
                                >
                                    <div>{this.props.children}</div>
                                </ToolbarContentContext.Provider>
                            )}
                        </ToolbarContext.Consumer>
                    );
                }
            }
            export { ToolbarContent };
        "#;

        let profile = extract_profile("ToolbarContent", "ToolbarContent.tsx", source);

        // Should PROVIDE ToolbarContentContext
        assert!(
            profile
                .provided_contexts
                .contains(&"ToolbarContentContext".to_string()),
            "Expected ToolbarContentContext in provided_contexts, got: {:?}",
            profile.provided_contexts
        );

        // Should CONSUME ToolbarContext
        assert!(
            profile
                .consumed_contexts
                .contains(&"ToolbarContext".to_string()),
            "Expected ToolbarContext in consumed_contexts, got: {:?}",
            profile.consumed_contexts
        );

        // Should have children prop
        assert!(profile.has_children_prop);
    }

    #[test]
    fn test_extract_profile_usecontext_and_consumer_merged() {
        // Component that uses BOTH useContext() and <X.Consumer> —
        // consumed_contexts should contain both without duplicates.
        let source = r#"
            import { useContext } from 'react';
            import { AccordionItemContext } from './AccordionItemContext';
            import { AccordionContext } from './AccordionContext';

            export const AccordionToggle = ({ children }: Props) => {
                const { isExpanded } = useContext(AccordionItemContext);
                return (
                    <AccordionContext.Consumer>
                        {({ displaySize }) => (
                            <button>{children}</button>
                        )}
                    </AccordionContext.Consumer>
                );
            };
        "#;

        let profile = extract_profile("AccordionToggle", "AccordionToggle.tsx", source);
        assert!(
            profile
                .consumed_contexts
                .contains(&"AccordionItemContext".to_string()),
            "Should detect useContext(AccordionItemContext)"
        );
        assert!(
            profile
                .consumed_contexts
                .contains(&"AccordionContext".to_string()),
            "Should detect <AccordionContext.Consumer>"
        );
        // No duplicates
        let unique: std::collections::HashSet<_> = profile.consumed_contexts.iter().collect();
        assert_eq!(
            unique.len(),
            profile.consumed_contexts.len(),
            "consumed_contexts should have no duplicates"
        );
    }

    /// JSX elements in arrow function parameter destructuring defaults
    /// should appear in rendered_components.
    ///
    /// Models the ChartBullet pattern:
    /// `({ measureComponent = <ChartBar /> }) => { ... }`
    #[test]
    fn test_extract_profile_arrow_param_default_jsx() {
        let source = r#"
            import { cloneElement } from 'react';
            export const ChartBullet = ({
                comparativeErrorMeasureComponent = <ChartBulletComparativeErrorMeasure />,
                qualitativeRangeComponent = <ChartBulletQualitativeRange />,
                titleComponent = <ChartBulletTitle />,
            }: ChartBulletProps) => {
                const measure = cloneElement(comparativeErrorMeasureComponent, { height: 100 });
                return <div>{measure}</div>;
            };
        "#;

        let profile = extract_profile("ChartBullet", "ChartBullet.tsx", source);
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "ChartBulletComparativeErrorMeasure"),
            "Expected ChartBulletComparativeErrorMeasure in rendered_components, got: {:?}",
            profile.rendered_components
        );
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "ChartBulletQualitativeRange"),
            "Expected ChartBulletQualitativeRange in rendered_components, got: {:?}",
            profile.rendered_components
        );
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "ChartBulletTitle"),
            "Expected ChartBulletTitle in rendered_components, got: {:?}",
            profile.rendered_components
        );
    }

    /// JSX elements in class component render() destructuring defaults
    /// should appear in rendered_components.
    ///
    /// Models the ExpandableSection pattern:
    /// `const { toggleIcon = <CaretDownIcon /> } = this.props;`
    #[test]
    fn test_extract_profile_class_render_destructuring_default_jsx() {
        let source = r#"
            import { Component } from 'react';

            class ExpandableSection extends Component<ExpandableSectionProps> {
                render() {
                    const {
                        toggleIcon = <RhMicronsCaretDownIcon />,
                        children,
                    } = this.props;

                    return (
                        <div>
                            {toggleIcon}
                            {children}
                        </div>
                    );
                }
            }
            export { ExpandableSection };
        "#;

        let profile = extract_profile("ExpandableSection", "ExpandableSection.tsx", source);
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "RhMicronsCaretDownIcon"),
            "Expected RhMicronsCaretDownIcon in rendered_components, got: {:?}",
            profile.rendered_components
        );
    }

    #[test]
    fn test_extract_profile_dynamic_component_td() {
        // Simplified version of PatternFly's Td pattern
        let source = r#"
            const TdBase = ({
                children,
                component = 'td',
                className,
            }: TdProps) => {
                const merged = mergeProps({ component });
                const {
                    component: MergedComponent = component,
                    children: mergedChildren = null,
                } = merged;
                const cell = (
                    <MergedComponent className={className}>
                        {mergedChildren || children}
                    </MergedComponent>
                );
                return cell;
            };

            export const Td = forwardRef((props: TdProps, ref) => (
                <TdBase {...props} innerRef={ref} />
            ));
        "#;

        let profile = extract_profile("Td", "Td.tsx", source);
        eprintln!("Td children_slot_path: {:?}", profile.children_slot_path);
        eprintln!("Td has_children_prop: {}", profile.has_children_prop);
        eprintln!("Td rendered_elements: {:?}", profile.rendered_elements);
        assert_eq!(profile.children_slot_path, vec!["td"]);
    }

    /// Class components that define `render` as an arrow property assignment
    /// (`render = () => { ... }`) use `ClassElement::PropertyDefinition` in
    /// the OXC AST, not `ClassElement::MethodDefinition`. The JSX walker must
    /// handle both forms to detect internally rendered components.
    ///
    /// Real-world example: PatternFly's ClipboardCopy component.
    #[test]
    fn test_extract_profile_class_property_definition_render() {
        let source = r#"
            import { Component } from 'react';
            import { ClipboardCopyButton } from './ClipboardCopyButton';
            import { ClipboardCopyToggle } from './ClipboardCopyToggle';

            class ClipboardCopy extends Component<ClipboardCopyProps, ClipboardCopyState> {
                timer = null as any;

                render = () => {
                    const { children } = this.props;
                    return (
                        <div>
                            <ClipboardCopyToggle />
                            <input value={this.state.text} />
                            <ClipboardCopyButton onClick={this.handleCopy}>
                                Copy
                            </ClipboardCopyButton>
                            {children}
                        </div>
                    );
                };
            }

            export { ClipboardCopy };
        "#;

        let profile = extract_profile("ClipboardCopy", "ClipboardCopy.tsx", source);
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "ClipboardCopyButton"),
            "Expected ClipboardCopyButton in rendered_components, got: {:?}",
            profile.rendered_components
        );
        assert!(
            profile
                .rendered_components
                .iter()
                .any(|r| r.name == "ClipboardCopyToggle"),
            "Expected ClipboardCopyToggle in rendered_components, got: {:?}",
            profile.rendered_components
        );
    }

    #[test]
    fn test_conditional_rendering_ternary() {
        // Components inside ternary are conditional;
        // components outside are unconditional.
        let source = r#"
            import React from 'react';
            const Comp = ({ show }) => {
                return (
                    <div>
                        <AlwaysRendered />
                        {show ? <ConditionalA /> : <ConditionalB />}
                    </div>
                );
            };
            export { Comp };
        "#;

        let profile = extract_profile("Comp", "Comp.tsx", source);

        let always = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "AlwaysRendered");
        assert!(always.is_some(), "AlwaysRendered should be present");
        assert!(
            !always.unwrap().conditional,
            "AlwaysRendered should be unconditional"
        );

        let cond_a = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "ConditionalA");
        assert!(cond_a.is_some(), "ConditionalA should be present");
        assert!(
            cond_a.unwrap().conditional,
            "ConditionalA should be conditional (inside ternary)"
        );

        let cond_b = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "ConditionalB");
        assert!(cond_b.is_some(), "ConditionalB should be present");
        assert!(
            cond_b.unwrap().conditional,
            "ConditionalB should be conditional (inside ternary)"
        );
    }

    #[test]
    fn test_conditional_rendering_logical_and() {
        // Components inside && are conditional.
        let source = r#"
            import React from 'react';
            const Comp = ({ show }) => {
                return (
                    <div>
                        <Header />
                        {show && <OptionalFooter />}
                    </div>
                );
            };
            export { Comp };
        "#;

        let profile = extract_profile("Comp", "Comp.tsx", source);

        let header = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "Header");
        assert!(
            !header.unwrap().conditional,
            "Header should be unconditional"
        );

        let footer = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "OptionalFooter");
        assert!(
            footer.unwrap().conditional,
            "OptionalFooter should be conditional (inside &&)"
        );
    }

    #[test]
    fn test_conditional_rendering_if_statement() {
        // Components inside if branches are conditional.
        let source = r#"
            import React from 'react';
            function Comp({ variant }) {
                if (variant === 'a') {
                    return <VariantA />;
                }
                return <Default />;
            }
            export { Comp };
        "#;

        let profile = extract_profile("Comp", "Comp.tsx", source);

        let variant_a = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "VariantA");
        assert!(
            variant_a.unwrap().conditional,
            "VariantA should be conditional (inside if branch)"
        );

        let default = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "Default");
        assert!(
            !default.unwrap().conditional,
            "Default should be unconditional (bare return)"
        );
    }

    #[test]
    fn test_conditional_rendering_map_is_unconditional() {
        // Components inside .map() are unconditional — the component's
        // purpose is to render children from data.
        let source = r#"
            import React from 'react';
            const List = ({ items }) => {
                return (
                    <ul>
                        {items.map(item => <ListItem key={item.id} />)}
                    </ul>
                );
            };
            export { List };
        "#;

        let profile = extract_profile("List", "List.tsx", source);

        let item = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "ListItem");
        assert!(
            !item.unwrap().conditional,
            "ListItem inside .map() should be unconditional"
        );
    }

    #[test]
    fn test_unconditional_wins_over_conditional() {
        // If a component appears both conditionally and unconditionally,
        // unconditional wins.
        let source = r#"
            import React from 'react';
            const Comp = ({ extra }) => {
                return (
                    <div>
                        <Child />
                        {extra && <Child />}
                    </div>
                );
            };
            export { Comp };
        "#;

        let profile = extract_profile("Comp", "Comp.tsx", source);

        let child = profile
            .rendered_components
            .iter()
            .find(|r| r.name == "Child");
        assert!(
            !child.unwrap().conditional,
            "Child should be unconditional (appears in both conditional and unconditional contexts)"
        );
    }
}