cranpose-ui 0.1.10

UI primitives 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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
//! LazyColumn and LazyRow widget implementations.
//!
//! Provides virtualized scrolling lists that only compose visible items,
//! matching Jetpack Compose's `LazyColumn` and `LazyRow` APIs.

#![allow(non_snake_case)]
#![allow(dead_code)] // Some public widget entry points are exercised by downstream apps.

use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use std::time::Instant;

use crate::composable;
use crate::layout::MeasuredNode;
use crate::modifier::{Modifier, Size};
use crate::subcompose_layout::{
    MeasurePolicy, Placement, SubcomposeChild, SubcomposeLayoutNode, SubcomposeMeasureScope,
    SubcomposeMeasureScopeImpl,
};
use cranpose_core::{NodeId, SlotId};
use cranpose_foundation::lazy::{
    measure_lazy_list, measure_lazy_list_with_beyond_bounds_policy, LazyListIntervalContent,
    LazyListMeasureConfig, LazyListMeasureResult, LazyListMeasuredItem, LazyListState,
    SmallNodeVec, SmallOffsetVec,
};
use cranpose_ui_layout::{Constraints, LinearArrangement, MeasureResult};
use smallvec::SmallVec;

// Re-export from foundation - single source of truth
pub use cranpose_foundation::lazy::{LazyListItemInfo, LazyListLayoutInfo};

const EXPENSIVE_RETAINED_REUSABLE_SLOTS: usize = 128;
const ACTIVE_SCROLL_UNCACHED_BEYOND_BOUNDS_FRONTIER: usize = 4;

#[derive(Clone, Copy)]
struct LazyItemMeasureContext {
    index: usize,
    key_slot_id: u64,
    content_type: Option<u64>,
    is_vertical: bool,
    cross_axis_size: f32,
    measure_start: Instant,
}

/// Specification for LazyColumn layout behavior.
#[derive(Clone, Debug, PartialEq)]
pub struct LazyColumnSpec {
    /// Vertical arrangement for spacing between items.
    pub vertical_arrangement: LinearArrangement,
    /// Content padding before the first item.
    pub content_padding_top: f32,
    /// Content padding after the last item.
    pub content_padding_bottom: f32,
    /// Number of items to compose beyond the visible bounds.
    /// Higher values reduce jank during fast scrolling but use more memory.
    pub beyond_bounds_item_count: usize,
    /// Whether to reverse the layout direction (bottom-to-top).
    pub reverse_layout: bool,
}

impl Default for LazyColumnSpec {
    fn default() -> Self {
        Self {
            vertical_arrangement: LinearArrangement::Start,
            content_padding_top: 0.0,
            content_padding_bottom: 0.0,
            beyond_bounds_item_count: 2,
            reverse_layout: false,
        }
    }
}

impl LazyColumnSpec {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn vertical_arrangement(mut self, arrangement: LinearArrangement) -> Self {
        self.vertical_arrangement = arrangement;
        self
    }

    pub fn content_padding(mut self, top: f32, bottom: f32) -> Self {
        self.content_padding_top = top;
        self.content_padding_bottom = bottom;
        self
    }

    /// Sets uniform content padding for top and bottom.
    pub fn content_padding_all(mut self, padding: f32) -> Self {
        self.content_padding_top = padding;
        self.content_padding_bottom = padding;
        self
    }

    pub fn reverse_layout(mut self, reverse: bool) -> Self {
        self.reverse_layout = reverse;
        self
    }
}

/// Specification for LazyRow layout behavior.
#[derive(Clone, Debug, PartialEq)]
pub struct LazyRowSpec {
    /// Horizontal arrangement for spacing between items.
    pub horizontal_arrangement: LinearArrangement,
    /// Content padding before the first item.
    pub content_padding_start: f32,
    /// Content padding after the last item.
    pub content_padding_end: f32,
    /// Number of items to compose beyond the visible bounds.
    pub beyond_bounds_item_count: usize,
    /// Whether to reverse the layout direction (end-to-start).
    pub reverse_layout: bool,
}

impl Default for LazyRowSpec {
    fn default() -> Self {
        Self {
            horizontal_arrangement: LinearArrangement::Start,
            content_padding_start: 0.0,
            content_padding_end: 0.0,
            beyond_bounds_item_count: 2,
            reverse_layout: false,
        }
    }
}

impl LazyRowSpec {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn horizontal_arrangement(mut self, arrangement: LinearArrangement) -> Self {
        self.horizontal_arrangement = arrangement;
        self
    }

    pub fn content_padding(mut self, start: f32, end: f32) -> Self {
        self.content_padding_start = start;
        self.content_padding_end = end;
        self
    }

    /// Sets uniform content padding for start and end.
    pub fn content_padding_all(mut self, padding: f32) -> Self {
        self.content_padding_start = padding;
        self.content_padding_end = padding;
        self
    }

    pub fn reverse_layout(mut self, reverse: bool) -> Self {
        self.reverse_layout = reverse;
        self
    }
}

struct LazyListItemMeasureInputs<'a> {
    is_vertical: bool,
    cross_axis_size: f32,
    content: &'a LazyListIntervalContent,
    state: &'a LazyListState,
    measured_item_cache: &'a Rc<RefCell<LazyMeasuredItemCache>>,
}

