cranpose-testing 0.1.14

Testing utilities and harness for Cranpose
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
//! Tests for composition switching bug
//!
//! This test reproduces a bug where switching between different composable views
//! and clicking buttons causes content to be appended multiple times.

use cranpose_core::{compositionLocalOf, CompositionLocalProvider, MutableState};
use cranpose_macros::composable;
use cranpose_testing::ComposeTestRule;
use cranpose_ui::*;

/// Helper to create a simple composable that tracks how many times it's rendered
#[composable]
fn counter_view(counter: MutableState<i32>, render_count: MutableState<i32>) {
    // Track render count
    render_count.set(render_count.get() + 1);

    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        move || {
            Text(
                format!("Counter: {}", counter.get()),
                Modifier::empty().padding(8.0),
                TextStyle::default(),
            );

            Button(
                Modifier::empty().padding(10.0),
                ButtonSpec::default(),
                {
                    move || {
                        counter.set(counter.get() + 1);
                    }
                },
                || {
                    Text(
                        "Increment",
                        Modifier::empty().padding(4.0),
                        TextStyle::default(),
                    );
                },
            );
        },
    );
}

/// Helper for an alternative view
#[composable]
fn alternative_view(counter: MutableState<i32>, render_count: MutableState<i32>) {
    // Track render count
    render_count.set(render_count.get() + 1);

    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        move || {
            Text(
                format!("Alternative: {}", counter.get()),
                Modifier::empty().padding(8.0),
                TextStyle::default(),
            );

            Button(
                Modifier::empty().padding(10.0),
                ButtonSpec::default(),
                {
                    move || {
                        counter.set(counter.get() + 1);
                    }
                },
                || {
                    Text("Add", Modifier::empty().padding(4.0), TextStyle::default());
                },
            );
        },
    );
}

/// Combined app that switches between views
#[composable]
fn combined_switching_app(
    show_counter: MutableState<bool>,
    counter1: MutableState<i32>,
    counter2: MutableState<i32>,
    render_count1: MutableState<i32>,
    render_count2: MutableState<i32>,
) {
    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        move || {
            let show_counter_inner = show_counter;
            let show_counter_for_button1 = show_counter;
            let show_counter_for_button2 = show_counter;
            let counter1_inner = counter1;
            let counter2_inner = counter2;
            let render_count1_inner = render_count1;
            let render_count2_inner = render_count2;

            // Switch buttons
            Row(
                Modifier::empty().padding(8.0),
                RowSpec::default(),
                move || {
                    Button(
                        Modifier::empty().padding(10.0),
                        ButtonSpec::default(),
                        {
                            let show_counter = show_counter_for_button1;
                            move || {
                                show_counter.set(true);
                            }
                        },
                        || {
                            Text(
                                "Counter View",
                                Modifier::empty().padding(4.0),
                                TextStyle::default(),
                            );
                        },
                    );

                    Spacer(Size {
                        width: 8.0,
                        height: 0.0,
                    });

                    Button(
                        Modifier::empty().padding(10.0),
                        ButtonSpec::default(),
                        {
                            let show_counter = show_counter_for_button2;
                            move || {
                                show_counter.set(false);
                            }
                        },
                        || {
                            Text(
                                "Alternative View",
                                Modifier::empty().padding(4.0),
                                TextStyle::default(),
                            );
                        },
                    );
                },
            );

            Spacer(Size {
                width: 0.0,
                height: 12.0,
            });

            // Conditionally show one view or the other
            if show_counter_inner.get() {
                counter_view(counter1_inner, render_count1_inner);
            } else {
                alternative_view(counter2_inner, render_count2_inner);
            }
        },
    );
}

