dioxus-motion 0.3.5

Animations library for Dioxus.
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
//! Memory pool management for Dioxus Motion optimizations
//!
//! This module provides pooling systems to reduce memory allocations in hot paths
//! of the animation system, particularly for configuration objects and other
//! frequently allocated structures.

use crate::animations::core::{Animatable, AnimationConfig};
use crate::animations::spring::Spring;
use std::collections::HashMap;

use std::any::{Any, TypeId};
use std::cell::RefCell;

/// A pool for reusing AnimationConfig instances to reduce allocations
pub struct ConfigPool {
    available: Vec<AnimationConfig>,
    in_use: HashMap<usize, AnimationConfig>,
    next_id: usize,
}

impl ConfigPool {
    /// Creates a new config pool with default capacity
    pub fn new() -> Self {
        Self::with_capacity(16)
    }

    /// Creates a new config pool with specified initial capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            available: Vec::with_capacity(capacity),
            in_use: HashMap::with_capacity(capacity),
            next_id: 0,
        }
    }

    /// Gets a config from the pool, creating a new one if none available
    pub fn get_config(&mut self) -> ConfigHandle {
        let config = self.available.pop().unwrap_or_default();
        let id = self.next_id;
        self.next_id += 1;
        self.in_use.insert(id, config);

        ConfigHandle { id, valid: true }
    }

    /// Returns a config to the pool for reuse
    pub fn return_config(&mut self, handle: ConfigHandle) {
        if let Some(mut config) = self.in_use.remove(&handle.id) {
            // Reset config to default state before returning to pool
            config.reset_to_default();
            self.available.push(config);
        }
        // If the config wasn't found in in_use, it might have already been returned
        // This is safe to ignore as it prevents double-return issues
    }

    /// Modifies a config in the pool safely
    pub fn modify_config<F>(&mut self, handle: &ConfigHandle, f: F)
    where
        F: FnOnce(&mut AnimationConfig),
    {
        if let Some(config) = self.in_use.get_mut(&handle.id) {
            f(config);
        }
    }

    /// Gets a reference to a config in the pool
    pub fn get_config_ref(&self, handle: &ConfigHandle) -> Option<&AnimationConfig> {
        self.in_use.get(&handle.id)
    }

    /// Gets the number of configs currently in use
    pub fn in_use_count(&self) -> usize {
        self.in_use.len()
    }

    /// Gets the number of configs available in the pool
    pub fn available_count(&self) -> usize {
        self.available.len()
    }

    /// Clears all configs from the pool
    pub fn clear(&mut self) {
        self.available.clear();
        self.in_use.clear();
        self.next_id = 0;
    }

    /// Trims the available configs to the specified target size
    /// This removes excess configs from the available pool while preserving in-use configs
    pub fn trim_to_size(&mut self, target_size: usize) {
        let current_available = self.available.len();
        if current_available > target_size {
            // Remove excess configs from the end of the available vector
            self.available.truncate(target_size);
        }
    }
}

impl Default for ConfigPool {
    fn default() -> Self {
        Self::new()
    }
}

/// A handle to a pooled AnimationConfig that automatically returns to pool when dropped
pub struct ConfigHandle {
    id: usize,
    // Track if this handle is still valid (not yet dropped)
    valid: bool,
}

impl ConfigHandle {
    /// Gets the ID of this handle
    pub fn id(&self) -> usize {
        self.id
    }

    /// Creates a new handle with the given ID and pool reference
    /// This is primarily for testing purposes
    #[cfg(test)]
    pub fn new_test(id: usize) -> Self {
        Self { id, valid: true }
    }
}

impl Drop for ConfigHandle {
    fn drop(&mut self) {
        // Don't automatically return configs to pool on drop
        // This prevents issues with cloned handles returning the same config multiple times
        // Configs should be explicitly returned via Motion::drop or other cleanup mechanisms
    }
}

impl Clone for ConfigHandle {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            valid: self.valid,
        }
    }
}

/// Extension trait for AnimationConfig to support pooling
trait ConfigPoolable {
    fn reset_to_default(&mut self);
}

impl ConfigPoolable for AnimationConfig {
    fn reset_to_default(&mut self) {
        *self = AnimationConfig::default();
    }
}

/// Trait for pools that can provide statistics
#[allow(dead_code)]
trait PoolStatsProvider {
    fn stats(&self) -> (usize, usize);
}

impl<T: Animatable + Send> PoolStatsProvider for SpringIntegratorPool<T> {
    fn stats(&self) -> (usize, usize) {
        (self.in_use.len(), self.available.len())
    }
}

// Thread-local config pool for efficient access
thread_local! {
    static CONFIG_POOL: RefCell<ConfigPool> = RefCell::new(ConfigPool::new());
}

/// Global functions for accessing the thread-local config pool
pub mod global {
    use super::*;

    /// Gets a config from the global thread-local pool
    pub fn get_config() -> ConfigHandle {
        CONFIG_POOL.with(|pool| pool.borrow_mut().get_config())
    }