fn measure_lazy_list_item(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    index: usize,
    inputs: &LazyListItemMeasureInputs<'_>,
    retained_measurement_batch: &mut Vec<Rc<MeasuredNode>>,
) -> LazyListMeasuredItem {
    let measure_start = Instant::now();
    let key = inputs.content.get_key(index);
    let key_slot_id = key.to_slot_id();
    let content_type = inputs.content.get_content_type(index);
    let slot_id = SlotId(key_slot_id);
    let item_context = LazyItemMeasureContext {
        index,
        key_slot_id,
        content_type,
        is_vertical: inputs.is_vertical,
        cross_axis_size: inputs.cross_axis_size,
        measure_start,
    };

    scope.update_content_type(slot_id, content_type);

    let cached_candidate = {
        inputs
            .measured_item_cache
            .borrow_mut()
            .candidate(index, key_slot_id, content_type)
    };
    if let Some(cached) = cached_candidate {
        inputs
            .measured_item_cache
            .borrow_mut()
            .record_candidate_hit();
        if let Some((root_children, children_match)) =
            scope.activate_exact_retained_slot_with_known_children(slot_id, &cached.item.node_ids)
        {
            let children_are_clean = !scope.children_need_measure(&root_children);
            if children_match && children_are_clean {
                retained_measurement_batch.extend(cached.retained_children.iter().cloned());
                inputs.measured_item_cache.borrow_mut().record_exact_reuse();
                return cached.item;
            }
            inputs.measured_item_cache.borrow_mut().remove(index);
            if children_match {
                inputs
                    .measured_item_cache
                    .borrow_mut()
                    .record_dirty_children();
            } else {
                inputs.measured_item_cache.borrow_mut().record_exact_miss();
            }
            return measure_lazy_list_children(
                scope,
                root_children,
                inputs.measured_item_cache,
                item_context,
            );
        } else {
            inputs.measured_item_cache.borrow_mut().record_exact_miss();
            inputs.measured_item_cache.borrow_mut().remove(index);
        }
    } else {
        inputs
            .measured_item_cache
            .borrow_mut()
            .record_candidate_miss();
    }

    let Some(item_content) = inputs
        .content
        .with_interval(index, |local_index, interval| {
            let content = Rc::clone(&interval.content);
            move || (content)(local_index)
        })
    else {
        return LazyListMeasuredItem::new(index, key_slot_id, content_type, 1.0, 0.0);
    };
    let root_children = scope.subcompose(slot_id, item_content);

    let was_reused = scope.was_last_slot_reused().unwrap_or(false);
    inputs.state.record_composition(was_reused);

    let root_node_ids: SmallNodeVec = root_children
        .iter()
        .map(|child| child.node_id() as u64)
        .collect();

    if let Some(cached) = inputs.measured_item_cache.borrow_mut().get(
        index,
        key_slot_id,
        content_type,
        &root_node_ids,
    ) {
        if !scope.children_need_measure(&root_children) {
            scope.register_retained_measurements(&cached.retained_children);
            return cached.item;
        }
        inputs.measured_item_cache.borrow_mut().remove(index);
    }

    measure_lazy_list_children(
        scope,
        root_children,
        inputs.measured_item_cache,
        item_context,
    )
}

fn lazy_list_child_constraints(is_vertical: bool, cross_axis_size: f32) -> Constraints {
    if is_vertical {
        Constraints {
            min_width: 0.0,
            max_width: cross_axis_size,
            min_height: 0.0,
            max_height: f32::INFINITY,
        }
    } else {
        Constraints {
            min_width: 0.0,
            max_width: f32::INFINITY,
            min_height: 0.0,
            max_height: cross_axis_size,
        }
    }
}
fn register_visible_lazy_list_child_measurements(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    visible_items: &[LazyListMeasuredItem],
    is_vertical: bool,
    cross_axis_size: f32,
) {
    let child_constraints = lazy_list_child_constraints(is_vertical, cross_axis_size);
    scope.ensure_cached_measurement_node_ids(
        visible_items
            .iter()
            .flat_map(|item| item.node_ids.iter())
            .filter_map(|&node_id| NodeId::try_from(node_id).ok()),
        child_constraints,
    );
}

fn measure_lazy_list_children(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    root_children: Vec<SubcomposeChild>,
    measured_item_cache: &Rc<RefCell<LazyMeasuredItemCache>>,
    context: LazyItemMeasureContext,
) -> LazyListMeasuredItem {
    let child_constraints =
        lazy_list_child_constraints(context.is_vertical, context.cross_axis_size);

    let mut total_main_size: f32 = 0.0;
    let mut max_cross_size: f32 = 0.0;
    let mut node_ids: SmallNodeVec = SmallVec::with_capacity(root_children.len());
    let mut child_offsets: SmallOffsetVec = SmallVec::new();
    let mut retained_children: SmallVec<[Rc<MeasuredNode>; 4]> =
        SmallVec::with_capacity(root_children.len());

    for child in root_children {
        let (placeable, retained) = scope.measure_retained(child, child_constraints);
        let size = retained
            .as_ref()
            .map(|measured| measured.size())
            .unwrap_or_else(|| Size {
                width: placeable.width(),
                height: placeable.height(),
            });
        let (main, cross) = if context.is_vertical {
            (size.height, size.width)
        } else {
            (size.width, size.height)
        };

        child_offsets.push(total_main_size);
        node_ids.push(child.node_id() as u64);
        if let Some(retained) = retained {
            retained_children.push(retained);
        }

        total_main_size += main;
        max_cross_size = max_cross_size.max(cross);
    }

    let main_axis_size = total_main_size.max(1.0);
    let mut item = LazyListMeasuredItem::new(
        context.index,
        context.key_slot_id,
        context.content_type,
        main_axis_size,
        max_cross_size,
    );
    item.node_ids = node_ids;
    item.child_offsets = child_offsets;

    measured_item_cache
        .borrow_mut()
        .insert(item.clone(), retained_children);
    let elapsed = context.measure_start.elapsed();
    if std::env::var_os("CRANPOSE_LAZY_ITEM_TELEMETRY").is_some() {
        log::warn!(
            "[lazy-item-telemetry] index={} children={} main={:.2} cross={:.2} elapsed_ms={:.2}",
            context.index,
            item.node_ids.len(),
            item.main_axis_size,
            item.cross_axis_size,
            elapsed.as_secs_f64() * 1000.0
        );
    }
    measured_item_cache.borrow_mut().record_uncached_measure();
    item
}

fn recycle_forward_skipped_active_slots(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    content: &LazyListIntervalContent,
    first_measured_index: usize,
    scroll_delta: f32,
) -> bool {
    if scroll_delta >= -0.001 || first_measured_index == 0 {
        return false;
    }

    scope.recycle_active_slots_where(|slot_id| {
        content
            .get_index_by_slot_id(slot_id.raw())
            .is_some_and(|index| index < first_measured_index)
    });
    true
}