#[test]
fn test_switching_between_views_doesnt_duplicate_content() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_counter = MutableState::with_runtime(true, runtime.clone());
    let counter1 = MutableState::with_runtime(0, runtime.clone());
    let counter2 = MutableState::with_runtime(0, runtime.clone());
    let render_count1 = MutableState::with_runtime(0, runtime.clone());
    let render_count2 = MutableState::with_runtime(0, runtime.clone());

    // Initial render - show counter view
    rule.set_content({
        move || {
            combined_switching_app(
                show_counter,
                counter1,
                counter2,
                render_count1,
                render_count2,
            );
        }
    })
    .expect("initial render succeeds");

    let initial_node_count = rule.applier_mut().len();
    println!("Initial node count: {}", initial_node_count);
    println!("Counter view render count: {}", render_count1.get());
    assert_eq!(
        render_count1.get(),
        1,
        "Counter view should render once initially"
    );
    assert_eq!(
        render_count2.get(),
        0,
        "Alternative view should not render initially"
    );

    // Switch to alternative view
    show_counter.set(false);
    rule.pump_until_idle().expect("recompose after switching");

    let after_switch_node_count = rule.applier_mut().len();
    println!("After switch node count: {}", after_switch_node_count);
    println!("Alternative view render count: {}", render_count2.get());
    assert_eq!(
        render_count1.get(),
        1,
        "Counter view should still have 1 render"
    );
    assert_eq!(
        render_count2.get(),
        1,
        "Alternative view should render once"
    );

    // Switch back to counter view
    show_counter.set(true);
    rule.pump_until_idle()
        .expect("recompose after switching back");

    let after_switch_back_node_count = rule.applier_mut().len();
    println!(
        "After switch back node count: {}",
        after_switch_back_node_count
    );
    println!(
        "Counter view render count after switch back: {}",
        render_count1.get()
    );

    // The bug: if content is being duplicated, node count will grow
    assert_eq!(
        after_switch_back_node_count, initial_node_count,
        "Node count should return to initial value after switching back"
    );
    assert_eq!(
        render_count2.get(),
        1,
        "Switching back should not re-render the alternative view"
    );

    // Click increment button twice in counter view
    counter1.set(1);
    rule.pump_until_idle()
        .expect("recompose after first increment");
    let after_first_click = rule.applier_mut().len();
    println!("After first increment node count: {}", after_first_click);

    counter1.set(2);
    rule.pump_until_idle()
        .expect("recompose after second increment");
    let after_second_click = rule.applier_mut().len();
    println!("After second increment node count: {}", after_second_click);

    // Node count should remain stable
    assert_eq!(
        after_first_click, after_switch_back_node_count,
        "Node count should not change on first increment"
    );
    assert_eq!(
        after_second_click, after_switch_back_node_count,
        "Node count should not change on second increment"
    );

    // Switch to alternative view again
    show_counter.set(false);
    rule.pump_until_idle()
        .expect("recompose after switching to alternative");
    let after_second_switch = rule.applier_mut().len();
    println!("After second switch node count: {}", after_second_switch);

    // Click increment button twice in alternative view
    counter2.set(1);
    rule.pump_until_idle().expect("recompose after first add");
    let after_first_add = rule.applier_mut().len();
    println!("After first add node count: {}", after_first_add);

    counter2.set(2);
    rule.pump_until_idle().expect("recompose after second add");
    let after_second_add = rule.applier_mut().len();
    println!("After second add node count: {}", after_second_add);

    // Node count should remain stable
    assert_eq!(
        after_first_add, after_second_switch,
        "Node count should not change on first add"
    );
    assert_eq!(
        after_second_add, after_second_switch,
        "Node count should not change on second add"
    );

    // Final check: switch back and verify no duplication
    show_counter.set(true);
    rule.pump_until_idle().expect("final recompose");
    let final_node_count = rule.applier_mut().len();
    println!("Final node count: {}", final_node_count);

    assert_eq!(
        final_node_count, initial_node_count,
        "Final node count should match initial - no content duplication"
    );
}