    /// Returns a config to the global thread-local pool
    pub fn return_config(handle: ConfigHandle) {
        CONFIG_POOL.with(|pool| {
            pool.borrow_mut().return_config(handle);
        });
    }

    /// Modifies a config in the global thread-local pool
    pub fn modify_config<F>(handle: &ConfigHandle, f: F)
    where
        F: FnOnce(&mut AnimationConfig),
    {
        CONFIG_POOL.with(|pool| {
            pool.borrow_mut().modify_config(handle, f);
        });
    }

    /// Gets a reference to a config in the global thread-local pool
    pub fn get_config_ref(handle: &ConfigHandle) -> Option<AnimationConfig> {
        CONFIG_POOL.with(|pool| pool.borrow().get_config_ref(handle).cloned())
    }

    /// Gets pool statistics
    pub fn pool_stats() -> (usize, usize) {
        CONFIG_POOL.with(|pool| {
            let pool = pool.borrow();
            (pool.in_use_count(), pool.available_count())
        })
    }

    /// Clears the global pool (primarily for testing)
    #[cfg(test)]
    pub fn clear_pool() {
        CONFIG_POOL.with(|pool| {
            pool.borrow_mut().clear();
        });
    }
}

/// Spring integrator with pre-allocated buffers for RK4 integration
/// Eliminates temporary State struct allocations in hot paths
pub struct SpringIntegrator<T: Animatable> {
    // Pre-allocated buffers for RK4 integration steps
    k1_pos: T,
    k1_vel: T,
    k2_pos: T,
    k2_vel: T,
    k3_pos: T,
    k3_vel: T,
    k4_pos: T,
    k4_vel: T,
    // Temporary state for calculations
    temp_pos: T,
    temp_vel: T,
}

impl<T: Animatable> SpringIntegrator<T> {
    /// Creates a new spring integrator with default-initialized buffers
    pub fn new() -> Self {
        Self {
            k1_pos: T::default(),
            k1_vel: T::default(),
            k2_pos: T::default(),
            k2_vel: T::default(),
            k3_pos: T::default(),
            k3_vel: T::default(),
            k4_pos: T::default(),
            k4_vel: T::default(),
            temp_pos: T::default(),
            temp_vel: T::default(),
        }
    }

    /// Performs RK4 integration using pre-allocated buffers
    /// Returns the new position and velocity
    pub fn integrate_rk4(
        &mut self,
        current_pos: T,
        current_vel: T,
        target: T,
        spring: &Spring,
        dt: f32,
    ) -> (T, T) {
        let stiffness = spring.stiffness;
        let damping = spring.damping;
        let mass_inv = 1.0 / spring.mass;

        // K1 calculation
        let delta = target - current_pos;
        let force = delta * stiffness;
        let damping_force = current_vel * damping;
        let acc = (force - damping_force) * mass_inv;
        self.k1_pos = current_vel;
        self.k1_vel = acc;

        // K2 calculation
        self.temp_pos = current_pos + self.k1_pos * (dt * 0.5);
        self.temp_vel = current_vel + self.k1_vel * (dt * 0.5);
        let delta = target - self.temp_pos;
        let force = delta * stiffness;
        let damping_force = self.temp_vel * damping;
        let acc = (force - damping_force) * mass_inv;
        self.k2_pos = self.temp_vel;
        self.k2_vel = acc;

        // K3 calculation
        self.temp_pos = current_pos + self.k2_pos * (dt * 0.5);
        self.temp_vel = current_vel + self.k2_vel * (dt * 0.5);
        let delta = target - self.temp_pos;
        let force = delta * stiffness;
        let damping_force = self.temp_vel * damping;
        let acc = (force - damping_force) * mass_inv;
        self.k3_pos = self.temp_vel;
        self.k3_vel = acc;

        // K4 calculation
        self.temp_pos = current_pos + self.k3_pos * dt;
        self.temp_vel = current_vel + self.k3_vel * dt;
        let delta = target - self.temp_pos;
        let force = delta * stiffness;
        let damping_force = self.temp_vel * damping;
        let acc = (force - damping_force) * mass_inv;
        self.k4_pos = self.temp_vel;
        self.k4_vel = acc;

        // Final integration
        const SIXTH: f32 = 1.0 / 6.0;
        let new_pos = current_pos
            + (self.k1_pos + self.k2_pos * 2.0 + self.k3_pos * 2.0 + self.k4_pos) * (dt * SIXTH);
        let new_vel = current_vel
            + (self.k1_vel + self.k2_vel * 2.0 + self.k3_vel * 2.0 + self.k4_vel) * (dt * SIXTH);

        (new_pos, new_vel)
    }

    /// Resets all buffers to default values (for pool reuse)
    pub fn reset(&mut self) {
        self.k1_pos = T::default();
        self.k1_vel = T::default();
        self.k2_pos = T::default();
        self.k2_vel = T::default();
        self.k3_pos = T::default();
        self.k3_vel = T::default();
        self.k4_pos = T::default();
        self.k4_vel = T::default();
        self.temp_pos = T::default();
        self.temp_vel = T::default();
    }
}