/// Internal helper to create a lazy list measure policy.
fn measure_lazy_list_internal(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    constraints: Constraints,
    is_vertical: bool,
    content: &LazyListIntervalContent,
    state: &LazyListState,
    config: &LazyListMeasureConfig,
    measured_item_cache: &Rc<RefCell<LazyMeasuredItemCache>>,
) -> MeasureResult {
    let raw_viewport_size = if is_vertical {
        constraints.max_height
    } else {
        constraints.max_width
    };
    let cross_axis_size = if is_vertical {
        constraints.max_width
    } else {
        constraints.max_height
    };

    let items_count = content.item_count();
    let retained_reusable_slots = EXPENSIVE_RETAINED_REUSABLE_SLOTS;
    scope.set_reusable_pool_limits(retained_reusable_slots, retained_reusable_slots);
    measured_item_cache
        .borrow_mut()
        .retain_constraint_scope(is_vertical, cross_axis_size);
    // Scroll position stability: if items were added/removed before the first visible,
    // find the item by key and adjust scroll position (JC's updateScrollPositionIfTheFirstItemWasMoved)
    if items_count > 0 {
        // Scroll position stability: try O(1) range search first, fall back to O(N) global search
        // This matches the performance-optimal pattern: most items are found within the range
        let range = state.nearest_range();
        state.update_scroll_position_if_item_moved(items_count, |slot_id| {
            content
                .get_index_by_slot_id_in_range(slot_id, range.clone())
                .or_else(|| content.get_index_by_slot_id(slot_id))
        });
        // Note: nearest range is automatically updated by scroll_position when index changes
    }

    // Capture scroll delta for direction inference BEFORE measurement consumes it.
    // This is more accurate than comparing first visible index, especially for:
    // - Scrolling within the same item (partial scroll)
    // - Variable height items where scroll offset changes without index change
    let scroll_delta_for_direction = state.peek_scroll_delta();
    let skipped_slots_recycled = Cell::new(false);
    let mut retained_measurement_batch = Vec::new();
    let item_measure_inputs = LazyListItemMeasureInputs {
        is_vertical,
        cross_axis_size,
        content,
        state,
        measured_item_cache,
    };

    // Run the lazy list measurement algorithm
    let measure_item = |index: usize| -> LazyListMeasuredItem {
        if !skipped_slots_recycled.get()
            && recycle_forward_skipped_active_slots(
                scope,
                content,
                index,
                scroll_delta_for_direction,
            )
        {
            skipped_slots_recycled.set(true);
        }
        measure_lazy_list_item(
            scope,
            index,
            &item_measure_inputs,
            &mut retained_measurement_batch,
        )
    };
    let mut measure_item = measure_item;
    let active_scroll = scroll_delta_for_direction.abs() > 0.001;
    let result = if active_scroll {
        let measured_item_cache_for_policy = Rc::clone(measured_item_cache);
        let uncached_beyond_frontier = Cell::new(ACTIVE_SCROLL_UNCACHED_BEYOND_BOUNDS_FRONTIER);
        measure_lazy_list_with_beyond_bounds_policy(
            items_count,
            state,
            raw_viewport_size,
            cross_axis_size,
            config,
            &mut measure_item,
            |index| {
                let key_slot_id = content.get_key(index).to_slot_id();
                let content_type = content.get_content_type(index);
                if measured_item_cache_for_policy.borrow().has_candidate(
                    index,
                    key_slot_id,
                    content_type,
                ) {
                    return true;
                }
                let remaining = uncached_beyond_frontier.get();
                if remaining == 0 {
                    return false;
                }
                uncached_beyond_frontier.set(remaining - 1);
                true
            },
        )
    } else {
        measure_lazy_list(
            items_count,
            state,
            raw_viewport_size,
            cross_axis_size,
            config,
            &mut measure_item,
        )
    };
    if !retained_measurement_batch.is_empty() {
        scope.register_retained_measurements(&retained_measurement_batch);
    }
    register_visible_lazy_list_child_measurements(
        scope,
        &result.visible_items,
        is_vertical,
        cross_axis_size,
    );
    log_lazy_cache_telemetry(&result, measured_item_cache);
    let effective_viewport_size = result.viewport_size;

    // Cache measured item sizes for better scroll estimation
    state.cache_item_sizes(
        result
            .visible_items
            .iter()
            .map(|item| (item.index, item.main_axis_size)),
    );
    // Update stats: count only items WITHIN viewport, not beyond-bounds buffer
    let truly_visible_count = result
        .visible_items
        .iter()
        .filter(|item| {
            // Item is visible if any part of it is within viewport bounds
            let item_end = item.offset + item.main_axis_size;
            item.offset < effective_viewport_size && item_end > 0.0
        })
        .count();
    // Get reusable slot count from SubcomposeState (the single source of truth)
    let in_pool = scope.reusable_slots_count();
    state.update_stats(truly_visible_count, in_pool);

    if !result.visible_items.is_empty() {
        state.record_scroll_direction(scroll_delta_for_direction);
    }

    let resolve_main_axis = |content_size: f32, min: f32, max: f32| {
        if max.is_finite() {
            content_size.clamp(min, max)
        } else {
            content_size.min(effective_viewport_size).max(min)
        }
    };

    // Report size that respects BOTH min and max constraints.
    // - If content < min: expand to min (e.g., fillMaxSize)
    // - If content > max: clamp to max (enables scrolling)
    // - Otherwise: use content size (shrink-wrap)
    let width = if is_vertical {
        cross_axis_size
    } else {
        resolve_main_axis(
            result.total_content_size,
            constraints.min_width,
            constraints.max_width,
        )
    };
    let height = if is_vertical {
        resolve_main_axis(
            result.total_content_size,
            constraints.min_height,
            constraints.max_height,
        )
    } else {
        cross_axis_size
    };

    scope.layout_with_placement_builder(width, height, |placements| {
        push_lazy_list_placements(
            placements,
            &result.visible_items,
            items_count,
            is_vertical,
            effective_viewport_size,
            config,
        );
    })
}