#[test]
fn test_node_cleanup_on_view_switch() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_first = MutableState::with_runtime(true, runtime.clone());

    rule.set_content({
        move || {
            let show_first_inner = show_first;
            Column(
                Modifier::empty().padding(20.0),
                ColumnSpec::default(),
                move || {
                    if show_first_inner.get() {
                        // First view with 3 text nodes
                        Text("First A", Modifier::empty(), TextStyle::default());
                        Text("First B", Modifier::empty(), TextStyle::default());
                        Text("First C", Modifier::empty(), TextStyle::default());
                    } else {
                        // Second view with 2 text nodes
                        Text("Second A", Modifier::empty(), TextStyle::default());
                        Text("Second B", Modifier::empty(), TextStyle::default());
                    }
                },
            );
        }
    })
    .expect("initial render succeeds");

    // Count nodes: 1 Column + 3 Text = 4
    let initial_count = rule.applier_mut().len();
    println!("Initial node count (first view): {}", initial_count);
    assert_eq!(initial_count, 4, "Should have Column + 3 Text nodes");

    // Switch to second view
    show_first.set(false);
    rule.pump_until_idle().expect("recompose after switch");

    // Count nodes: 1 Column + 2 Text = 3
    let after_switch = rule.applier_mut().len();
    println!("Node count after switch (second view): {}", after_switch);
    assert_eq!(after_switch, 3, "Should have Column + 2 Text nodes");

    // Switch back to first view
    show_first.set(true);
    rule.pump_until_idle().expect("recompose after switch back");

    let after_switch_back = rule.applier_mut().len();
    println!(
        "Node count after switch back (first view): {}",
        after_switch_back
    );
    assert_eq!(
        after_switch_back, initial_count,
        "Should return to initial node count"
    );

    // Multiple rapid switches
    for i in 0..5 {
        show_first.set(i % 2 == 0);
        rule.pump_until_idle()
            .unwrap_or_else(|_| panic!("recompose on switch {}", i));
        let count = rule.applier_mut().len();
        let expected = if i % 2 == 0 { 4 } else { 3 };
        assert_eq!(
            count, expected,
            "Node count should be correct after rapid switch {}",
            i
        );
    }
}

#[test]
fn test_multiple_switches_with_state_changes() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_view_a = MutableState::with_runtime(true, runtime.clone());
    let counter_a = MutableState::with_runtime(0, runtime.clone());
    let counter_b = MutableState::with_runtime(0, runtime.clone());

    rule.set_content({
        move || {
            let show_view_a_inner = show_view_a;
            let counter_a_inner = counter_a;
            let counter_b_inner = counter_b;
            Column(Modifier::empty(), ColumnSpec::default(), move || {
                if show_view_a_inner.get() {
                    Text(
                        format!("View A: {}", counter_a_inner.get()),
                        Modifier::empty(),
                        TextStyle::default(),
                    );
                    Button(
                        Modifier::empty(),
                        ButtonSpec::default(),
                        {
                            let counter_a = counter_a_inner;
                            move || counter_a.set(counter_a.get() + 1)
                        },
                        || {
                            Text("Increment A", Modifier::empty(), TextStyle::default());
                        },
                    );
                } else {
                    Text(
                        format!("View B: {}", counter_b_inner.get()),
                        Modifier::empty(),
                        TextStyle::default(),
                    );
                    Button(
                        Modifier::empty(),
                        ButtonSpec::default(),
                        {
                            let counter_b = counter_b_inner;
                            move || counter_b.set(counter_b.get() + 1)
                        },
                        || {
                            Text("Increment B", Modifier::empty(), TextStyle::default());
                        },
                    );
                }
            });
        }
    })
    .expect("initial render succeeds");

    let baseline_count = rule.applier_mut().len();
    println!("Baseline node count: {}", baseline_count);

    // Reproduce the exact scenario from the bug report:
    // 1. Start in View A (Counter APP)
    // 2. Switch to View B (CompositionLocal Test)
    // 3. Click button in View B twice
    // 4. Switch back to View A
    // 5. Click button in View A twice
    // Expected: No node duplication at any point

    // Step 1: We're already in View A
    assert_eq!(counter_a.get(), 0);

    // Step 2: Switch to View B
    show_view_a.set(false);
    rule.pump_until_idle().expect("switch to view B");
    let after_switch_to_b = rule.applier_mut().len();
    println!("After switch to View B: {}", after_switch_to_b);
    assert_eq!(
        after_switch_to_b, baseline_count,
        "Node count should be same (both views have same structure)"
    );

    // Step 3: Click button twice in View B
    counter_b.set(counter_b.get() + 1);
    rule.pump_until_idle().expect("first click in view B");
    let after_first_click_b = rule.applier_mut().len();
    println!("After first click in View B: {}", after_first_click_b);
    assert_eq!(counter_b.get(), 1);

    counter_b.set(counter_b.get() + 1);
    rule.pump_until_idle().expect("second click in view B");
    let after_second_click_b = rule.applier_mut().len();
    println!("After second click in View B: {}", after_second_click_b);
    assert_eq!(counter_b.get(), 2);

    // This is where the bug might manifest - content appended twice
    assert_eq!(
        after_second_click_b, baseline_count,
        "BUG: Content should not be duplicated after two clicks in View B"
    );

    // Step 4: Switch back to View A
    show_view_a.set(true);
    rule.pump_until_idle().expect("switch back to view A");
    let after_switch_to_a = rule.applier_mut().len();
    println!("After switch back to View A: {}", after_switch_to_a);
    assert_eq!(
        after_switch_to_a, baseline_count,
        "Node count should return to baseline after switching back"
    );

    // Step 5: Click button twice in View A
    counter_a.set(counter_a.get() + 1);
    rule.pump_until_idle().expect("first click in view A");
    let after_first_click_a = rule.applier_mut().len();
    println!("After first click in View A: {}", after_first_click_a);
    assert_eq!(counter_a.get(), 1);

    counter_a.set(counter_a.get() + 1);
    rule.pump_until_idle().expect("second click in view A");
    let after_second_click_a = rule.applier_mut().len();
    println!("After second click in View A: {}", after_second_click_a);
    assert_eq!(counter_a.get(), 2);

    // Final verification: no duplication
    assert_eq!(
        after_second_click_a, baseline_count,
        "BUG: Content should not be duplicated after two clicks in View A"
    );
}