impl<T: Animatable> Default for SpringIntegrator<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Pool for reusing SpringIntegrator instances
pub struct SpringIntegratorPool<T: Animatable> {
    available: Vec<SpringIntegrator<T>>,
    in_use: HashMap<usize, SpringIntegrator<T>>,
    next_id: usize,
}

impl<T: Animatable> SpringIntegratorPool<T> {
    /// Creates a new integrator pool
    pub fn new() -> Self {
        Self::with_capacity(8)
    }

    /// Creates a new integrator pool with specified capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            available: Vec::with_capacity(capacity),
            in_use: HashMap::with_capacity(capacity),
            next_id: 0,
        }
    }

    /// Gets an integrator from the pool
    pub fn get_integrator(&mut self) -> SpringIntegratorHandle {
        let mut integrator = self.available.pop().unwrap_or_default();
        integrator.reset(); // Ensure clean state

        let id = self.next_id;
        self.next_id += 1;
        self.in_use.insert(id, integrator);

        SpringIntegratorHandle { id }
    }

    /// Returns an integrator to the pool
    pub fn return_integrator(&mut self, handle: SpringIntegratorHandle) {
        if let Some(integrator) = self.in_use.remove(&handle.id) {
            self.available.push(integrator);
        }
    }

    /// Gets a mutable reference to an integrator
    pub fn get_integrator_mut(
        &mut self,
        handle: &SpringIntegratorHandle,
    ) -> Option<&mut SpringIntegrator<T>> {
        self.in_use.get_mut(&handle.id)
    }

    /// Gets pool statistics
    pub fn stats(&self) -> (usize, usize) {
        (self.in_use.len(), self.available.len())
    }

    /// Clears the pool
    pub fn clear(&mut self) {
        self.available.clear();
        self.in_use.clear();
        self.next_id = 0;
    }
}

impl<T: Animatable> Default for SpringIntegratorPool<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Handle to a pooled SpringIntegrator
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpringIntegratorHandle {
    id: usize,
}

/// Global integrator pool management using type-erased storage
pub struct GlobalIntegratorPools {
    pools: HashMap<TypeId, Box<dyn Any + Send>>,
    // Track stats separately since we can't easily downcast trait objects
    stats_tracker: HashMap<TypeId, (usize, usize)>,
}

impl Default for GlobalIntegratorPools {
    fn default() -> Self {
        Self::new()
    }
}

impl GlobalIntegratorPools {
    pub fn new() -> Self {
        Self {
            pools: HashMap::new(),
            stats_tracker: HashMap::new(),
        }
    }

    /// Gets or creates a pool for type T
    pub fn get_pool<T: Animatable + Send + 'static>(&mut self) -> &mut SpringIntegratorPool<T> {
        let type_id = TypeId::of::<T>();

        // Get or create the pool
        let pool = self
            .pools
            .entry(type_id)
            .or_insert_with(|| Box::new(SpringIntegratorPool::<T>::new()))
            .downcast_mut::<SpringIntegratorPool<T>>()
            .expect("Type mismatch in integrator pool");

        // Update stats tracker
        let stats = pool.stats();
        self.stats_tracker.insert(type_id, stats);

        pool
    }

    /// Clears all pools
    pub fn clear(&mut self) {
        self.pools.clear();
        self.stats_tracker.clear();
    }

    /// Gets statistics for all pools
    pub fn stats(&self) -> HashMap<TypeId, (usize, usize)> {
        self.stats_tracker.clone()
    }

    /// Updates stats for a specific type (called when integrators are returned)
    pub fn update_stats<T: Animatable + Send + 'static>(&mut self) {
        let type_id = TypeId::of::<T>();
        if let Some(pool) = self.pools.get(&type_id)
            && let Some(pool) = pool.downcast_ref::<SpringIntegratorPool<T>>()
        {
            let stats = pool.stats();
            self.stats_tracker.insert(type_id, stats);
        }
    }
}

/// Global resource pool management for Motion optimizations
/// Manages all pooled resources including configs, integrators, and closures
pub struct MotionResourcePools {
    /// Configuration pool for reusing AnimationConfig instances
    pub config_pool: ConfigPool,
    /// Integrator pools for different animatable types
    pub integrator_pools: GlobalIntegratorPools,
    /// Web closure pool for JavaScript closure reuse (web only)
    #[cfg(feature = "web")]
    pub closure_pool: crate::animations::closure_pool::WebClosurePool,
    /// Pool configuration settings
    pub config: PoolConfig,
}

impl MotionResourcePools {
    /// Creates new resource pools with default configuration
    pub fn new() -> Self {
        Self::with_config(PoolConfig::default())
    }

    /// Creates new resource pools with specified configuration
    pub fn with_config(config: PoolConfig) -> Self {
        Self {
            config_pool: ConfigPool::with_capacity(config.config_pool_capacity),
            integrator_pools: GlobalIntegratorPools::new(),
            #[cfg(feature = "web")]
            closure_pool: crate::animations::closure_pool::WebClosurePool::new(),
            config,
        }
    }