fn get_spacing(arrangement: LinearArrangement) -> f32 {
    match arrangement {
        LinearArrangement::SpacedBy(spacing) => spacing,
        _ => 0.0,
    }
}

fn bind_layout_invalidation_callback(state: LazyListState, list_state_id: usize, node_id: NodeId) {
    let callback_owner =
        cranpose_core::remember(|| Rc::new(RefCell::new(None::<u64>))).with(|cell| cell.clone());
    let app_context_id = crate::render_state::current_app_context_id();
    let callback_id = state.try_register_layout_callback(
        node_id,
        Rc::new(move || {
            let _ = crate::render_state::enter_app_context_by_id(app_context_id, || {
                crate::schedule_layout_repass(node_id);
            });
        }),
    );

    if let Some(previous_id) = callback_owner.replace(callback_id) {
        if Some(previous_id) != callback_id {
            state.remove_invalidate_callback(previous_id);
        }
    }

    cranpose_core::DisposableEffect!((list_state_id, node_id, callback_id), move |scope| {
        scope.on_dispose(move || {
            if let Some(callback_id) = callback_id {
                state.remove_invalidate_callback(callback_id);
            }
        })
    });
}

#[derive(Clone)]
struct LazyListContentHandle(Rc<LazyListIntervalContent>);

impl LazyListContentHandle {
    fn new(content: LazyListIntervalContent) -> Self {
        Self(Rc::new(content))
    }

    fn empty() -> Self {
        Self::new(LazyListIntervalContent::new())
    }

    fn content(&self) -> &LazyListIntervalContent {
        self.0.as_ref()
    }
}

impl PartialEq for LazyListContentHandle {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

const MEASURED_ITEM_CACHE_CAPACITY: usize = 4096;

#[derive(Default)]
struct LazyMeasuredItemCache {
    is_vertical: bool,
    cross_axis_bits: u32,
    telemetry: LazyCacheTelemetry,
    entries: HashMap<usize, CachedLazyMeasuredItem>,
    order: VecDeque<usize>,
}

#[derive(Clone)]
struct CachedLazyMeasuredItem {
    item: LazyListMeasuredItem,
    retained_children: SmallVec<[Rc<MeasuredNode>; 4]>,
}

#[derive(Clone, Copy, Default)]
struct LazyCacheTelemetry {
    candidate_hits: usize,
    candidate_misses: usize,
    exact_reuses: usize,
    exact_misses: usize,
    dirty_children: usize,
    uncached_measures: usize,
}

impl LazyCacheTelemetry {
    fn has_events(self) -> bool {
        self.candidate_hits > 0
            || self.candidate_misses > 0
            || self.exact_reuses > 0
            || self.exact_misses > 0
            || self.dirty_children > 0
            || self.uncached_measures > 0
    }
}

impl LazyMeasuredItemCache {
    fn retain_constraint_scope(&mut self, is_vertical: bool, cross_axis_size: f32) {
        let cross_axis_bits = normalized_axis_bits(cross_axis_size);
        if self.entries.is_empty() {
            self.is_vertical = is_vertical;
            self.cross_axis_bits = cross_axis_bits;
            return;
        }
        if self.is_vertical != is_vertical || self.cross_axis_bits != cross_axis_bits {
            self.clear();
            self.is_vertical = is_vertical;
            self.cross_axis_bits = cross_axis_bits;
        }
    }

    fn clear(&mut self) {
        self.entries.clear();
        self.order.clear();
    }

    fn get(
        &mut self,
        index: usize,
        key: u64,
        content_type: Option<u64>,
        node_ids: &SmallNodeVec,
    ) -> Option<CachedLazyMeasuredItem> {
        let cached = self.entries.get(&index)?;
        if cached.item.key != key
            || cached.item.content_type != content_type
            || cached.item.node_ids != *node_ids
            || cached.retained_children.len() != cached.item.node_ids.len()
        {
            self.entries.remove(&index);
            return None;
        }
        Some(cached.clone())
    }

    fn candidate(
        &mut self,
        index: usize,
        key: u64,
        content_type: Option<u64>,
    ) -> Option<CachedLazyMeasuredItem> {
        let cached = self.entries.get(&index)?;
        if cached.item.key != key
            || cached.item.content_type != content_type
            || cached.retained_children.len() != cached.item.node_ids.len()
        {
            self.entries.remove(&index);
            return None;
        }
        Some(cached.clone())
    }

    fn has_candidate(&self, index: usize, key: u64, content_type: Option<u64>) -> bool {
        self.entries.get(&index).is_some_and(|cached| {
            cached.item.key == key
                && cached.item.content_type == content_type
                && cached.retained_children.len() == cached.item.node_ids.len()
        })
    }

    fn remove(&mut self, index: usize) {
        self.entries.remove(&index);
    }

    fn insert(
        &mut self,
        item: LazyListMeasuredItem,
        retained_children: SmallVec<[Rc<MeasuredNode>; 4]>,
    ) {
        let index = item.index;
        let cached = CachedLazyMeasuredItem {
            item,
            retained_children,
        };
        if self.entries.insert(index, cached).is_none() {
            self.order.push_back(index);
        }
        while self.entries.len() > MEASURED_ITEM_CACHE_CAPACITY {
            let Some(evicted) = self.order.pop_front() else {
                break;
            };
            self.entries.remove(&evicted);
        }
    }

    fn record_candidate_hit(&mut self) {
        self.telemetry.candidate_hits += 1;
    }

    fn record_candidate_miss(&mut self) {
        self.telemetry.candidate_misses += 1;
    }

    fn record_exact_reuse(&mut self) {
        self.telemetry.exact_reuses += 1;
    }

    fn record_exact_miss(&mut self) {
        self.telemetry.exact_misses += 1;
    }

    fn record_dirty_children(&mut self) {
        self.telemetry.dirty_children += 1;
    }

    fn take_telemetry(&mut self) -> LazyCacheTelemetry {
        std::mem::take(&mut self.telemetry)
    }