#[test]
fn test_deeply_nested_conditional_switching() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_outer = MutableState::with_runtime(true, runtime.clone());
    let show_inner = MutableState::with_runtime(true, runtime.clone());

    rule.set_content({
        move || {
            let show_outer_inner = show_outer;
            let show_inner_inner = show_inner;
            Column(Modifier::empty(), ColumnSpec::default(), move || {
                if show_outer_inner.get() {
                    let show_inner_for_column = show_inner_inner;
                    Column(Modifier::empty(), ColumnSpec::default(), move || {
                        if show_inner_for_column.get() {
                            Text("Outer A, Inner A", Modifier::empty(), TextStyle::default());
                            Text("Nested content A", Modifier::empty(), TextStyle::default());
                        } else {
                            Text("Outer A, Inner B", Modifier::empty(), TextStyle::default());
                        }
                    });
                } else {
                    Text("Outer B", Modifier::empty(), TextStyle::default());
                }
            });
        }
    })
    .expect("initial render succeeds");

    // Initial: outer=true, inner=true -> 1 root + 1 nested column + 2 texts = 4
    let initial = rule.applier_mut().len();
    assert_eq!(initial, 4, "Should have nested structure");

    // Switch inner: outer=true, inner=false -> 1 root + 1 nested column + 1 text = 3
    show_inner.set(false);
    rule.pump_until_idle().expect("switch inner");
    let after_inner_switch = rule.applier_mut().len();
    assert_eq!(
        after_inner_switch, 3,
        "Should have fewer nodes after inner switch"
    );

    // Switch outer: outer=false -> 1 root + 1 text = 2
    show_outer.set(false);
    rule.pump_until_idle().expect("switch outer");
    let after_outer_switch = rule.applier_mut().len();
    assert_eq!(after_outer_switch, 2, "Should have minimal nodes");

    // Switch back to initial state
    show_outer.set(true);
    show_inner.set(true);
    rule.pump_until_idle().expect("restore initial");
    let restored = rule.applier_mut().len();
    assert_eq!(restored, initial, "Should restore original node count");
}