    /// Gets statistics for all pools
    pub fn stats(&self) -> PoolStats {
        let (config_in_use, config_available) = (
            self.config_pool.in_use_count(),
            self.config_pool.available_count(),
        );

        #[cfg(feature = "web")]
        let (closure_in_use, closure_available) = (
            self.closure_pool.in_use_count(),
            self.closure_pool.available_count(),
        );
        #[cfg(not(feature = "web"))]
        let (closure_in_use, closure_available) = (0, 0);

        // Get integrator stats from the global integrator pools
        let integrator_stats = INTEGRATOR_POOLS.with(|pools| pools.borrow().stats());

        PoolStats {
            config_pool: (config_in_use, config_available),
            closure_pool: (closure_in_use, closure_available),
            integrator_pools: integrator_stats,
            total_memory_saved_bytes: self.estimate_memory_savings(),
        }
    }

    /// Estimates memory savings from pooling (rough calculation)
    fn estimate_memory_savings(&self) -> usize {
        // Rough estimates based on typical struct sizes
        const CONFIG_SIZE: usize = std::mem::size_of::<AnimationConfig>();
        const INTEGRATOR_SIZE: usize = 256; // Rough estimate for SpringIntegrator<f32>
        const CLOSURE_SIZE: usize = 64; // Rough estimate for web closures

        let config_savings = self.config_pool.available_count() * CONFIG_SIZE;
        let closure_savings = {
            #[cfg(feature = "web")]
            {
                self.closure_pool.available_count() * CLOSURE_SIZE
            }
            #[cfg(not(feature = "web"))]
            {
                0
            }
        };

        // Integrator savings would need type-specific calculation
        // For now, just estimate based on common usage
        let integrator_savings = 8 * INTEGRATOR_SIZE; // Assume ~8 pooled integrators on average

        config_savings + closure_savings + integrator_savings
    }

    /// Clears all pools (primarily for testing and cleanup)
    pub fn clear(&mut self) {
        self.config_pool.clear();
        self.integrator_pools.clear();
        #[cfg(feature = "web")]
        self.closure_pool.clear();
    }

    /// Performs maintenance on all pools (removes excess capacity, etc.)
    pub fn maintain(&mut self) {
        // Trim config pool if it's grown too large
        if self.config_pool.available_count() > self.config.max_config_pool_size {
            self.config_pool
                .trim_to_size(self.config.target_config_pool_size);
        }

        // Similar maintenance for other pools could be added here
    }
}

impl Default for MotionResourcePools {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for resource pools
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Initial capacity for config pool
    pub config_pool_capacity: usize,
    /// Maximum size for config pool before trimming
    pub max_config_pool_size: usize,
    /// Target size to trim config pool to
    pub target_config_pool_size: usize,
    /// Whether to enable automatic pool maintenance
    pub auto_maintain: bool,
    /// Interval for automatic maintenance (in animation frames)
    pub maintenance_interval: u32,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            config_pool_capacity: 16,
            max_config_pool_size: 64,
            target_config_pool_size: 32,
            auto_maintain: true,
            maintenance_interval: 1000, // Every ~16 seconds at 60fps
        }
    }
}

/// Statistics about all resource pools
#[derive(Debug, Clone)]
pub struct PoolStats {
    /// Config pool stats: (in_use, available)
    pub config_pool: (usize, usize),
    /// Closure pool stats: (in_use, available)
    pub closure_pool: (usize, usize),
    /// Integrator pool stats by type
    pub integrator_pools: HashMap<TypeId, (usize, usize)>,
    /// Estimated memory saved by pooling (in bytes)
    pub total_memory_saved_bytes: usize,
}

// Thread-local resource pools
thread_local! {
    static MOTION_RESOURCE_POOLS: RefCell<MotionResourcePools> = RefCell::new(MotionResourcePools::new());
    static INTEGRATOR_POOLS: RefCell<GlobalIntegratorPools> = RefCell::new(GlobalIntegratorPools::new());
}

/// Global functions for integrator pool management
pub mod integrator {
    use super::*;

    /// Gets an integrator from the global thread-local pool
    pub fn get_integrator<T: Animatable + Send + 'static>() -> SpringIntegratorHandle {
        INTEGRATOR_POOLS.with(|pools| pools.borrow_mut().get_pool::<T>().get_integrator())
    }

    /// Returns an integrator to the global thread-local pool
    pub fn return_integrator<T: Animatable + Send + 'static>(handle: SpringIntegratorHandle) {
        INTEGRATOR_POOLS.with(|pools| {
            let mut pools = pools.borrow_mut();
            pools.get_pool::<T>().return_integrator(handle);
            pools.update_stats::<T>();
        });
    }

    /// Performs RK4 integration using a pooled integrator
    pub fn integrate_rk4<T: Animatable + Send + 'static>(
        handle: &SpringIntegratorHandle,
        current_pos: T,
        current_vel: T,
        target: T,
        spring: &Spring,
        dt: f32,
    ) -> (T, T) {
        INTEGRATOR_POOLS.with(|pools| {
            let mut pools = pools.borrow_mut();
            let pool = pools.get_pool::<T>();
            pool.get_integrator_mut(handle).map_or_else(
                || {
                    // Fallback to non-pooled integration if handle is invalid
                    let mut integrator = SpringIntegrator::new();
                    integrator.integrate_rk4(current_pos, current_vel, target, spring, dt)
                },
                |integrator| integrator.integrate_rk4(current_pos, current_vel, target, spring, dt),
            )
        })
    }

    /// Gets pool statistics for type T
    pub fn pool_stats<T: Animatable + Send + 'static>() -> (usize, usize) {
        INTEGRATOR_POOLS.with(|pools| pools.borrow_mut().get_pool::<T>().stats())
    }

    /// Clears all integrator pools (primarily for testing)
    #[cfg(test)]
    pub fn clear_pools() {
        INTEGRATOR_POOLS.with(|pools| {
            pools.borrow_mut().clear();
        });
    }
}