    fn record_uncached_measure(&mut self) {
        self.telemetry.uncached_measures += 1;
    }
}

fn log_lazy_cache_telemetry(
    result: &LazyListMeasureResult,
    measured_item_cache: &Rc<RefCell<LazyMeasuredItemCache>>,
) {
    if std::env::var_os("CRANPOSE_LAZY_CACHE_TELEMETRY").is_none() {
        return;
    }

    let telemetry = measured_item_cache.borrow_mut().take_telemetry();
    if !telemetry.has_events() {
        return;
    }

    let message = format!(
        "[lazy-cache-telemetry] first={} offset={:.2} visible={} candidate_hits={} candidate_misses={} exact_reuses={} exact_misses={} dirty_children={} uncached_measures={} cache_entries={}",
        result.first_visible_item_index,
        result.first_visible_item_scroll_offset,
        result.visible_items.len(),
        telemetry.candidate_hits,
        telemetry.candidate_misses,
        telemetry.exact_reuses,
        telemetry.exact_misses,
        telemetry.dirty_children,
        telemetry.uncached_measures,
        measured_item_cache.borrow().entries.len(),
    );
    log::warn!("{message}");
    #[cfg(test)]
    eprintln!("{message}");
}

fn normalized_axis_bits(size: f32) -> u32 {
    if size.is_finite() && size >= 0.0 {
        size.to_bits()
    } else {
        f32::INFINITY.to_bits()
    }
}

/// Writes placements for measured lazy list items.
///
/// This helper encapsulates the logic for:
/// - Applying arrangement when all items fit (hasSpareSpace in JC)
/// - Using sequential positioning during scrolling
fn push_lazy_list_placements(
    placements: &mut Vec<Placement>,
    visible_items: &[LazyListMeasuredItem],
    items_count: usize,
    is_vertical: bool,
    viewport_size: f32,
    config: &LazyListMeasureConfig,
) {
    use cranpose_ui_layout::Arrangement;

    placements.clear();
    placements.reserve(visible_items.iter().map(|item| item.node_ids.len()).sum());

    let arrangement = if is_vertical {
        config
            .vertical_arrangement
            .unwrap_or(LinearArrangement::Start)
    } else {
        config
            .horizontal_arrangement
            .unwrap_or(LinearArrangement::Start)
    };

    // Check if we should apply arrangement:
    // 1. All items are visible (visible_items.len() == total items)
    // 2. Content is smaller than viewport (hasSpareSpace)
    // 3. Arrangement is not sequential (Start or SpacedBy)
    let spacing = get_spacing(arrangement);
    let total_item_size: f32 = visible_items.iter().map(|i| i.main_axis_size).sum::<f32>()
        + (items_count.saturating_sub(1) as f32) * spacing;
    // Account for content padding when checking spare space (JC pattern)
    // Clamp to 0.0 to handle edge case where padding exceeds viewport
    let available_main_axis =
        (viewport_size - config.before_content_padding - config.after_content_padding).max(0.0);
    let has_spare_space =
        total_item_size < available_main_axis && visible_items.len() == items_count;
    let should_apply_arrangement = has_spare_space
        && !matches!(
            arrangement,
            LinearArrangement::Start | LinearArrangement::SpacedBy(_)
        );

    if should_apply_arrangement {
        // Apply arrangement to compute final positions
        // JC: density.arrange(mainAxisLayoutSize, sizes, offsets)
        let content_offset = config.before_content_padding;

        let sizes: SmallVec<[f32; 32]> = visible_items.iter().map(|i| i.main_axis_size).collect();
        let mut positions: SmallVec<[f32; 32]> = SmallVec::from_elem(0.0, sizes.len());
        arrangement.arrange(available_main_axis, &sizes, &mut positions);

        for (item, &pos) in visible_items.iter().zip(positions.iter()) {
            for (&nid, &child_offset) in item.node_ids.iter().zip(item.child_offsets.iter()) {
                let node_id: NodeId = nid as NodeId;
                let item_size = item.main_axis_size;

                let placement = if is_vertical {
                    let y = if config.reverse_layout {
                        viewport_size - (content_offset + pos) - item_size + child_offset
                    } else {
                        content_offset + pos + child_offset
                    };
                    Placement::new(node_id, 0.0, y, 0)
                } else {
                    let x = if config.reverse_layout {
                        viewport_size - (content_offset + pos) - item_size + child_offset
                    } else {
                        content_offset + pos + child_offset
                    };
                    Placement::new(node_id, x, 0.0, 0)
                };
                placements.push(placement);
            }
        }
    } else {
        // Use sequential offsets from measurement (scrolling case)
        for item in visible_items {
            for (&nid, &child_offset) in item.node_ids.iter().zip(item.child_offsets.iter()) {
                let node_id: NodeId = nid as NodeId;
                let item_size = item.main_axis_size;

                let placement = if is_vertical {
                    let y = if config.reverse_layout {
                        viewport_size - item.offset - item_size + child_offset
                    } else {
                        item.offset + child_offset
                    };
                    Placement::new(node_id, 0.0, y, 0)
                } else {
                    let x = if config.reverse_layout {
                        viewport_size - item.offset - item_size + child_offset
                    } else {
                        item.offset + child_offset
                    };
                    Placement::new(node_id, x, 0.0, 0)
                };
                placements.push(placement);
            }
        }
    }
}

fn lazy_list_state_identity(state: &LazyListState) -> usize {
    // The remembered state stores its inner payload behind an `Rc`, so this allocation address
    // remains stable for the lifetime of the live state handle and is safe to use as a list key.
    let state_ptr = state.inner_ptr();
    debug_assert!(
        !state_ptr.is_null(),
        "lazy list identity requires a live LazyListState"
    );
    state_ptr as usize
}

fn lazy_list_state_only_recomposition(state: &LazyListState) -> bool {
    cranpose_core::current_recompose_scope_invalidated_only_by(state.reactive_state_ids())
        .unwrap_or(false)
}

/// Internal implementation for LazyColumn that takes pre-built content.
///
/// Users should prefer the DSL-based [`LazyColumn`] function instead.
fn LazyColumnImpl(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: LazyListContentHandle,
) -> NodeId {
    use std::cell::RefCell;

    // Use remember to keep a shared RefCell for content that persists across recompositions
    // This allows updating the content on each recomposition while reusing the same node/policy
    let content_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyListContentHandle::empty())))
            .with(|cell| cell.clone());

    let refresh_content = !lazy_list_state_only_recomposition(&state);
    if refresh_content {
        *content_cell.borrow_mut() = content;
    }

    let config = LazyListMeasureConfig {
        is_vertical: true,
        reverse_layout: spec.reverse_layout,
        before_content_padding: spec.content_padding_top,
        after_content_padding: spec.content_padding_bottom,
        spacing: get_spacing(spec.vertical_arrangement),
        beyond_bounds_item_count: spec.beyond_bounds_item_count,
        vertical_arrangement: Some(spec.vertical_arrangement),
        horizontal_arrangement: None,
    };
    let config_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(config.clone()))).with(|cell| cell.clone());
    let config_changed = {
        let mut current = config_cell.borrow_mut();
        let changed = *current != config;
        if changed {
            *current = config.clone();
        }
        changed
    };
    let measured_item_cache =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyMeasuredItemCache::default())))
            .with(|cache| cache.clone());

    // Create measure policy with stable identity using remember.
    // The policy reads latest values via state references, so it can be memoized.
    let content_for_policy = content_cell.clone();
    let measured_item_cache_for_policy = measured_item_cache.clone();
    let policy: Rc<MeasurePolicy> = cranpose_core::remember(move || {
        let config_ref = config_cell.clone();
        let content_ref = content_for_policy.clone();
        let measured_item_cache = measured_item_cache_for_policy.clone();
        let policy: Rc<MeasurePolicy> = Rc::new(
            move |scope: &mut SubcomposeMeasureScopeImpl<'_>, constraints: Constraints| {
                let content = content_ref.borrow();
                let config = config_ref.borrow().clone();
                measure_lazy_list_internal(
                    scope,
                    constraints,
                    true,
                    content.content(),
                    &state,
                    &config,
                    &measured_item_cache,
                )
            },
        );
        policy
    })
    .with(|p| p.clone());
    let list_state_id = lazy_list_state_identity(&state);

    // Apply clipping and scroll gesture handling to modifier
    let scroll_modifier = modifier
        .clip_to_bounds()
        .lazy_vertical_scroll(state, spec.reverse_layout);

    // Create and register the subcompose layout node with the composer
    let node_id = cranpose_core::with_current_composer(|composer| {
        composer.with_key(&(list_state_id, "LazyColumnNode"), |composer| {
            composer.emit_node({
                let scroll_modifier = scroll_modifier.clone();
                let policy = Rc::clone(&policy);
                move || SubcomposeLayoutNode::with_content_type_policy(scroll_modifier, policy)
            })
        })
    });
    if let Err(err) = cranpose_core::with_node_mut(node_id, |node: &mut SubcomposeLayoutNode| {
        let modifier_changed = !node.modifier().structural_eq(&scroll_modifier);
        if refresh_content || config_changed || modifier_changed {
            node.set_modifier(scroll_modifier.clone());
        }
        node.set_measure_policy(Rc::clone(&policy));
        if refresh_content || config_changed || modifier_changed {
            measured_item_cache.borrow_mut().clear();
            node.request_measure_recompose();
        }
    }) {
        debug_assert!(false, "failed to update LazyColumn node: {err}");
    }
    bind_layout_invalidation_callback(state, list_state_id, node_id);

    node_id
}