#[test]
fn test_switching_with_different_node_counts() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let view_type = MutableState::with_runtime(0, runtime.clone());

    rule.set_content({
        move || {
            let view_type_inner = view_type;
            Column(Modifier::empty(), ColumnSpec::default(), move || {
                match view_type_inner.get() {
                    0 => {
                        // View with 1 node
                        Text("Single", Modifier::empty(), TextStyle::default());
                    }
                    1 => {
                        // View with 3 nodes
                        Text("Triple 1", Modifier::empty(), TextStyle::default());
                        Text("Triple 2", Modifier::empty(), TextStyle::default());
                        Text("Triple 3", Modifier::empty(), TextStyle::default());
                    }
                    2 => {
                        // View with 5 nodes including nested structure
                        Column(Modifier::empty(), ColumnSpec::default(), || {
                            Text("Nested 1", Modifier::empty(), TextStyle::default());
                            Text("Nested 2", Modifier::empty(), TextStyle::default());
                        });
                        Text("Extra", Modifier::empty(), TextStyle::default());
                    }
                    _ => {}
                }
            });
        }
    })
    .expect("initial render succeeds");

    // View 0: 1 root + 1 text = 2
    let count0 = rule.applier_mut().len();
    assert_eq!(count0, 2);

    // Switch to View 1: 1 root + 3 texts = 4
    view_type.set(1);
    rule.pump_until_idle().expect("switch to view 1");
    let count1 = rule.applier_mut().len();
    assert_eq!(count1, 4);

    // Switch to View 2: 1 root + 1 nested column + 2 texts + 1 extra text = 5
    view_type.set(2);
    rule.pump_until_idle().expect("switch to view 2");
    let count2 = rule.applier_mut().len();
    assert_eq!(count2, 5);

    // Switch back to View 0
    view_type.set(0);
    rule.pump_until_idle().expect("switch back to view 0");
    let count0_again = rule.applier_mut().len();
    assert_eq!(count0_again, count0, "Should return to original count");

    // Cycle through all views multiple times
    for _ in 0..3 {
        view_type.set(1);
        rule.pump_until_idle().expect("cycle: view 1");
        assert_eq!(rule.applier_mut().len(), 4);

        view_type.set(2);
        rule.pump_until_idle().expect("cycle: view 2");
        assert_eq!(rule.applier_mut().len(), 5);

        view_type.set(0);
        rule.pump_until_idle().expect("cycle: view 0");
        assert_eq!(rule.applier_mut().len(), 2);
    }
}

#[test]
fn test_conditional_with_complex_button_structure() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_first = MutableState::with_runtime(true, runtime.clone());
    let counter = MutableState::with_runtime(0, runtime.clone());

    rule.set_content({
        move || {
            let show_first_inner = show_first;
            let counter_inner = counter;
            Column(Modifier::empty(), ColumnSpec::default(), move || {
                if show_first_inner.get() {
                    // Complex structure with nested buttons
                    Column(Modifier::empty(), ColumnSpec::default(), {
                        let counter = counter_inner;
                        move || {
                            Text("First View", Modifier::empty(), TextStyle::default());
                            Button(
                                Modifier::empty(),
                                ButtonSpec::default(),
                                move || counter.set(counter.get() + 1),
                                || {
                                    Text("Button 1", Modifier::empty(), TextStyle::default());
                                },
                            );
                            Button(
                                Modifier::empty(),
                                ButtonSpec::default(),
                                move || counter.set(counter.get() + 10),
                                || {
                                    Text("Button 2", Modifier::empty(), TextStyle::default());
                                },
                            );
                        }
                    });
                } else {
                    // Different structure
                    Text("Second View", Modifier::empty(), TextStyle::default());
                    Button(
                        Modifier::empty(),
                        ButtonSpec::default(),
                        {
                            let counter = counter_inner;
                            move || counter.set(counter.get() - 1)
                        },
                        || {
                            Text("Decrement", Modifier::empty(), TextStyle::default());
                        },
                    );
                }
            });
        }
    })
    .expect("initial render succeeds");

    // First view: 1 root + 1 nested column + 1 text + 2 buttons (each with 1 text child) = 7
    // (root Column, nested Column, Text, Button1, Button1's Text, Button2, Button2's Text)
    let initial = rule.applier_mut().len();
    println!("Initial node count: {}", initial);
    assert_eq!(initial, 7);

    // Interact with first view
    counter.set(5);
    rule.pump_until_idle().expect("update counter");
    assert_eq!(
        rule.applier_mut().len(),
        initial,
        "Node count stable after state change"
    );

    // Switch to second view: 1 root + 1 text + 1 button (with 1 text child) = 4
    show_first.set(false);
    rule.pump_until_idle().expect("switch to second");
    let after_switch = rule.applier_mut().len();
    assert_eq!(after_switch, 4);

    // Interact with second view
    counter.set(3);
    rule.pump_until_idle()
        .expect("update counter in second view");
    assert_eq!(
        rule.applier_mut().len(),
        after_switch,
        "Node count stable in second view"
    );

    // Switch back to first view
    show_first.set(true);
    rule.pump_until_idle().expect("switch back to first");
    let restored = rule.applier_mut().len();
    assert_eq!(
        restored, initial,
        "Should restore original complex structure"
    );
}

