hypen-engine 0.4.46

A Rust implementation of the Hypen engine
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
use super::conditionals::{evaluate_value, find_matching_branch};
use super::item_bindings::{replace_ir_node_item_bindings, replace_item_bindings};
use super::keyed::generate_item_key;
use super::resolve::{evaluate_binding, resolve_props_full};
use super::{ControlFlowKind, InstanceTree, Patch};
use crate::ir::{ConditionalBranch, Element, IRNode, NodeId, Props, Value};
use crate::reactive::{Binding, DependencyGraph};
use indexmap::IndexMap;

/// Data sources type alias for readability
type DataSources = indexmap::IndexMap<String, serde_json::Value>;

/// Shared mutable context threaded through the recursive tree-building and
/// reconciliation helpers.  Grouping these fields removes the repetitive
/// parameter tuple that was being copy-pasted across every internal function.
struct ReconcileCtx<'a> {
    tree: &'a mut InstanceTree,
    state: &'a serde_json::Value,
    patches: &'a mut Vec<Patch>,
    dependencies: &'a mut DependencyGraph,
    data_sources: Option<&'a DataSources>,
}

/// Reconcile an element tree against the instance tree and generate patches
pub fn reconcile(
    tree: &mut InstanceTree,
    element: &Element,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    dependencies: &mut DependencyGraph,
) -> Vec<Patch> {
    reconcile_with_ds(tree, element, parent_id, state, dependencies, None)
}