/// Global functions for managing Motion resource pools
pub mod resource_pools {
    use super::*;

    /// Gets statistics for all resource pools
    pub fn stats() -> PoolStats {
        MOTION_RESOURCE_POOLS.with(|pools| pools.borrow().stats())
    }

    /// Configures the global resource pools
    /// This should be called early in your application startup for optimal performance
    pub fn configure(config: PoolConfig) {
        MOTION_RESOURCE_POOLS.with(|pools| {
            *pools.borrow_mut() = MotionResourcePools::with_config(config);
        });
    }

    /// Initializes resource pools with high-performance defaults
    /// Recommended for applications with many concurrent animations
    pub fn init_high_performance() {
        configure(PoolConfig {
            config_pool_capacity: 64,
            max_config_pool_size: 256,
            target_config_pool_size: 128,
            auto_maintain: true,
            maintenance_interval: 500, // More frequent maintenance
        });
    }

    /// Initializes resource pools with memory-conservative defaults
    /// Recommended for memory-constrained environments
    pub fn init_memory_conservative() {
        configure(PoolConfig {
            config_pool_capacity: 8,
            max_config_pool_size: 32,
            target_config_pool_size: 16,
            auto_maintain: true,
            maintenance_interval: 2000, // Less frequent maintenance
        });
    }

    /// Performs maintenance on all resource pools
    pub fn maintain() {
        MOTION_RESOURCE_POOLS.with(|pools| {
            pools.borrow_mut().maintain();
        });
    }

    /// Clears all resource pools (primarily for testing)
    #[cfg(test)]
    pub fn clear_all() {
        MOTION_RESOURCE_POOLS.with(|pools| {
            pools.borrow_mut().clear();
        });
    }

    /// Gets the current pool configuration
    pub fn get_config() -> PoolConfig {
        MOTION_RESOURCE_POOLS.with(|pools| pools.borrow().config.clone())
    }