#[test]
fn test_clicking_same_switch_button_twice_no_duplication() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    // This test reproduces the bug where clicking the "CompositionLocal Test" button
    // twice causes content duplication
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let show_counter = MutableState::with_runtime(true, runtime.clone());

    rule.set_content({
        move || {
            let show_counter_copy = show_counter;
            let show_counter_for_button = show_counter;
            Column(Modifier::empty(), ColumnSpec::default(), move || {
                // Row with switching buttons
                Row(Modifier::empty(), RowSpec::default(), {
                    let show_counter = show_counter_for_button;
                    move || {
                        let show_counter_for_btn1 = show_counter;
                        let show_counter_for_btn2 = show_counter;

                        Button(
                            Modifier::empty(),
                            ButtonSpec::default(),
                            move || show_counter_for_btn1.set(true),
                            || {
                                Text("Counter App", Modifier::empty(), TextStyle::default());
                            },
                        );

                        Button(
                            Modifier::empty(),
                            ButtonSpec::default(),
                            move || show_counter_for_btn2.set(false),
                            || {
                                Text(
                                    "CompositionLocal Test",
                                    Modifier::empty(),
                                    TextStyle::default(),
                                );
                            },
                        );
                    }
                });

                // Conditional content
                if show_counter_copy.get() {
                    Column(Modifier::empty(), ColumnSpec::default(), || {
                        Text("Counter View", Modifier::empty(), TextStyle::default());
                        Text("Line 2", Modifier::empty(), TextStyle::default());
                    });
                } else {
                    Column(Modifier::empty(), ColumnSpec::default(), || {
                        Text(
                            "CompositionLocal Subscription Test",
                            Modifier::empty(),
                            TextStyle::default(),
                        );
                        Text("Counter: 0", Modifier::empty(), TextStyle::default());
                        Text("Extra content", Modifier::empty(), TextStyle::default());
                    });
                }
            });
        }
    })
    .expect("initial render succeeds");

    // Initial: root Column + Row with 2 Buttons (each with 1 Text) + nested Column + 2 Texts
    // = 1 + 1 + 2 + 2 + 1 + 2 = 9
    let initial = rule.applier_mut().len();
    println!("Initial node count (Counter View): {}", initial);

    // Click "CompositionLocal Test" button once
    show_counter.set(false);
    rule.pump_until_idle()
        .expect("first switch to composition local");
    let after_first_click = rule.applier_mut().len();
    println!(
        "After first click to CompositionLocal: {}",
        after_first_click
    );
    // Should be: 1 + 1 + 2 + 2 + 1 + 3 = 10
    assert_eq!(
        after_first_click, 10,
        "Node count changes due to different content"
    );

    // Click "CompositionLocal Test" button AGAIN (should be no-op since already showing that view)
    show_counter.set(false);
    rule.pump_until_idle()
        .expect("second click on composition local");
    let after_second_click = rule.applier_mut().len();
    println!(
        "After second click to CompositionLocal: {}",
        after_second_click
    );
    println!("\n=== Tree structure after second click ===");
    println!("{}", rule.dump_tree());

    // BUG: This is where duplication might happen
    assert_eq!(
        after_second_click, after_first_click,
        "BUG: Clicking the same button twice should not duplicate content"
    );

    // Switch to Counter App
    show_counter.set(true);
    rule.pump_until_idle().expect("switch to counter app");
    let after_switch_to_counter = rule.applier_mut().len();
    println!("After switch to Counter App: {}", after_switch_to_counter);
    assert_eq!(
        after_switch_to_counter, initial,
        "Should return to initial count"
    );

    // Click Counter App button again
    show_counter.set(true);
    rule.pump_until_idle().expect("second click on counter app");
    let after_second_counter_click = rule.applier_mut().len();
    println!(
        "After second click to Counter App: {}",
        after_second_counter_click
    );
    assert_eq!(
        after_second_counter_click, after_switch_to_counter,
        "Clicking Counter App button twice should not duplicate"
    );
}