/// Internal implementation for LazyRow that takes pre-built content.
///
/// Users should prefer the DSL-based [`LazyRow`] function instead.
fn LazyRowImpl(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyRowSpec,
    content: LazyListContentHandle,
) -> NodeId {
    use std::cell::RefCell;

    // Use remember to keep a shared RefCell for content that persists across recompositions
    let content_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyListContentHandle::empty())))
            .with(|cell| cell.clone());

    let refresh_content = !lazy_list_state_only_recomposition(&state);
    if refresh_content {
        *content_cell.borrow_mut() = content;
    }

    let config = LazyListMeasureConfig {
        is_vertical: false,
        reverse_layout: spec.reverse_layout,
        before_content_padding: spec.content_padding_start,
        after_content_padding: spec.content_padding_end,
        spacing: get_spacing(spec.horizontal_arrangement),
        beyond_bounds_item_count: spec.beyond_bounds_item_count,
        vertical_arrangement: None,
        horizontal_arrangement: Some(spec.horizontal_arrangement),
    };
    let config_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(config.clone()))).with(|cell| cell.clone());
    let config_changed = {
        let mut current = config_cell.borrow_mut();
        let changed = *current != config;
        if changed {
            *current = config.clone();
        }
        changed
    };
    let measured_item_cache =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyMeasuredItemCache::default())))
            .with(|cache| cache.clone());

    // Create measure policy with stable identity using remember.
    let content_for_policy = content_cell.clone();
    let measured_item_cache_for_policy = measured_item_cache.clone();
    let policy: Rc<MeasurePolicy> = cranpose_core::remember(move || {
        let config_ref = config_cell.clone();
        let content_ref = content_for_policy.clone();
        let measured_item_cache = measured_item_cache_for_policy.clone();
        let policy: Rc<MeasurePolicy> = Rc::new(
            move |scope: &mut SubcomposeMeasureScopeImpl<'_>, constraints: Constraints| {
                let content = content_ref.borrow();
                let config = config_ref.borrow().clone();
                measure_lazy_list_internal(
                    scope,
                    constraints,
                    false,
                    content.content(),
                    &state,
                    &config,
                    &measured_item_cache,
                )
            },
        );
        policy
    })
    .with(|p| p.clone());
    let list_state_id = lazy_list_state_identity(&state);

    // Apply clipping and scroll gesture handling to modifier
    let scroll_modifier = modifier
        .clip_to_bounds()
        .lazy_horizontal_scroll(state, spec.reverse_layout);

    // Create and register the subcompose layout node with the composer
    let node_id = cranpose_core::with_current_composer(|composer| {
        composer.with_key(&(list_state_id, "LazyRowNode"), |composer| {
            composer.emit_node({
                let scroll_modifier = scroll_modifier.clone();
                let policy = Rc::clone(&policy);
                move || SubcomposeLayoutNode::with_content_type_policy(scroll_modifier, policy)
            })
        })
    });
    if let Err(err) = cranpose_core::with_node_mut(node_id, |node: &mut SubcomposeLayoutNode| {
        let modifier_changed = !node.modifier().structural_eq(&scroll_modifier);
        if refresh_content || config_changed || modifier_changed {
            node.set_modifier(scroll_modifier.clone());
        }
        node.set_measure_policy(Rc::clone(&policy));
        if refresh_content || config_changed || modifier_changed {
            measured_item_cache.borrow_mut().clear();
            node.request_measure_recompose();
        }
    }) {
        debug_assert!(false, "failed to update LazyRow node: {err}");
    }
    bind_layout_invalidation_callback(state, list_state_id, node_id);

    node_id
}