/// Reconcile an element tree with data source context
pub fn reconcile_with_ds(
    tree: &mut InstanceTree,
    element: &Element,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> Vec<Patch> {
    let mut patches = Vec::new();

    // For initial render, just create the tree
    if tree.root().is_none() {
        let node_id = create_tree(
            tree,
            element,
            parent_id,
            state,
            &mut patches,
            true,
            dependencies,
            data_sources,
        );
        tree.set_root(node_id);
        return patches;
    }

    // Incremental update: reconcile root against existing tree
    if let Some(root_id) = tree.root() {
        reconcile_node(tree, root_id, element, state, &mut patches, dependencies, data_sources);
    }

    patches
}

/// Reconcile an IRNode tree against the instance tree and generate patches
/// This is the primary entry point for the IRNode-based reconciliation system,
/// which supports first-class ForEach, When/If, and custom item variable names.
pub fn reconcile_ir(
    tree: &mut InstanceTree,
    node: &IRNode,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    dependencies: &mut DependencyGraph,
) -> Vec<Patch> {
    reconcile_ir_with_ds(tree, node, parent_id, state, dependencies, None)
}

/// Reconcile an IRNode tree with data source context
pub fn reconcile_ir_with_ds(
    tree: &mut InstanceTree,
    node: &IRNode,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> Vec<Patch> {
    let mut patches = Vec::new();

    // For initial render, create the tree
    if tree.root().is_none() {
        let node_id = create_ir_node_tree(
            tree,
            node,
            parent_id,
            state,
            &mut patches,
            true,
            dependencies,
            data_sources,
        );
        tree.set_root(node_id);
        return patches;
    }

    // Incremental update: reconcile root against existing tree
    if let Some(root_id) = tree.root() {
        reconcile_ir_node(tree, root_id, node, state, &mut patches, dependencies, data_sources);
    }

    patches
}

/// Create a new subtree from an element
#[allow(clippy::too_many_arguments)]
pub fn create_tree(
    tree: &mut InstanceTree,
    element: &Element,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    is_root: bool,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> NodeId {
    // Special handling for iterable elements (List, Grid, etc.)
    // An element is iterable if it has BOTH:
    // 1. prop "0" with a Binding (like @state.items) - not a static value
    // 2. children (the template to repeat for each item)
    // This distinguishes iterables from:
    // - Text elements (prop "0" but no children)
    // - Route/Link elements (prop "0" with static path, not a binding)
    if let Some(Value::Binding(_)) = element.props.get("0") {
        if !element.children.is_empty() {
            return create_list_tree(
                tree,
                element,
                parent_id,
                state,
                patches,
                is_root,
                dependencies,
                data_sources,
            );
        }
    }

    // Create the node (with data sources for proper binding resolution)
    let node_id = tree.create_node_full(element, state, data_sources);

    // Register dependencies for this node
    for value in element.props.values() {
        match value {
            Value::Binding(binding) => {
                dependencies.add_dependency(node_id, binding);
            }
            Value::TemplateString { bindings, .. } => {
                // Register all bindings in the template string
                for binding in bindings {
                    dependencies.add_dependency(node_id, binding);
                }
            }
            _ => {}
        }
    }

    // Generate Create patch
    let node = tree.get(node_id).unwrap();

    // For lazy elements, add child component name as a prop
    let mut props = node.props.clone();
    if let Some(Value::Static(val)) = element.props.get("__lazy") {
        if val.as_bool().unwrap_or(false) && !element.children.is_empty() {
            // Store the first child's element type so renderer knows what component to load
            let child_component = &element.children[0].element_type;
            props.insert(
                "__lazy_child".to_string(),
                serde_json::json!(child_component),
            );
        }
    }

    patches.push(Patch::create(node_id, node.element_type.clone(), props));

    // Event handling is now done at the renderer level

    // If there's a parent, insert this node
    if let Some(parent) = parent_id {
        tree.add_child(parent, node_id, None);
        patches.push(Patch::insert(parent, node_id, None));
    } else if is_root {
        // This is the root node - insert into "root" container
        patches.push(Patch::insert_root(node_id));
    }

    // Create children (skip if element is marked as lazy)
    let is_lazy = element
        .props
        .get("__lazy")
        .and_then(|v| {
            if let Value::Static(val) = v {
                val.as_bool()
            } else {
                None
            }
        })
        .unwrap_or(false);

    if !is_lazy {
        for child_element in &element.children {
            create_tree(
                tree,
                child_element,
                Some(node_id),
                state,
                patches,
                false,
                dependencies,
                data_sources,
            );
        }
    }

    node_id
}

/// Create an iterable element (List, Grid, etc.) that iterates over an array in state
/// Iterable elements are identified by having prop "0" with an array binding
#[allow(clippy::too_many_arguments)]
fn create_list_tree(
    tree: &mut InstanceTree,
    element: &Element,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    is_root: bool,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> NodeId {
    // Get the array binding from first prop (prop "0")
    let array = if let Some(Value::Binding(binding)) = element.props.get("0") {
        evaluate_binding(binding, state).unwrap_or(serde_json::Value::Array(vec![]))
    } else {
        serde_json::Value::Array(vec![])
    };

    // Create a container element - use the original element type (List, Grid, etc.)
    // but remove the "0" prop since it's only for iteration, not rendering
    let mut list_element = Element::new(&element.element_type);
    for (key, value) in &element.props {
        // Skip prop "0" - it's only for array binding, not for rendering
        if key != "0" {
            list_element.props.insert(key.clone(), value.clone());
        }
    }

    let node_id = tree.create_node_full(&list_element, state, data_sources);

    // Register the List node as depending on the array binding
    // This is critical for reactive updates when the array changes
    if let Some(Value::Binding(binding)) = element.props.get("0") {
        dependencies.add_dependency(node_id, binding);
    }

    // Store the original element template for re-reconciliation
    // This allows us to rebuild the list when the array changes
    if let Some(node) = tree.get_mut(node_id) {
        node.raw_props = element.props.clone();
        node.element_template = Some(std::sync::Arc::new(element.clone()));
    }

    // Generate Create patch for container
    let node = tree.get(node_id).unwrap();
    patches.push(Patch::create(
        node_id,
        node.element_type.clone(),
        node.props.clone(),
    ));

    // Insert container
    if let Some(parent) = parent_id {
        tree.add_child(parent, node_id, None);
        patches.push(Patch::insert(parent, node_id, None));
    } else if is_root {
        patches.push(Patch::insert_root(node_id));
    }

    // If array is empty, return early
    if let serde_json::Value::Array(items) = &array {
        // Create children for each item in the array
        for (index, item) in items.iter().enumerate() {
            for child_template in &element.children {
                // Clone child and replace ${item.x} bindings with actual item data
                let child_with_item = replace_item_bindings(child_template, item, index);
                create_tree(
                    tree,
                    &child_with_item,
                    Some(node_id),
                    state,
                    patches,
                    false,
                    dependencies,
                    data_sources,
                );
            }
        }
    }

    node_id
}

/// Reconcile a single node with a new element
pub fn reconcile_node(
    tree: &mut InstanceTree,
    node_id: NodeId,
    element: &Element,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) {
    let node = tree.get(node_id).cloned();
    if node.is_none() {
        return;
    }
    let node = node.unwrap();

    // Special handling for iterable elements (List, Grid, etc.)
    // An element is iterable if it has BOTH prop "0" (array binding) AND children (template)
    // This distinguishes iterables from Text elements, which also use prop "0" but have no children
    let is_iterable = element.props.get("0").is_some() && !element.children.is_empty();

    if is_iterable {
        // Get the array binding from first prop (prop "0")
        let array = if let Some(Value::Binding(binding)) = element.props.get("0") {
            evaluate_binding(binding, state).unwrap_or(serde_json::Value::Array(vec![]))
        } else {
            serde_json::Value::Array(vec![])
        };

        // Regenerate iterable children
        if let serde_json::Value::Array(items) = &array {
            let old_children = node.children.clone();

            // Calculate expected number of children
            let expected_children_count = items.len() * element.children.len();

            // Remove old children if count doesn't match
            if old_children.len() != expected_children_count {
                for &old_child_id in &old_children {
                    patches.push(Patch::remove(old_child_id));
                }

                // Clear children from node
                if let Some(node) = tree.get_mut(node_id) {
                    node.children.clear();
                }

                // Create new children
                for (index, item) in items.iter().enumerate() {
                    for child_template in &element.children {
                        let child_with_item = replace_item_bindings(child_template, item, index);
                        create_tree(
                            tree,
                            &child_with_item,
                            Some(node_id),
                            state,
                            patches,
                            false,
                            dependencies,
                            data_sources,
                        );
                    }
                }
            } else {
                // Reconcile existing children
                let mut child_index = 0;
                for (item_index, item) in items.iter().enumerate() {
                    for child_template in &element.children {
                        if let Some(&old_child_id) = old_children.get(child_index) {
                            let child_with_item =
                                replace_item_bindings(child_template, item, item_index);
                            reconcile_node(
                                tree,
                                old_child_id,
                                &child_with_item,
                                state,
                                patches,
                                dependencies,
                                data_sources,
                            );
                        }
                        child_index += 1;
                    }
                }
            }
        }

        return; // Done with List reconciliation
    }

    // If element type changed, replace the entire subtree
    if node.element_type != element.element_type {
        replace_subtree(tree, node_id, &node, element, state, patches, dependencies, data_sources);
        return;
    }

    // Register dependencies for this node (must match create_tree to survive clear+reconcile)
    for value in element.props.values() {
        match value {
            Value::Binding(binding) => {
                dependencies.add_dependency(node_id, binding);
            }
            Value::TemplateString { bindings, .. } => {
                for binding in bindings {
                    dependencies.add_dependency(node_id, binding);
                }
            }
            _ => {}
        }
    }

    // Diff props (thread data_sources for template strings with data source refs)
    let new_props = resolve_props_full(&element.props, state, None, data_sources);
    let prop_patches = diff_props(node_id, &node.props, &new_props);
    patches.extend(prop_patches);

    // Update node props in tree
    if let Some(node) = tree.get_mut(node_id) {
        node.props = new_props.clone();
        node.raw_props = element.props.clone();
    }

    // Reconcile children (skip if element is marked as lazy)
    let is_lazy = element
        .props
        .get("__lazy")
        .and_then(|v| {
            if let Value::Static(val) = v {
                val.as_bool()
            } else {
                None
            }
        })
        .unwrap_or(false);

    if !is_lazy {
        let old_children = node.children.clone();
        let new_children = &element.children;

        // Simple strategy: match children by index
        for (i, new_child_element) in new_children.iter().enumerate() {
            if let Some(&old_child_id) = old_children.get(i) {
                // Reconcile existing child
                reconcile_node(
                    tree,
                    old_child_id,
                    new_child_element,
                    state,
                    patches,
                    dependencies,
                    data_sources,
                );
            } else {
                // Create new child
                let new_child_id = create_tree(
                    tree,
                    new_child_element,
                    Some(node_id),
                    state,
                    patches,
                    false,
                    dependencies,
                    data_sources,
                );
                if let Some(node) = tree.get_mut(node_id) {
                    node.children.push_back(new_child_id);
                }
            }
        }

        // Remove extra old children
        if old_children.len() > new_children.len() {
            for old_child_id in old_children.iter().skip(new_children.len()).copied() {
                // Collect all nodes in subtree first (for Remove patches)
                let subtree_ids = collect_subtree_ids(tree, old_child_id);
                for &id in &subtree_ids {
                    patches.push(Patch::remove(id));
                    dependencies.remove_node(id);
                }
                // Remove from parent's children and from tree
                tree.remove_child(node_id, old_child_id);
                tree.remove(old_child_id);
            }
        }
    }
}

/// Reconcile an existing element node against a new Element that has IRNode children.
/// Handles props diffing like `reconcile_node`, but reconciles children as IRNodes
/// to support nested ForEach/When/If.
fn reconcile_element_with_ir_children(
    tree: &mut InstanceTree,
    node_id: NodeId,
    element: &Element,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) {
    let node = tree.get(node_id).cloned();
    if node.is_none() {
        return;
    }
    let node = node.unwrap();

    // If element type changed, replace the entire subtree
    if node.element_type != element.element_type {
        replace_subtree(tree, node_id, &node, element, state, patches, dependencies, data_sources);
        return;
    }

    // Register dependencies
    for value in element.props.values() {
        match value {
            Value::Binding(binding) => {
                dependencies.add_dependency(node_id, binding);
            }
            Value::TemplateString { bindings, .. } => {
                for binding in bindings {
                    dependencies.add_dependency(node_id, binding);
                }
            }
            _ => {}
        }
    }

    // Diff props
    let new_props = resolve_props_full(&element.props, state, None, data_sources);
    let prop_patches = diff_props(node_id, &node.props, &new_props);
    patches.extend(prop_patches);

    // Update node props in tree
    if let Some(n) = tree.get_mut(node_id) {
        n.props = new_props;
        n.raw_props = element.props.clone();
    }

    // Reconcile ir_children as IRNodes
    let old_children = node.children.clone();
    let new_children = &element.ir_children;
    let common = old_children.len().min(new_children.len());

    for (i, child_ir) in new_children.iter().enumerate().take(common) {
        if let Some(&old_child_id) = old_children.get(i) {
            reconcile_ir_node(tree, old_child_id, child_ir, state, patches, dependencies, data_sources);
        }
    }

    // Create new children beyond old count
    for child_ir in &new_children[common..] {
        create_ir_node_tree(
            tree,
            child_ir,
            Some(node_id),
            state,
            patches,
            false,
            dependencies,
            data_sources,
        );
    }

    // Remove surplus old children
    for old_child_id in old_children.iter().skip(new_children.len()).copied() {
        remove_subtree(tree, old_child_id, patches, dependencies);
        if let Some(n) = tree.get_mut(node_id) {
            n.children = n
                .children
                .iter()
                .filter(|&&id| id != old_child_id)
                .copied()
                .collect();
        }
    }
}

/// Replace an entire subtree when element types don't match.
/// This removes the old node and its descendants, then creates a new subtree in its place.
#[allow(clippy::too_many_arguments)]
fn replace_subtree(
    tree: &mut InstanceTree,
    old_node_id: NodeId,
    old_node: &super::InstanceNode,
    new_element: &Element,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) {
    let parent_id = old_node.parent;

    // Remember the position of the old node in its parent's children list
    let old_position = if let Some(pid) = parent_id {
        tree.get(pid)
            .and_then(|parent| parent.children.iter().position(|&id| id == old_node_id))
    } else {
        None
    };

    // Collect all node IDs in the old subtree (depth-first, children before parents)
    let ids_to_remove = collect_subtree_ids(tree, old_node_id);

    // Generate Remove patches and clear dependencies in one pass
    for &id in &ids_to_remove {
        patches.push(Patch::remove(id));
        dependencies.remove_node(id);
    }

    // Remove old node from parent's children list
    if let Some(pid) = parent_id {
        if let Some(parent) = tree.get_mut(pid) {
            parent.children = parent
                .children
                .iter()
                .filter(|&&id| id != old_node_id)
                .copied()
                .collect();
        }
    }

    // Remove the old subtree from the tree
    tree.remove(old_node_id);

    // Create the new subtree
    let is_root = parent_id.is_none();
    let new_node_id = create_tree(
        tree,
        new_element,
        parent_id,
        state,
        patches,
        is_root,
        dependencies,
        data_sources,
    );

    // If this was the root, update it
    if is_root {
        tree.set_root(new_node_id);
    } else if let Some(pid) = parent_id {
        if let Some(pos) = old_position {
            if let Some(parent) = tree.get_mut(pid) {
                let current_len = parent.children.len();
                // create_tree appended at end, so new node is at current_len - 1
                // We want it at position `pos`
                if pos < current_len - 1 {
                    // Pop from end (O(log n) for im::Vector) and insert at correct position
                    let new_id = parent.children.pop_back().unwrap();
                    parent.children.insert(pos, new_id);

                    // Get the next sibling for the Move patch
                    let next_sibling = parent.children.get(pos + 1).copied();
                    patches.push(Patch::move_node(pid, new_node_id, next_sibling));
                }
                // If pos == current_len - 1, it's already in the right place (was last child)
            }
        }
    }
}

/// Collect all node IDs in a subtree (post-order: children before parents)
/// Uses iterative approach to avoid stack overflow on deep trees
fn collect_subtree_ids(tree: &InstanceTree, root_id: NodeId) -> Vec<NodeId> {
    let mut result = Vec::new();
    let mut stack: Vec<(NodeId, bool)> = vec![(root_id, false)];

    while let Some((node_id, children_processed)) = stack.pop() {
        if children_processed {
            // Children already processed, add this node
            result.push(node_id);
        } else {
            // Push self back with flag, then push children
            stack.push((node_id, true));
            if let Some(node) = tree.get(node_id) {
                // Push children in reverse order so they're processed left-to-right
                for &child_id in node.children.iter().rev() {
                    stack.push((child_id, false));
                }
            }
        }
    }

    result
}

/// Diff two sets of props and generate SetProp/RemoveProp patches
pub fn diff_props(
    node_id: NodeId,
    old_props: &IndexMap<String, serde_json::Value>,
    new_props: &IndexMap<String, serde_json::Value>,
) -> Vec<Patch> {
    let mut patches = Vec::new();

    // Check for changed or new props
    for (key, new_value) in new_props {
        if old_props.get(key) != Some(new_value) {
            patches.push(Patch::set_prop(node_id, key.clone(), new_value.clone()));
        }
    }

    // Remove props that exist in old but not in new
    for key in old_props.keys() {
        if !new_props.contains_key(key) {
            patches.push(Patch::remove_prop(node_id, key.clone()));
        }
    }

    patches
}

// ============================================================================
// IRNode-based reconciliation (first-class control flow constructs)
// ============================================================================

/// Create a tree from an IRNode (supports ForEach, When/If, and regular elements)
#[allow(clippy::too_many_arguments)]
pub fn create_ir_node_tree(
    tree: &mut InstanceTree,
    node: &IRNode,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    is_root: bool,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> NodeId {
    match node {
        IRNode::Element(element) => {
            if element.ir_children.is_empty() {
                // No control-flow children — use optimized legacy path
                create_tree(
                    tree,
                    element,
                    parent_id,
                    state,
                    patches,
                    is_root,
                    dependencies,
                    data_sources,
                )
            } else {
                // Has IRNode children (may include ForEach/When/If) — process as IRNodes
                create_element_with_ir_children(
                    tree,
                    element,
                    parent_id,
                    state,
                    patches,
                    is_root,
                    dependencies,
                    data_sources,
                )
            }
        }
        IRNode::ForEach {
            source,
            item_name,
            key_path,
            template,
            props,
        } => {
            let mut ctx = ReconcileCtx {
                tree,
                state,
                patches,
                dependencies,
                data_sources,
            };
            create_foreach_ir_tree(
                &mut ctx,
                source,
                item_name,
                key_path.as_deref(),
                template,
                props,
                node,
                parent_id,
                is_root,
            )
        }
        IRNode::Conditional {
            value,
            branches,
            fallback,
        } => {
            let mut ctx = ReconcileCtx {
                tree,
                state,
                patches,
                dependencies,
                data_sources,
            };
            create_conditional_tree(
                &mut ctx,
                value,
                branches,
                fallback.as_deref(),
                node,
                parent_id,
                is_root,
            )
        }
    }
}

/// Create a tree from an Element that has `ir_children` (IRNode children).
/// This handles elements whose children include control-flow nodes (ForEach, When, If).
/// The element itself is created normally; children are processed as IRNodes.
fn create_element_with_ir_children(
    tree: &mut InstanceTree,
    element: &Element,
    parent_id: Option<NodeId>,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    is_root: bool,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) -> NodeId {
    // Create the element node (same as create_tree)
    let node_id = tree.create_node(element, state);

    // Register dependencies
    for value in element.props.values() {
        match value {
            Value::Binding(binding) => {
                dependencies.add_dependency(node_id, binding);
            }
            Value::TemplateString { bindings, .. } => {
                for binding in bindings {
                    dependencies.add_dependency(node_id, binding);
                }
            }
            _ => {}
        }
    }

    // Generate Create patch
    let node = tree.get(node_id).unwrap();
    patches.push(Patch::create(
        node_id,
        node.element_type.clone(),
        node.props.clone(),
    ));

    // Insert into parent
    if let Some(parent) = parent_id {
        tree.add_child(parent, node_id, None);
        patches.push(Patch::insert(parent, node_id, None));
    } else if is_root {
        patches.push(Patch::insert_root(node_id));
    }

    // Process children as IRNodes (supports ForEach, When, If)
    for child_ir in &element.ir_children {
        create_ir_node_tree(
            tree,
            child_ir,
            Some(node_id),
            state,
            patches,
            false,
            dependencies,
            data_sources,
        );
    }

    node_id
}

/// Create an IRNode tree with separate logical and render parents.
///
/// This is used for control flow children where:
/// - `logical_parent`: Where the node goes in the InstanceTree (the control flow node)
/// - `render_parent`: Where Insert patches should target (the grandparent)
///
/// Control flow nodes are transparent - they exist in the tree for bookkeeping
/// but don't create DOM elements. Their children render directly into the grandparent.
fn create_ir_node_tree_with_render_parent(
    ctx: &mut ReconcileCtx,
    node: &IRNode,
    logical_parent: Option<NodeId>,
    render_parent: Option<NodeId>,
    is_root: bool,
) -> NodeId {
    match node {
        IRNode::Element(element) => {
            // Create element and add to logical parent in tree
            let node_id = ctx.tree.create_node_full(element, ctx.state, ctx.data_sources);

            // Add to logical parent's children list
            if let Some(parent) = logical_parent {
                ctx.tree.add_child(parent, node_id, None);
            }

            // Emit patches targeting the render parent
            ctx.patches.push(Patch::create(
                node_id,
                element.element_type.clone(),
                ctx.tree
                    .get(node_id)
                    .map(|n| n.props.clone())
                    .unwrap_or_default(),
            ));

            if let Some(render_p) = render_parent {
                ctx.patches.push(Patch::insert(render_p, node_id, None));
            } else if is_root {
                ctx.patches.push(Patch::insert_root(node_id));
            }

            // Register dependencies (must match create_tree to survive clear+reconcile)
            for (_, value) in &element.props {
                match value {
                    Value::Binding(binding) => {
                        ctx.dependencies.add_dependency(node_id, binding);
                    }
                    Value::TemplateString { bindings, .. } => {
                        for binding in bindings {
                            ctx.dependencies.add_dependency(node_id, binding);
                        }
                    }
                    _ => {}
                }
            }

            // Recursively create children - they use this node as both logical and render parent
            let children_source: Vec<IRNode> = if !element.ir_children.is_empty() {
                element.ir_children.clone()
            } else {
                element
                    .children
                    .iter()
                    .map(|child| IRNode::Element((**child).clone()))
                    .collect()
            };
            for child_ir in &children_source {
                create_ir_node_tree(
                    ctx.tree,
                    child_ir,
                    Some(node_id),
                    ctx.state,
                    ctx.patches,
                    false,
                    ctx.dependencies,
                    ctx.data_sources,
                );
            }

            node_id
        }
        IRNode::ForEach {
            source,
            item_name,
            key_path,
            template,
            props,
        } => {
            // ForEach within control flow - still uses grandparent for its own children
            create_foreach_ir_tree(
                ctx,
                source,
                item_name,
                key_path.as_deref(),
                template,
                props,
                node,
                logical_parent, // ForEach goes into logical parent
                is_root,
            )
        }
        IRNode::Conditional {
            value,
            branches,
            fallback,
        } => {
            // Nested conditional - also transparent
            create_conditional_tree(
                ctx,
                value,
                branches,
                fallback.as_deref(),
                node,
                logical_parent, // Conditional goes into logical parent
                is_root,
            )
        }
    }
}

/// Create a ForEach iteration tree from IRNode::ForEach
#[allow(clippy::too_many_arguments)]
fn create_foreach_ir_tree(
    ctx: &mut ReconcileCtx,
    source: &Binding,
    item_name: &str,
    key_path: Option<&str>,
    template: &[IRNode],
    props: &Props,
    original_node: &IRNode,
    parent_id: Option<NodeId>,
    is_root: bool,
) -> NodeId {
    // Evaluate the source array binding
    let array = evaluate_binding(source, ctx.state).unwrap_or(serde_json::Value::Array(vec![]));

    // Resolve container props (with data sources for template strings)
    let resolved_props = resolve_props_full(props, ctx.state, None, ctx.data_sources);

    // Create the ForEach container node (internal bookkeeping only - no DOM element)
    let node_id = ctx.tree.create_control_flow_node(
        "__ForEach",
        resolved_props.clone(),
        props.clone(),
        ControlFlowKind::ForEach {
            item_name: item_name.to_string(),
            key_path: key_path.map(|s| s.to_string()),
        },
        original_node.clone(),
    );

    // Register dependency on the source array binding
    ctx.dependencies.add_dependency(node_id, source);

    // Add to parent's children list (for tree structure) but NO patches for the container itself
    // Control flow nodes are transparent - they don't create DOM elements
    if let Some(parent) = parent_id {
        ctx.tree.add_child(parent, node_id, None);
    }

    // Render children for each item in the array
    // Children are inserted into the GRANDPARENT for rendering purposes
    let render_parent = parent_id; // Children render directly into ForEach's parent

    if let serde_json::Value::Array(items) = &array {
        for (index, item) in items.iter().enumerate() {
            let item_key = generate_item_key(item, key_path, item_name, index);

            // Create each template child with item bindings replaced
            for child_template in template {
                let child_with_item = replace_ir_node_item_bindings(
                    child_template,
                    item,
                    index,
                    item_name,
                    &item_key,
                );
                // Children are added to ForEach node in tree, but patches go to grandparent
                create_ir_node_tree_with_render_parent(
                    ctx,
                    &child_with_item,
                    Some(node_id), // logical parent (ForEach)
                    render_parent, // render parent (grandparent)
                    is_root && render_parent.is_none(),
                );
            }
        }
    }

    node_id
}

/// Create a Conditional (When/If) tree from IRNode::Conditional
fn create_conditional_tree(
    ctx: &mut ReconcileCtx,
    value: &Value,
    branches: &[ConditionalBranch],
    fallback: Option<&[IRNode]>,
    original_node: &IRNode,
    parent_id: Option<NodeId>,
    is_root: bool,
) -> NodeId {
    // Evaluate the condition value (with data sources for template string conditions)
    let evaluated_value = evaluate_value(value, ctx.state, ctx.data_sources);

    // Create the Conditional container node (internal bookkeeping only - no DOM element)
    let mut raw_props = Props::new();
    raw_props.insert("__condition".to_string(), value.clone());

    let node_id = ctx.tree.create_control_flow_node(
        "__Conditional",
        IndexMap::new(),
        raw_props,
        ControlFlowKind::Conditional,
        original_node.clone(),
    );

    // Register dependency on the condition binding
    if let Value::Binding(binding) = value {
        ctx.dependencies.add_dependency(node_id, binding);
    } else if let Value::TemplateString { bindings, .. } = value {
        for binding in bindings {
            ctx.dependencies.add_dependency(node_id, binding);
        }
    }

    // Add to parent's children list (for tree structure) but NO patches for the container itself
    // Control flow nodes are transparent - they don't create DOM elements
    if let Some(parent) = parent_id {
        ctx.tree.add_child(parent, node_id, None);
    }

    // Find matching branch (with data sources for pattern matching)
    let matched_children =
        find_matching_branch(&evaluated_value, branches, fallback, ctx.state, ctx.data_sources);

    // Render matched children - insert directly into grandparent for rendering
    let render_parent = parent_id; // Children render directly into Conditional's parent

    if let Some(children) = matched_children {
        for child in children {
            // Children are added to Conditional node in tree, but patches go to grandparent
            create_ir_node_tree_with_render_parent(
                ctx,
                child,
                Some(node_id), // logical parent (Conditional)
                render_parent, // render parent (grandparent)
                is_root && render_parent.is_none(),
            );
        }
    }

    node_id
}

/// Reconcile an existing tree against a new IRNode
pub fn reconcile_ir_node(
    tree: &mut InstanceTree,
    node_id: NodeId,
    node: &IRNode,
    state: &serde_json::Value,
    patches: &mut Vec<Patch>,
    dependencies: &mut DependencyGraph,
    data_sources: Option<&DataSources>,
) {
    let existing_node = tree.get(node_id).cloned();
    if existing_node.is_none() {
        return;
    }
    let existing = existing_node.unwrap();

    match node {
        IRNode::Element(element) => {
            if element.ir_children.is_empty() {
                // No control-flow children — use existing reconciliation
                reconcile_node(tree, node_id, element, state, patches, dependencies, data_sources);
            } else {
                // Has IRNode children (may include ForEach/When/If)
                reconcile_element_with_ir_children(
                    tree, node_id, element, state, patches, dependencies, data_sources,
                );
            }
        }
        IRNode::ForEach {
            source,
            item_name,
            key_path,
            template,
            props: _,
        } => {
            // ForEach reconciliation
            if !existing.is_foreach() {
                // Type mismatch - replace entire subtree
                let parent_id = existing.parent;
                remove_subtree(tree, node_id, patches, dependencies);
                create_ir_node_tree(
                    tree,
                    node,
                    parent_id,
                    state,
                    patches,
                    parent_id.is_none(),
                    dependencies,
                    data_sources,
                );
                return;
            }

            // Re-register dependency on the source array binding (cleared before reconcile)
            dependencies.add_dependency(node_id, source);

            // Re-evaluate the array
            let array = evaluate_binding(source, state).unwrap_or(serde_json::Value::Array(vec![]));

            if let serde_json::Value::Array(items) = &array {
                let old_children = existing.children.clone();
                let expected_children_count = items.len() * template.len();

                // ForEach children should be inserted into the GRANDPARENT (ForEach's parent),
                // not the __ForEach node itself. The __ForEach is a transparent wrapper that
                // renderers don't know about — it's never sent as a CREATE patch.
                // This matches the initial render path in create_foreach_tree which uses
                // `render_parent = parent_id` (the grandparent).
                let render_parent = existing.parent.unwrap_or(node_id);

                // If child count changed, rebuild
                if old_children.len() != expected_children_count {
                    // Remove old children
                    for &old_child_id in &old_children {
                        patches.push(Patch::remove(old_child_id));
                    }

                    if let Some(node) = tree.get_mut(node_id) {
                        node.children.clear();
                    }

                    // Create new children
                    for (index, item) in items.iter().enumerate() {
                        let item_key =
                            generate_item_key(item, key_path.as_deref(), item_name, index);

                        for child_template in template {
                            let child_with_item = replace_ir_node_item_bindings(
                                child_template,
                                item,
                                index,
                                item_name,
                                &item_key,
                            );
                            create_ir_node_tree(
                                tree,
                                &child_with_item,
                                Some(render_parent),
                                state,
                                patches,
                                false,
                                dependencies,
                                data_sources,
                            );
                        }
                    }
                } else {
                    // Reconcile existing children
                    let mut child_index = 0;
                    for (item_index, item) in items.iter().enumerate() {
                        let item_key =
                            generate_item_key(item, key_path.as_deref(), item_name, item_index);

                        for child_template in template {
                            if let Some(&old_child_id) = old_children.get(child_index) {
                                let child_with_item = replace_ir_node_item_bindings(
                                    child_template,
                                    item,
                                    item_index,
                                    item_name,
                                    &item_key,
                                );
                                reconcile_ir_node(
                                    tree,
                                    old_child_id,
                                    &child_with_item,
                                    state,
                                    patches,
                                    dependencies,
                                    data_sources,
                                );
                            }
                            child_index += 1;
                        }
                    }
                }
            }
        }
        IRNode::Conditional {
            value,
            branches,
            fallback,
        } => {
            // Conditional reconciliation
            if !existing.is_conditional() {
                // Type mismatch - replace entire subtree
                let parent_id = existing.parent;
                remove_subtree(tree, node_id, patches, dependencies);
                create_ir_node_tree(
                    tree,
                    node,
                    parent_id,
                    state,
                    patches,
                    parent_id.is_none(),
                    dependencies,
                    data_sources,
                );
                return;
            }

            // Re-register dependency on the condition binding (cleared before reconcile)
            if let Value::Binding(binding) = value {
                dependencies.add_dependency(node_id, binding);
            } else if let Value::TemplateString { bindings, .. } = value {
                for binding in bindings {
                    dependencies.add_dependency(node_id, binding);
                }
            }

            // Re-evaluate the condition (with data sources for proper resolution)
            let evaluated_value = evaluate_value(value, state, data_sources);
            let matched_children =
                find_matching_branch(&evaluated_value, branches, fallback.as_deref(), state, data_sources);

            let old_children = existing.children.clone();
            let old_len = old_children.len();
            // __Conditional nodes are transparent — they have no DOM element.
            // Insert patches for children must target the grandparent (the
            // Conditional's own parent) so the renderer can find a real element.
            let render_parent = existing.parent;

            if let Some(children) = matched_children {
                let new_len = children.len();
                let common = old_len.min(new_len);

                // Reconcile overlapping children (diff reuses DOM nodes where structure matches)
                for (i, child) in children.iter().enumerate().take(common) {
                    if let Some(&old_child_id) = old_children.get(i) {
                        reconcile_ir_node(tree, old_child_id, child, state, patches, dependencies, data_sources);
                    }
                }

                // Remove surplus old children
                for i in common..old_len {
                    if let Some(&old_child_id) = old_children.get(i) {
                        remove_subtree(tree, old_child_id, patches, dependencies);
                        if let Some(cond_node) = tree.get_mut(node_id) {
                            cond_node.children = cond_node
                                .children
                                .iter()
                                .filter(|&&id| id != old_child_id)
                                .copied()
                                .collect();
                        }
                    }
                }

                // Create new children beyond the old count.
                // Use render_parent (grandparent) for Insert patches, matching
                // the initial-render path in create_conditional_tree.
                let mut ctx = ReconcileCtx {
                    tree,
                    state,
                    patches,
                    dependencies,
                    data_sources,
                };
                for child in &children[common..] {
                    create_ir_node_tree_with_render_parent(
                        &mut ctx,
                        child,
                        Some(node_id),   // logical parent (__Conditional)
                        render_parent,   // render parent (grandparent)
                        false,
                    );
                }
            } else {
                // No matched branch - remove all children
                for &old_child_id in &old_children {
                    remove_subtree(tree, old_child_id, patches, dependencies);
                }

                if let Some(cond_node) = tree.get_mut(node_id) {
                    cond_node.children.clear();
                }
            }
        }
    }
}

/// Remove a subtree and generate Remove patches
fn remove_subtree(
    tree: &mut InstanceTree,
    node_id: NodeId,
    patches: &mut Vec<Patch>,
    dependencies: &mut DependencyGraph,
) {
    let ids = collect_subtree_ids(tree, node_id);
    for &id in &ids {
        patches.push(Patch::remove(id));
        dependencies.remove_node(id);
    }
    tree.remove(node_id);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::Value;
    use serde_json::json;

    #[test]
    fn test_create_simple_tree() {
        use crate::reactive::DependencyGraph;

        let mut tree = InstanceTree::new();
        let mut patches = Vec::new();
        let mut dependencies = DependencyGraph::new();

        let element = Element::new("Column")
            .with_child(Element::new("Text").with_prop("text", Value::Static(json!("Hello"))));

        let state = json!({});
        create_tree(
            &mut tree,
            &element,
            None,
            &state,
            &mut patches,
            true,
            &mut dependencies,
            None,
        );

        // Should create 2 nodes (Column + Text) + 2 Inserts (root + child)
        // Create Column, Insert Column into root, Create Text, Insert Text into Column
        assert_eq!(patches.len(), 4);

        // Verify root insert patch exists
        let root_insert = patches
            .iter()
            .find(|p| matches!(p, Patch::Insert { parent_id, .. } if parent_id == "root"));
        assert!(root_insert.is_some(), "Root insert patch should exist");
    }

    #[test]
    fn test_diff_props() {
        let node_id = NodeId::default();
        let old = indexmap::indexmap! {
            "color".to_string() => json!("red"),
            "size".to_string() => json!(16),
        };
        let new = indexmap::indexmap! {
            "color".to_string() => json!("blue"),
            "size".to_string() => json!(16),
        };

        let patches = diff_props(node_id, &old, &new);

        // Only color changed
        assert_eq!(patches.len(), 1);
    }
}