#[composable]
fn test_composition_local_content_inner(local_holder: cranpose_core::CompositionLocal<i32>) {
    let value = local_holder.current();
    Text(
        format!("READING local: count={}", value),
        Modifier::empty().padding(8.0),
        TextStyle::default(),
    );
}

#[composable]
fn test_composition_local_content(local_holder: cranpose_core::CompositionLocal<i32>) {
    Text(
        "Outside provider (NOT reading)",
        Modifier::empty().padding(8.0),
        TextStyle::default(),
    );

    Spacer(Size {
        width: 0.0,
        height: 8.0,
    });

    test_composition_local_content_inner(local_holder.clone());

    Spacer(Size {
        width: 0.0,
        height: 8.0,
    });

    Text(
        "NOT reading local",
        Modifier::empty().padding(8.0),
        TextStyle::default(),
    );
}

#[composable]
fn test_composition_local_demo(
    counter: MutableState<i32>,
    local_holder: cranpose_core::CompositionLocal<i32>,
) {
    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        move || {
            Text(
                "CompositionLocal Subscription Test",
                Modifier::empty().padding(8.0),
                TextStyle::default(),
            );

            Spacer(Size {
                width: 0.0,
                height: 12.0,
            });

            Text(
                format!("Counter: {}", counter.get()),
                Modifier::empty().padding(8.0),
                TextStyle::default(),
            );

            Spacer(Size {
                width: 0.0,
                height: 12.0,
            });

            Button(
                Modifier::empty().padding(10.0),
                ButtonSpec::default(),
                {
                    move || {
                        counter.set(counter.get() + 1);
                    }
                },
                || {
                    Text(
                        "Increment",
                        Modifier::empty().padding(4.0),
                        TextStyle::default(),
                    );
                },
            );

            Spacer(Size {
                width: 0.0,
                height: 12.0,
            });

            let current_count = counter.get();
            CompositionLocalProvider(vec![local_holder.provides(current_count)], {
                let local_holder = local_holder.clone();
                move || {
                    test_composition_local_content(local_holder.clone());
                }
            });
        },
    );
}

#[test]
fn composition_local_increment_keeps_node_count_stable() {
    let _app_context = cranpose_ui::AppContext::new();
    let _app_context_scope = _app_context.enter_scope();
    _app_context.enter(cranpose_ui::reset_render_state_for_tests);
    let mut rule = ComposeTestRule::new();
    let runtime = rule.runtime_handle();

    let counter = MutableState::with_runtime(0, runtime.clone());
    let local_holder = compositionLocalOf(|| 0);

    rule.set_content({
        let local_holder = local_holder.clone();
        move || {
            test_composition_local_demo(counter, local_holder.clone());
        }
    })
    .expect("initial render succeeds");

    let initial_nodes = rule.applier_mut().len();

    for step in 1..=2 {
        counter.set(counter.get() + 1);
        rule.pump_until_idle()
            .unwrap_or_else(|_| panic!("pump after increment {}", step));
        let nodes = rule.applier_mut().len();
        assert_eq!(
            nodes, initial_nodes,
            "node count should stay stable after increment {}",
            step
        );
    }
}

#[composable]
fn composable_view_a() {
    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        || {
            Text("View A - Line 1", Modifier::empty(), TextStyle::default());
            Text("View A - Line 2", Modifier::empty(), TextStyle::default());
            Button(
                Modifier::empty(),
                ButtonSpec::default(),
                || {},
                || {
                    Text("Button A", Modifier::empty(), TextStyle::default());
                },
            );
        },
    );
}

#[composable]
fn composable_view_b() {
    Column(
        Modifier::empty().padding(20.0),
        ColumnSpec::default(),
        || {
            Text("View B - Line 1", Modifier::empty(), TextStyle::default());
            Text("View B - Line 2", Modifier::empty(), TextStyle::default());
            Text("View B - Line 3", Modifier::empty(), TextStyle::default());
            Button(
                Modifier::empty(),
                ButtonSpec::default(),
                || {},
                || {
                    Text("Button B", Modifier::empty(), TextStyle::default());
                },
            );
        },
    );
}