    /// Estimates total memory usage of all pools
    pub fn memory_usage_bytes() -> usize {
        MOTION_RESOURCE_POOLS.with(|pools| {
            let pools = pools.borrow();
            let stats = pools.stats();

            // Rough calculation of memory usage
            const CONFIG_SIZE: usize = std::mem::size_of::<AnimationConfig>();
            const INTEGRATOR_SIZE: usize = 256;
            const CLOSURE_SIZE: usize = 64;

            let config_memory = (stats.config_pool.0 + stats.config_pool.1) * CONFIG_SIZE;
            let closure_memory = (stats.closure_pool.0 + stats.closure_pool.1) * CLOSURE_SIZE;
            let integrator_memory = stats
                .integrator_pools
                .values()
                .map(|(in_use, available)| (in_use + available) * INTEGRATOR_SIZE)
                .sum::<usize>();

            config_memory + closure_memory + integrator_memory
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use crate::animations::core::AnimationMode;
    use crate::animations::spring::Spring;
    use instant::Duration;

    #[test]
    fn test_config_pool_basic_operations() {
        let mut pool = ConfigPool::new();

        // Test getting a config
        let handle1 = pool.get_config();
        assert_eq!(pool.in_use_count(), 1);
        assert_eq!(pool.available_count(), 0);

        // Test getting another config
        let handle2 = pool.get_config();
        assert_eq!(pool.in_use_count(), 2);
        assert_eq!(pool.available_count(), 0);

        // Test returning a config
        pool.return_config(handle1);
        assert_eq!(pool.in_use_count(), 1);
        assert_eq!(pool.available_count(), 1);

        // Test reusing returned config
        let handle3 = pool.get_config();
        assert_eq!(pool.in_use_count(), 2);
        assert_eq!(pool.available_count(), 0);

        // Clean up
        pool.return_config(handle2);
        pool.return_config(handle3);
    }

    #[test]
    fn test_config_pool_modification() {
        let mut pool = ConfigPool::new();
        let handle = pool.get_config();

        // Modify the config
        pool.modify_config(&handle, |config| {
            config.mode = AnimationMode::Spring(Spring::default());
            config.delay = Duration::from_millis(100);
        });

        // Verify modification
        let config_ref = pool.get_config_ref(&handle).unwrap();
        assert!(matches!(config_ref.mode, AnimationMode::Spring(_)));
        assert_eq!(config_ref.delay, Duration::from_millis(100));

        pool.return_config(handle);
    }

    #[test]
    fn test_config_pool_reset_on_return() {
        let mut pool = ConfigPool::new();
        let handle = pool.get_config();

        // Modify the config
        pool.modify_config(&handle, |config| {
            config.mode = AnimationMode::Spring(Spring::default());
            config.delay = Duration::from_millis(100);
        });

        // Return to pool (should reset)
        pool.return_config(handle);

        // Get a new config and verify it's reset
        let new_handle = pool.get_config();
        let config_ref = pool.get_config_ref(&new_handle).unwrap();
        assert!(matches!(config_ref.mode, AnimationMode::Tween(_)));
        assert_eq!(config_ref.delay, Duration::default());

        pool.return_config(new_handle);
    }

    #[test]
    fn test_config_pool_with_capacity() {
        let pool = ConfigPool::with_capacity(32);
        assert_eq!(pool.available_count(), 0);
        assert_eq!(pool.in_use_count(), 0);
    }

    #[test]
    fn test_config_pool_clear() {
        let mut pool = ConfigPool::new();
        let handle1 = pool.get_config();
        let _handle2 = pool.get_config();

        pool.return_config(handle1);
        assert_eq!(pool.in_use_count(), 1);
        assert_eq!(pool.available_count(), 1);

        pool.clear();
        assert_eq!(pool.in_use_count(), 0);
        assert_eq!(pool.available_count(), 0);

        // _handle2 is now invalid, but we won't try to return it
    }

    #[test]
    fn test_global_config_pool() {
        global::clear_pool();

        let handle1 = global::get_config();
        let handle2 = global::get_config();

        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 2);
        assert_eq!(available, 0);

        global::modify_config(&handle1, |config| {
            config.delay = Duration::from_millis(50);
        });

        let config = global::get_config_ref(&handle1).unwrap();
        assert_eq!(config.delay, Duration::from_millis(50));

        global::return_config(handle1);
        global::return_config(handle2);

        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 0);
        assert_eq!(available, 2);
    }

    #[test]
    fn test_config_handle_clone() {
        let handle1 = ConfigHandle::new_test(42);
        let handle2 = handle1.clone();

        assert_eq!(handle1.id(), handle2.id());
        assert_eq!(handle1.id(), 42);
    }

    #[test]
    fn test_config_handle_explicit_cleanup() {
        // Clear the pool first
        global::clear_pool();

        // Get a config handle
        let handle = global::get_config();

        // Verify the config is in use
        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 1);
        assert_eq!(available, 0);

        // Explicitly return the handle to pool
        global::return_config(handle);

        // Verify the config was returned to the pool
        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 0);
        assert_eq!(available, 1);
    }

    #[test]
    fn test_config_handle_double_drop_safety() {
        // Clear the pool first
        global::clear_pool();

        // Get a config handle
        let handle = global::get_config();
        let handle_id = handle.id();

        // Manually return the config
        global::return_config(ConfigHandle {
            id: handle_id,
            valid: false,
        });

        // Verify it was returned
        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 0);
        assert_eq!(available, 1);

        // Now drop the original handle - should not cause issues
        drop(handle);

        // Should still have the same state
        let (in_use, available) = global::pool_stats();
        assert_eq!(in_use, 0);
        assert_eq!(available, 1);
    }

    #[test]
    fn test_spring_integrator() {
        let mut integrator = SpringIntegrator::<f32>::new();
        let spring = Spring::default();

        let current_pos = 0.0f32;
        let current_vel = 0.0f32;
        let target = 100.0f32;
        let dt = 1.0 / 60.0; // 60 FPS

        let (new_pos, new_vel) =
            integrator.integrate_rk4(current_pos, current_vel, target, &spring, dt);

        // After one integration step, position should have moved toward target
        assert!(new_pos > current_pos);
        assert!(new_pos < target);
        assert!(new_vel > 0.0); // Should be moving toward target

        // Test reset
        integrator.reset();
        // All buffers should be reset to default (can't easily test without exposing internals)
    }

    #[test]
    fn test_spring_integrator_pool() {
        let mut pool = SpringIntegratorPool::<f32>::new();

        // Test getting integrator
        let handle1 = pool.get_integrator();
        let handle2 = pool.get_integrator();

        let (in_use, available) = pool.stats();
        assert_eq!(in_use, 2);
        assert_eq!(available, 0);

        // Test using integrator
        let spring = Spring::default();
        if let Some(integrator) = pool.get_integrator_mut(&handle1) {
            let (new_pos, new_vel) = integrator.integrate_rk4(0.0, 0.0, 100.0, &spring, 1.0 / 60.0);
            assert!(new_pos > 0.0);
            assert!(new_vel > 0.0);
        }

        // Test returning integrator
        pool.return_integrator(handle1);
        let (in_use, available) = pool.stats();
        assert_eq!(in_use, 1);
        assert_eq!(available, 1);

        // Test reusing returned integrator
        let handle3 = pool.get_integrator();
        let (in_use, available) = pool.stats();
        assert_eq!(in_use, 2);
        assert_eq!(available, 0);

        // Clean up
        pool.return_integrator(handle2);
        pool.return_integrator(handle3);
    }

    #[test]
    fn test_global_integrator_pool() {
        integrator::clear_pools();

        let handle1 = integrator::get_integrator::<f32>();
        let handle2 = integrator::get_integrator::<f32>();

        let (in_use, available) = integrator::pool_stats::<f32>();
        assert_eq!(in_use, 2);
        assert_eq!(available, 0);

        // Test integration
        let spring = Spring::default();
        let (new_pos, new_vel) =
            integrator::integrate_rk4(&handle1, 0.0, 0.0, 100.0, &spring, 1.0 / 60.0);
        assert!(new_pos > 0.0);
        assert!(new_vel > 0.0);

        // Return integrators
        integrator::return_integrator::<f32>(handle1);
        integrator::return_integrator::<f32>(handle2);

        let (in_use, available) = integrator::pool_stats::<f32>();
        assert_eq!(in_use, 0);
        assert_eq!(available, 2);
    }

    #[test]
    fn test_integrator_pool_stats_tracking() {
        // Clear both pools to start fresh
        integrator::clear_pools();
        resource_pools::clear_all();

        // Get integrators for different types using the integrator module
        let handle_f32 = integrator::get_integrator::<f32>();
        let handle_vec2 = integrator::get_integrator::<crate::animations::transform::Transform>();

        // Get stats from the integrator module directly
        let f32_stats = integrator::pool_stats::<f32>();
        let transform_stats = integrator::pool_stats::<crate::animations::transform::Transform>();

        // Check that stats are tracked correctly
        assert_eq!(f32_stats.0, 1); // in_use
        assert_eq!(f32_stats.1, 0); // available

        assert_eq!(transform_stats.0, 1); // in_use
        assert_eq!(transform_stats.1, 0); // available

        // Return integrators
        integrator::return_integrator::<f32>(handle_f32);
        integrator::return_integrator::<crate::animations::transform::Transform>(handle_vec2);

        // Get updated stats
        let updated_f32_stats = integrator::pool_stats::<f32>();
        let updated_transform_stats =
            integrator::pool_stats::<crate::animations::transform::Transform>();

        // Check that stats were updated after returning
        assert_eq!(updated_f32_stats.0, 0); // in_use
        assert_eq!(updated_f32_stats.1, 1); // available

        assert_eq!(updated_transform_stats.0, 0); // in_use
        assert_eq!(updated_transform_stats.1, 1); // available
    }

    #[test]
    fn test_spring_integrator_accuracy() {
        // Test that the pooled integrator produces the same results as the original
        let mut integrator = SpringIntegrator::<f32>::new();
        let spring = Spring::default();

        let current_pos = 10.0f32;
        let current_vel = 5.0f32;
        let target = 50.0f32;
        let dt = 1.0 / 120.0; // 120 FPS

        let (new_pos, new_vel) =
            integrator.integrate_rk4(current_pos, current_vel, target, &spring, dt);

        // The result should be mathematically consistent
        // Position should move in the direction of velocity
        assert!(new_pos > current_pos);
        // Velocity should be affected by spring force
        let expected_force_direction = target - current_pos;
        assert!(expected_force_direction > 0.0); // Force toward target
        // With default spring settings, velocity should increase toward target
        assert!(new_vel > current_vel);
    }

    #[test]
    fn test_motion_resource_pools() {
        let pools = MotionResourcePools::new();

        // Test initial state
        let stats = pools.stats();
        assert_eq!(stats.config_pool, (0, 0));
        assert_eq!(stats.closure_pool, (0, 0));
        assert!(stats.integrator_pools.is_empty());
        assert_eq!(stats.total_memory_saved_bytes, 8 * 256); // Estimated integrator savings
    }

    #[test]
    fn test_motion_resource_pools_with_config() {
        let config = PoolConfig {
            config_pool_capacity: 32,
            max_config_pool_size: 128,
            target_config_pool_size: 64,
            auto_maintain: false,
            maintenance_interval: 500,
        };

        let pools = MotionResourcePools::with_config(config.clone());
        assert_eq!(pools.config.config_pool_capacity, 32);
        assert_eq!(pools.config.max_config_pool_size, 128);
        assert!(!pools.config.auto_maintain);
    }

    #[test]
    fn test_motion_resource_pools_clear() {
        let mut pools = MotionResourcePools::new();

        // Add some items to pools (simplified test)
        let _handle = pools.config_pool.get_config();

        pools.clear();

        let stats = pools.stats();
        assert_eq!(stats.config_pool, (0, 0));
        assert_eq!(stats.closure_pool, (0, 0));
    }

    #[test]
    fn test_resource_pools_global_functions() {
        resource_pools::clear_all();

        // Test configuration
        let config = PoolConfig {
            config_pool_capacity: 24,
            max_config_pool_size: 96,
            target_config_pool_size: 48,
            auto_maintain: true,
            maintenance_interval: 750,
        };

        resource_pools::configure(config.clone());
        let retrieved_config = resource_pools::get_config();
        assert_eq!(retrieved_config.config_pool_capacity, 24);
        assert_eq!(retrieved_config.max_config_pool_size, 96);

        // Test stats
        let stats = resource_pools::stats();
        assert_eq!(stats.config_pool, (0, 0));

        // Test memory usage (should be reasonable)
        let memory_usage = resource_pools::memory_usage_bytes();
        // Memory usage should be reasonable (at least 0, but not too large)
        assert!(memory_usage < 1_000_000); // Shouldn't be unreasonably large

        // Test maintenance (should not panic)
        resource_pools::maintain();
    }

    #[test]
    fn test_pool_config_default() {
        let config = PoolConfig::default();
        assert_eq!(config.config_pool_capacity, 16);
        assert_eq!(config.max_config_pool_size, 64);
        assert_eq!(config.target_config_pool_size, 32);
        assert!(config.auto_maintain);
        assert_eq!(config.maintenance_interval, 1000);
    }

    #[test]
    fn test_pool_stats_memory_estimation() {
        let pools = MotionResourcePools::new();
        let stats = pools.stats();

        // Memory savings should be reasonable estimate
        assert!(stats.total_memory_saved_bytes > 0);
        assert!(stats.total_memory_saved_bytes < 1_000_000); // Shouldn't be unreasonably large
    }

    #[test]
    fn test_resource_pools_stats_returns_actual_data() {
        // Clear pools to start fresh
        resource_pools::clear_all();

        // Get some integrators to populate the pools
        let handle1 = integrator::get_integrator::<f32>();
        let handle2 = integrator::get_integrator::<crate::animations::transform::Transform>();

        // Get stats from resource_pools
        let stats = resource_pools::stats();

        // Verify that we get actual stats instead of empty data
        // The integrator_pools should contain stats for the types we used
        assert!(
            !stats.integrator_pools.is_empty(),
            "Integrator pools stats should not be empty"
        );

        // Check that we have stats for the types we used
        let f32_type_id = std::any::TypeId::of::<f32>();
        let transform_type_id = std::any::TypeId::of::<crate::animations::transform::Transform>();

        assert!(
            stats.integrator_pools.contains_key(&f32_type_id),
            "Should have f32 stats"
        );
        assert!(
            stats.integrator_pools.contains_key(&transform_type_id),
            "Should have Transform stats"
        );

        // Return integrators
        integrator::return_integrator::<f32>(handle1);
        integrator::return_integrator::<crate::animations::transform::Transform>(handle2);
    }

    #[test]
    fn test_motion_resource_pools_maintain() {
        let mut pools = MotionResourcePools::new();

        // Test maintenance doesn't panic
        pools.maintain();

        // Test with modified config
        pools.config.max_config_pool_size = 1;
        pools.config.target_config_pool_size = 0;
        pools.maintain(); // Should handle edge cases gracefully
    }

    #[test]
    fn test_config_pool_trimming() {
        let mut pool = ConfigPool::new();

        // Add some configs to the available pool
        for _ in 0..10 {
            pool.available.push(AnimationConfig::default());
        }

        // Verify initial state
        assert_eq!(pool.available_count(), 10);
        assert_eq!(pool.in_use_count(), 0);

        // Trim to target size
        pool.trim_to_size(5);
        assert_eq!(pool.available_count(), 5);
        assert_eq!(pool.in_use_count(), 0);

        // Trim to smaller size
        pool.trim_to_size(2);
        assert_eq!(pool.available_count(), 2);
        assert_eq!(pool.in_use_count(), 0);

        // Trim to larger size (should not add configs)
        pool.trim_to_size(10);
        assert_eq!(pool.available_count(), 2);
        assert_eq!(pool.in_use_count(), 0);

        // Trim to zero
        pool.trim_to_size(0);
        assert_eq!(pool.available_count(), 0);
        assert_eq!(pool.in_use_count(), 0);
    }

    #[test]
    fn test_config_pool_trimming_with_in_use_configs() {
        let mut pool = ConfigPool::new();

        // Add some configs to the available pool
        for _ in 0..10 {
            pool.available.push(AnimationConfig::default());
        }

        // Get some configs (put them in use)
        let handle1 = pool.get_config();
        let handle2 = pool.get_config();

        // Verify state before trimming
        assert_eq!(pool.available_count(), 8);
        assert_eq!(pool.in_use_count(), 2);

        // Trim available configs (should not affect in-use configs)
        pool.trim_to_size(3);
        assert_eq!(pool.available_count(), 3);
        assert_eq!(pool.in_use_count(), 2);

        // Return configs and verify they're still available
        pool.return_config(handle1);
        pool.return_config(handle2);
        assert_eq!(pool.available_count(), 5);
        assert_eq!(pool.in_use_count(), 0);
    }
}