#[composable]
fn LazyColumnNode(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: LazyListContentHandle,
) -> NodeId {
    cranpose_core::debug_label_current_scope("LazyColumnNode");
    LazyColumnImpl(modifier, state, spec, content)
}

#[composable]
fn LazyRowNode(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyRowSpec,
    content: LazyListContentHandle,
) -> NodeId {
    cranpose_core::debug_label_current_scope("LazyRowNode");
    LazyRowImpl(modifier, state, spec, content)
}

/// A vertically scrolling list that only composes visible items.
///
/// Matches Jetpack Compose's `LazyColumn` API. The closure receives
/// a [`LazyListIntervalContent`] which implements [`LazyListScope`] for defining items.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyColumn(Modifier::empty(), state, LazyColumnSpec::default(), |scope| {
///     // Single header item
///     scope.item(Some(0), None, || {
///         Text("Header", Modifier::empty());
///     });
///
///     // Multiple items from data
///     scope.items(data.len(), Some(|i| data[i].id), None, |i| {
///         Text(data[i].name.clone(), Modifier::empty());
///     });
/// });
/// ```
///
/// For convenience with slices, use the [`LazyListScopeExt`] extension methods:
///
/// ```rust,ignore
/// use cranpose_foundation::lazy::LazyListScopeExt;
///
/// LazyColumn(Modifier::empty(), state, LazyColumnSpec::default(), |scope| {
///     scope.items_slice(&my_data, |item| {
///         Text(item.name.clone(), Modifier::empty());
///     });
/// });
/// ```
/// A vertically scrolling list that only composes and lays out visible items.
///
/// # When to use
/// Use `LazyColumn` for lists with many items (100+) or unknown length.
/// It is much more efficient than using a `Column` with `vertical_scroll` modifier
/// because it recycles nodes and only keeps visible items in memory (virtualization).
///
/// # Arguments
///
/// * `modifier` - Modifiers to apply to the list container.
/// * `state` - The scroll state, used to control scroll position or observe changes.
/// * `spec` - Configuration for content padding, item spacing, and reverse layout.
/// * `content` - A closure that defines the list content using `LazyListScope`.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyColumn(
///     Modifier::fill_max_size(),
///     state,
///     LazyColumnSpec::default(),
///     |scope| {
///         scope.items(1000, None, None, |i| {
///             Text(format!("Item {}", i), Modifier::padding(16.0));
///         });
///     }
/// );
/// ```
pub fn LazyColumn<F>(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: F,
) -> NodeId
where
    F: FnOnce(&mut LazyListIntervalContent),
{
    let mut interval_content = LazyListIntervalContent::new();
    content(&mut interval_content);
    LazyColumnNode(
        modifier,
        state,
        spec,
        LazyListContentHandle::new(interval_content),
    )
}

/// A horizontally scrolling list that only composes visible items.
///
/// Matches Jetpack Compose's `LazyRow` API. The closure receives
/// a [`LazyListIntervalContent`] which implements [`LazyListScope`] for defining items.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyRow(Modifier::empty(), state, LazyRowSpec::default(), |scope| {
///     scope.items(10, None::<fn(usize)->u64>, None::<fn(usize)->u64>, |i| {
///         Text(format!("Item {}", i), Modifier::empty());
///     });
/// });
/// ```
pub fn LazyRow<F>(modifier: Modifier, state: LazyListState, spec: LazyRowSpec, content: F) -> NodeId
where
    F: FnOnce(&mut LazyListIntervalContent),
{
    let mut interval_content = LazyListIntervalContent::new();
    content(&mut interval_content);
    LazyRowNode(
        modifier,
        state,
        spec,
        LazyListContentHandle::new(interval_content),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use cranpose_core::{location_key, Composition, MemoryApplier};

    #[test]
    fn test_lazy_column_spec_default() {
        let spec = LazyColumnSpec::default();
        assert_eq!(spec.vertical_arrangement, LinearArrangement::Start);
        assert_eq!(spec.beyond_bounds_item_count, 2);
    }

    #[test]
    fn test_lazy_column_spec_builder() {
        let spec = LazyColumnSpec::new()
            .vertical_arrangement(LinearArrangement::SpacedBy(8.0))
            .content_padding(16.0, 16.0);

        assert_eq!(spec.vertical_arrangement, LinearArrangement::SpacedBy(8.0));
        assert_eq!(spec.content_padding_top, 16.0);
    }

    #[test]
    fn test_lazy_row_spec_default() {
        let spec = LazyRowSpec::default();
        assert_eq!(spec.horizontal_arrangement, LinearArrangement::Start);
        assert_eq!(spec.beyond_bounds_item_count, 2);
    }

    #[test]
    fn test_get_spacing() {
        assert_eq!(get_spacing(LinearArrangement::Start), 0.0);
        assert_eq!(get_spacing(LinearArrangement::SpacedBy(12.0)), 12.0);
    }

    #[test]
    fn test_content_padding_all() {
        let spec = LazyColumnSpec::new().content_padding_all(24.0);
        assert_eq!(spec.content_padding_top, 24.0);
        assert_eq!(spec.content_padding_bottom, 24.0);
    }

    #[test]
    fn lazy_list_placements_reuse_output_storage() {
        let mut item = LazyListMeasuredItem::new(0, 10, None, 20.0, 50.0);
        item.offset = 7.0;
        item.node_ids.push(101);
        item.node_ids.push(102);
        item.child_offsets.push(0.0);
        item.child_offsets.push(5.0);
        let config = LazyListMeasureConfig {
            is_vertical: true,
            reverse_layout: false,
            before_content_padding: 0.0,
            after_content_padding: 0.0,
            spacing: 0.0,
            beyond_bounds_item_count: 0,
            vertical_arrangement: Some(LinearArrangement::Start),
            horizontal_arrangement: None,
        };
        let mut placements = Vec::with_capacity(8);
        let original_capacity = placements.capacity();

        push_lazy_list_placements(&mut placements, &[item], 1, true, 100.0, &config);

        assert_eq!(placements.len(), 2);
        assert_eq!(placements[0].node_id, 101);
        assert_eq!(placements[0].y, 7.0);
        assert_eq!(placements[1].node_id, 102);
        assert_eq!(placements[1].y, 12.0);
        assert_eq!(placements.capacity(), original_capacity);
    }

    #[test]
    fn lazy_list_placements_retain_offscreen_measured_items_for_renderer_prewarm() {
        let mut hidden = LazyListMeasuredItem::new(0, 10, None, 20.0, 50.0);
        hidden.offset = -40.0;
        hidden.node_ids.push(101);
        hidden.child_offsets.push(0.0);

        let mut partial = LazyListMeasuredItem::new(1, 11, None, 20.0, 50.0);
        partial.offset = -5.0;
        partial.node_ids.push(102);
        partial.child_offsets.push(0.0);

        let config = LazyListMeasureConfig {
            is_vertical: true,
            reverse_layout: false,
            before_content_padding: 0.0,
            after_content_padding: 0.0,
            spacing: 0.0,
            beyond_bounds_item_count: 2,
            vertical_arrangement: Some(LinearArrangement::Start),
            horizontal_arrangement: None,
        };
        let mut placements = Vec::new();

        push_lazy_list_placements(
            &mut placements,
            &[hidden, partial],
            100,
            true,
            100.0,
            &config,
        );

        assert_eq!(placements.len(), 2);
        assert_eq!(placements[0].node_id, 101);
        assert_eq!(placements[0].y, -40.0);
        assert_eq!(placements[1].node_id, 102);
        assert_eq!(placements[1].y, -5.0);
    }

    #[test]
    fn lazy_list_placements_retain_after_viewport_prefetch_items_for_renderer_prewarm() {
        let mut visible = LazyListMeasuredItem::new(0, 10, None, 40.0, 50.0);
        visible.offset = 60.0;
        visible.node_ids.push(101);
        visible.child_offsets.push(0.0);

        let mut warm = LazyListMeasuredItem::new(1, 11, None, 40.0, 50.0);
        warm.offset = 110.0;
        warm.node_ids.push(102);
        warm.child_offsets.push(0.0);

        let mut far = LazyListMeasuredItem::new(2, 12, None, 40.0, 50.0);
        far.offset = 158.0;
        far.node_ids.push(103);
        far.child_offsets.push(0.0);

        let config = LazyListMeasureConfig {
            is_vertical: true,
            reverse_layout: false,
            before_content_padding: 0.0,
            after_content_padding: 0.0,
            spacing: 8.0,
            beyond_bounds_item_count: 8,
            vertical_arrangement: Some(LinearArrangement::SpacedBy(8.0)),
            horizontal_arrangement: None,
        };
        let mut placements = Vec::new();

        push_lazy_list_placements(
            &mut placements,
            &[visible, warm, far],
            100,
            true,
            100.0,
            &config,
        );

        let placed_nodes = placements.iter().map(|p| p.node_id).collect::<Vec<_>>();
        assert_eq!(
            placed_nodes,
            vec![101, 102, 103],
            "prefetch rows remain in the retained placement list so renderers can prewarm clipped content"
        );
    }

    #[test]
    fn lazy_measure_policy_does_not_schedule_speculative_prefetch_frames() {
        let source = include_str!("lazy_list.rs");
        let start = source
            .find("fn measure_lazy_list_internal")
            .expect("measure function exists");
        let end = source[start..]
            .find("fn get_spacing")
            .map(|offset| start + offset)
            .expect("measure function boundary exists");
        let body = &source[start..end];

        assert!(
            !body.contains("prefetch_lazy_list_items")
                && !body.contains("schedule_layout_prewarm_repass"),
            "lazy layout measurement must not schedule speculative frame work"
        );
    }

    #[test]
    fn active_scroll_cached_reuse_validates_retained_children() {
        let source = include_str!("lazy_list.rs");
        let trust_mode = ["TrustClean", "RetainedScrollItem"].concat();
        let trust_api = ["trusting_", "cached_children"].concat();

        assert!(
            !source.contains(trust_mode.as_str()) && !source.contains(trust_api.as_str()),
            "lazy cached reuse must validate retained children during active scroll"
        );
    }

    #[test]
    fn lazy_list_state_identity_is_stable_for_copied_state() {
        let mut composition = Composition::new(MemoryApplier::new());
        let key = location_key(file!(), line!(), column!());
        let mut state = None;
        composition
            .render(key, || {
                state = Some(cranpose_foundation::lazy::remember_lazy_list_state());
            })
            .expect("lazy list state render should succeed");
        let state = state.expect("lazy list state should be captured");
        let copied_state = state;

        assert_ne!(state.inner_ptr(), std::ptr::null());
        assert_eq!(
            lazy_list_state_identity(&state),
            lazy_list_state_identity(&copied_state)
        );
    }
}