blinc_animation 0.5.1

Blinc animation system - spring physics, keyframes, and timeline orchestration
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
//! Keyframe animations
//!
//! This module provides both single-value keyframe animations and multi-property
//! keyframe animations for animating multiple properties simultaneously.

use crate::easing::Easing;

/// A single keyframe in a single-value animation
#[derive(Clone, Debug)]
pub struct Keyframe {
    /// Time position (0.0 to 1.0)
    pub time: f32,
    /// Target value at this keyframe
    pub value: f32,
    /// Easing function to use when transitioning TO this keyframe
    pub easing: Easing,
}

/// A keyframe-based animation (single value)
#[derive(Clone, Debug)]
pub struct KeyframeAnimation {
    duration_ms: u32,
    keyframes: Vec<Keyframe>,
    current_time: f32,
    playing: bool,
}

impl KeyframeAnimation {
    pub fn new(duration_ms: u32, keyframes: Vec<Keyframe>) -> Self {
        Self {
            duration_ms,
            keyframes,
            current_time: 0.0,
            playing: false,
        }
    }

    pub fn start(&mut self) {
        self.current_time = 0.0;
        self.playing = true;
    }

    pub fn stop(&mut self) {
        self.playing = false;
    }

    pub fn is_playing(&self) -> bool {
        self.playing
    }

    pub fn progress(&self) -> f32 {
        self.current_time / self.duration_ms as f32
    }

    /// Get the current interpolated value
    pub fn value(&self) -> f32 {
        if self.keyframes.is_empty() {
            return 0.0;
        }

        let progress = self.progress().clamp(0.0, 1.0);

        // Find surrounding keyframes
        let mut prev_kf = &self.keyframes[0];
        let mut next_kf = &self.keyframes[0];

        for kf in &self.keyframes {
            if kf.time <= progress {
                prev_kf = kf;
            }
            if kf.time >= progress {
                next_kf = kf;
                break;
            }
        }

        if (prev_kf.time - next_kf.time).abs() < f32::EPSILON {
            return prev_kf.value;
        }

        // Interpolate between keyframes
        let local_progress = (progress - prev_kf.time) / (next_kf.time - prev_kf.time);
        let eased = next_kf.easing.apply(local_progress);

        prev_kf.value + (next_kf.value - prev_kf.value) * eased
    }

    /// Advance the animation by delta time (in milliseconds)
    pub fn tick(&mut self, dt_ms: f32) {
        if !self.playing {
            return;
        }

        self.current_time += dt_ms;

        if self.current_time >= self.duration_ms as f32 {
            self.current_time = self.duration_ms as f32;
            self.playing = false;
        }
    }

    /// Get the keyframes
    pub fn keyframes(&self) -> &[Keyframe] {
        &self.keyframes
    }
}

// ============================================================================
// Multi-Property Keyframe Animation
// ============================================================================

/// Properties that can be animated in a multi-property keyframe
#[derive(Clone, Debug, Default, PartialEq)]
pub struct KeyframeProperties {
    /// Opacity (0.0 to 1.0)
    pub opacity: Option<f32>,
    /// Scale X factor
    pub scale_x: Option<f32>,
    /// Scale Y factor
    pub scale_y: Option<f32>,
    /// Translation X in pixels
    pub translate_x: Option<f32>,
    /// Translation Y in pixels
    pub translate_y: Option<f32>,
    /// Rotation in degrees (Z-axis)
    pub rotate: Option<f32>,
    /// Rotation X in degrees (3D tilt)
    pub rotate_x: Option<f32>,
    /// Rotation Y in degrees (3D turn)
    pub rotate_y: Option<f32>,
    /// Perspective distance in pixels
    pub perspective: Option<f32>,
    /// 3D extrusion depth in pixels
    pub depth: Option<f32>,
    /// Z-axis translation in pixels (positive = toward viewer)
    pub translate_z: Option<f32>,
    /// Blend radius for smooth boolean operations (in pixels)
    pub blend_3d: Option<f32>,
    /// Clip-path inset [top%, right%, bottom%, left%]
    pub clip_inset: Option<[f32; 4]>,

    // --- Color properties ---
    /// Background color RGBA (solid brush)
    pub background_color: Option<[f32; 4]>,
    /// Gradient start color RGBA (first stop)
    pub gradient_start_color: Option<[f32; 4]>,
    /// Gradient end color RGBA (last stop)
    pub gradient_end_color: Option<[f32; 4]>,
    /// Gradient angle in degrees (linear gradients)
    pub gradient_angle: Option<f32>,
    /// Border color RGBA
    pub border_color: Option<[f32; 4]>,
    /// Text foreground color RGBA
    pub text_color: Option<[f32; 4]>,

    // --- Geometric properties ---
    /// Corner radius [top_left, top_right, bottom_right, bottom_left]
    pub corner_radius: Option<[f32; 4]>,
    /// Corner shape (superellipse n parameter) [top_left, top_right, bottom_right, bottom_left]
    pub corner_shape: Option<[f32; 4]>,
    /// Border width in pixels
    pub border_width: Option<f32>,
    /// Outline width in pixels
    pub outline_width: Option<f32>,
    /// Outline color RGBA
    pub outline_color: Option<[f32; 4]>,
    /// Outline offset in pixels
    pub outline_offset: Option<f32>,
    /// Clip-path circle radius (percent)
    pub clip_circle_radius: Option<f32>,
    /// Clip-path ellipse radii [rx, ry] (percent)
    pub clip_ellipse_radii: Option<[f32; 2]>,
    /// Overflow fade distances [top, right, bottom, left]
    pub overflow_fade: Option<[f32; 4]>,

    // --- Shadow properties ---
    /// Shadow [offset_x, offset_y, blur, spread]
    pub shadow_params: Option<[f32; 4]>,
    /// Shadow color RGBA
    pub shadow_color: Option<[f32; 4]>,
    /// Text shadow [offset_x, offset_y, blur, spread]
    pub text_shadow_params: Option<[f32; 4]>,
    /// Text shadow color RGBA
    pub text_shadow_color: Option<[f32; 4]>,

    // --- 3D lighting ---
    /// Light intensity (0.0-1.0+)
    pub light_intensity: Option<f32>,
    /// Ambient light level (0.0-1.0)
    pub ambient: Option<f32>,
    /// Specular power (higher = sharper highlights)
    pub specular: Option<f32>,
    /// Light direction [x, y, z]
    pub light_direction: Option<[f32; 3]>,

    // --- CSS filter properties ---
    /// filter: grayscale(0..1)
    pub filter_grayscale: Option<f32>,
    /// filter: invert(0..1)
    pub filter_invert: Option<f32>,
    /// filter: sepia(0..1)
    pub filter_sepia: Option<f32>,
    /// filter: brightness(multiplier, 1.0 = normal)
    pub filter_brightness: Option<f32>,
    /// filter: contrast(multiplier, 1.0 = normal)
    pub filter_contrast: Option<f32>,
    /// filter: saturate(multiplier, 1.0 = normal)
    pub filter_saturate: Option<f32>,
    /// filter: hue-rotate(degrees)
    pub filter_hue_rotate: Option<f32>,
    /// filter: blur(px)
    pub filter_blur: Option<f32>,

    // --- Backdrop filter (glass material) ---
    /// backdrop-filter: blur(px)
    pub backdrop_blur: Option<f32>,
    /// backdrop-filter saturation multiplier (1.0 = normal)
    pub backdrop_saturation: Option<f32>,
    /// backdrop-filter brightness multiplier (1.0 = normal)
    pub backdrop_brightness: Option<f32>,

    // --- Layout properties (require layout recomputation) ---
    /// Width in pixels
    pub width: Option<f32>,
    /// Height in pixels
    pub height: Option<f32>,
    /// Min-width in pixels
    pub min_width: Option<f32>,
    /// Max-width in pixels
    pub max_width: Option<f32>,
    /// Min-height in pixels
    pub min_height: Option<f32>,
    /// Max-height in pixels
    pub max_height: Option<f32>,
    /// Padding [top, right, bottom, left] in pixels
    pub padding: Option<[f32; 4]>,
    /// Margin [top, right, bottom, left] in pixels
    pub margin: Option<[f32; 4]>,
    /// Gap between flex items in pixels
    pub gap: Option<f32>,
    /// Flex grow factor
    pub flex_grow: Option<f32>,
    /// Flex shrink factor
    pub flex_shrink: Option<f32>,

    // --- Positioning (require layout recomputation) ---
    /// top inset in pixels
    pub inset_top: Option<f32>,
    /// right inset in pixels
    pub inset_right: Option<f32>,
    /// bottom inset in pixels
    pub inset_bottom: Option<f32>,
    /// left inset in pixels
    pub inset_left: Option<f32>,

    // --- Text properties ---
    /// Font size in pixels
    pub font_size: Option<f32>,

    // --- Skew ---
    /// Skew X in degrees
    pub skew_x: Option<f32>,
    /// Skew Y in degrees
    pub skew_y: Option<f32>,

    // --- Transform origin ---
    /// Transform origin [x%, y%] (default 50%, 50% = center)
    pub transform_origin: Option<[f32; 2]>,

    // --- Stacking ---
    /// z-index (f32 for smooth interpolation, rounded on apply)
    pub z_index: Option<f32>,

    // --- Mask gradient ---
    /// Combined mask gradient: [mask_type, start_alpha, end_alpha, 0, p0, p1, p2, p3]
    /// where p0..p3 = linear(x1,y1,x2,y2) or radial(cx,cy,r,0) in OBB space
    pub mask_gradient: Option<[f32; 8]>,

    // --- SVG properties ---
    /// SVG fill color RGBA
    pub svg_fill: Option<[f32; 4]>,
    /// SVG stroke color RGBA
    pub svg_stroke: Option<[f32; 4]>,
    /// SVG stroke width in pixels
    pub svg_stroke_width: Option<f32>,
    /// SVG stroke-dashoffset in pixels (for line-drawing animations)
    pub svg_stroke_dashoffset: Option<f32>,
    /// SVG path `d` attribute data (for path morphing animations)
    pub svg_path_data: Option<String>,
}

impl KeyframeProperties {
    /// Create properties with only opacity set
    pub fn opacity(value: f32) -> Self {
        Self {
            opacity: Some(value),
            ..Default::default()
        }
    }

    /// Create properties with uniform scale
    pub fn scale(value: f32) -> Self {
        Self {
            scale_x: Some(value),
            scale_y: Some(value),
            ..Default::default()
        }
    }

    /// Create properties with translation
    pub fn translate(x: f32, y: f32) -> Self {
        Self {
            translate_x: Some(x),
            translate_y: Some(y),
            ..Default::default()
        }
    }

    /// Create properties with rotation
    pub fn rotation(degrees: f32) -> Self {
        Self {
            rotate: Some(degrees),
            ..Default::default()
        }
    }

    /// Builder: set opacity
    pub fn with_opacity(mut self, value: f32) -> Self {
        self.opacity = Some(value);
        self
    }

    /// Builder: set uniform scale
    pub fn with_scale(mut self, value: f32) -> Self {
        self.scale_x = Some(value);
        self.scale_y = Some(value);
        self
    }

    /// Builder: set scale x and y separately
    pub fn with_scale_xy(mut self, x: f32, y: f32) -> Self {
        self.scale_x = Some(x);
        self.scale_y = Some(y);
        self
    }

    /// Builder: set translation
    pub fn with_translate(mut self, x: f32, y: f32) -> Self {
        self.translate_x = Some(x);
        self.translate_y = Some(y);
        self
    }

    /// Builder: set rotation
    pub fn with_rotate(mut self, degrees: f32) -> Self {
        self.rotate = Some(degrees);
        self
    }

    /// Builder: set X rotation (3D tilt)
    pub fn with_rotate_x(mut self, degrees: f32) -> Self {
        self.rotate_x = Some(degrees);
        self
    }

    /// Builder: set Y rotation (3D turn)
    pub fn with_rotate_y(mut self, degrees: f32) -> Self {
        self.rotate_y = Some(degrees);
        self
    }

    /// Builder: set perspective distance
    pub fn with_perspective(mut self, px: f32) -> Self {
        self.perspective = Some(px);
        self
    }

    /// Builder: set 3D depth
    pub fn with_depth(mut self, px: f32) -> Self {
        self.depth = Some(px);
        self
    }

    /// Builder: set translate-z
    pub fn with_translate_z(mut self, px: f32) -> Self {
        self.translate_z = Some(px);
        self
    }

    /// Builder: set 3D blend radius
    pub fn with_blend_3d(mut self, px: f32) -> Self {
        self.blend_3d = Some(px);
        self
    }

    /// Interpolate between two property sets
    pub fn lerp(&self, other: &Self, t: f32) -> Self {
        Self {
            opacity: lerp_opt(self.opacity, other.opacity, t),
            scale_x: lerp_opt(self.scale_x, other.scale_x, t),
            scale_y: lerp_opt(self.scale_y, other.scale_y, t),
            translate_x: lerp_opt(self.translate_x, other.translate_x, t),
            translate_y: lerp_opt(self.translate_y, other.translate_y, t),
            rotate: lerp_opt(self.rotate, other.rotate, t),
            rotate_x: lerp_opt(self.rotate_x, other.rotate_x, t),
            rotate_y: lerp_opt(self.rotate_y, other.rotate_y, t),
            perspective: lerp_opt(self.perspective, other.perspective, t),
            depth: lerp_opt(self.depth, other.depth, t),
            translate_z: lerp_opt(self.translate_z, other.translate_z, t),
            blend_3d: lerp_opt(self.blend_3d, other.blend_3d, t),
            clip_inset: lerp_opt_array4(self.clip_inset, other.clip_inset, t),
            // Color
            background_color: lerp_opt_array4(self.background_color, other.background_color, t),
            gradient_start_color: lerp_opt_array4(
                self.gradient_start_color,
                other.gradient_start_color,
                t,
            ),
            gradient_end_color: lerp_opt_array4(
                self.gradient_end_color,
                other.gradient_end_color,
                t,
            ),
            gradient_angle: lerp_opt(self.gradient_angle, other.gradient_angle, t),
            border_color: lerp_opt_array4(self.border_color, other.border_color, t),
            text_color: lerp_opt_array4(self.text_color, other.text_color, t),
            // Geometric
            corner_radius: lerp_opt_array4(self.corner_radius, other.corner_radius, t),
            corner_shape: lerp_opt_array4(self.corner_shape, other.corner_shape, t),
            border_width: lerp_opt(self.border_width, other.border_width, t),
            outline_width: lerp_opt(self.outline_width, other.outline_width, t),
            outline_color: lerp_opt_array4(self.outline_color, other.outline_color, t),
            outline_offset: lerp_opt(self.outline_offset, other.outline_offset, t),
            clip_circle_radius: lerp_opt(self.clip_circle_radius, other.clip_circle_radius, t),
            clip_ellipse_radii: lerp_opt_array2(
                self.clip_ellipse_radii,
                other.clip_ellipse_radii,
                t,
            ),
            overflow_fade: lerp_opt_array4(self.overflow_fade, other.overflow_fade, t),
            // Shadow
            shadow_params: lerp_opt_array4(self.shadow_params, other.shadow_params, t),
            shadow_color: lerp_opt_array4(self.shadow_color, other.shadow_color, t),
            text_shadow_params: lerp_opt_array4(
                self.text_shadow_params,
                other.text_shadow_params,
                t,
            ),
            text_shadow_color: lerp_opt_array4(self.text_shadow_color, other.text_shadow_color, t),
            // 3D lighting
            light_intensity: lerp_opt(self.light_intensity, other.light_intensity, t),
            ambient: lerp_opt(self.ambient, other.ambient, t),
            specular: lerp_opt(self.specular, other.specular, t),
            light_direction: lerp_opt_array3(self.light_direction, other.light_direction, t),
            // Filters
            filter_grayscale: lerp_opt(self.filter_grayscale, other.filter_grayscale, t),
            filter_invert: lerp_opt(self.filter_invert, other.filter_invert, t),
            filter_sepia: lerp_opt(self.filter_sepia, other.filter_sepia, t),
            filter_brightness: lerp_opt(self.filter_brightness, other.filter_brightness, t),
            filter_contrast: lerp_opt(self.filter_contrast, other.filter_contrast, t),
            filter_saturate: lerp_opt(self.filter_saturate, other.filter_saturate, t),
            filter_hue_rotate: lerp_opt(self.filter_hue_rotate, other.filter_hue_rotate, t),
            filter_blur: lerp_opt(self.filter_blur, other.filter_blur, t),
            // Backdrop filter
            backdrop_blur: lerp_opt(self.backdrop_blur, other.backdrop_blur, t),
            backdrop_saturation: lerp_opt(self.backdrop_saturation, other.backdrop_saturation, t),
            backdrop_brightness: lerp_opt(self.backdrop_brightness, other.backdrop_brightness, t),
            // Layout
            width: lerp_opt(self.width, other.width, t),
            height: lerp_opt(self.height, other.height, t),
            min_width: lerp_opt(self.min_width, other.min_width, t),
            max_width: lerp_opt(self.max_width, other.max_width, t),
            min_height: lerp_opt(self.min_height, other.min_height, t),
            max_height: lerp_opt(self.max_height, other.max_height, t),
            padding: lerp_opt_array4(self.padding, other.padding, t),
            margin: lerp_opt_array4(self.margin, other.margin, t),
            gap: lerp_opt(self.gap, other.gap, t),
            flex_grow: lerp_opt(self.flex_grow, other.flex_grow, t),
            flex_shrink: lerp_opt(self.flex_shrink, other.flex_shrink, t),
            // Positioning
            inset_top: lerp_opt(self.inset_top, other.inset_top, t),
            inset_right: lerp_opt(self.inset_right, other.inset_right, t),
            inset_bottom: lerp_opt(self.inset_bottom, other.inset_bottom, t),
            inset_left: lerp_opt(self.inset_left, other.inset_left, t),
            // Text properties
            font_size: lerp_opt(self.font_size, other.font_size, t),
            // Skew
            skew_x: lerp_opt(self.skew_x, other.skew_x, t),
            skew_y: lerp_opt(self.skew_y, other.skew_y, t),
            // Transform origin
            transform_origin: lerp_opt_array2(self.transform_origin, other.transform_origin, t),
            // Stacking
            z_index: lerp_opt(self.z_index, other.z_index, t),
            // Mask gradient
            mask_gradient: lerp_opt_array8(self.mask_gradient, other.mask_gradient, t),
            // SVG
            svg_fill: lerp_opt_array4(self.svg_fill, other.svg_fill, t),
            svg_stroke: lerp_opt_array4(self.svg_stroke, other.svg_stroke, t),
            svg_stroke_width: lerp_opt(self.svg_stroke_width, other.svg_stroke_width, t),
            svg_stroke_dashoffset: lerp_opt(
                self.svg_stroke_dashoffset,
                other.svg_stroke_dashoffset,
                t,
            ),
            svg_path_data: lerp_path_data(&self.svg_path_data, &other.svg_path_data, t),
        }
    }

    /// Get the resolved opacity (defaults to 1.0 if not set)
    pub fn resolved_opacity(&self) -> f32 {
        self.opacity.unwrap_or(1.0)
    }

    /// Get the resolved scale (defaults to 1.0 if not set)
    pub fn resolved_scale(&self) -> (f32, f32) {
        (self.scale_x.unwrap_or(1.0), self.scale_y.unwrap_or(1.0))
    }

    /// Get the resolved translation (defaults to 0.0 if not set)
    pub fn resolved_translate(&self) -> (f32, f32) {
        (
            self.translate_x.unwrap_or(0.0),
            self.translate_y.unwrap_or(0.0),
        )
    }

    /// Get the resolved rotation (defaults to 0.0 if not set)
    pub fn resolved_rotate(&self) -> f32 {
        self.rotate.unwrap_or(0.0)
    }

    /// Get the resolved X rotation in degrees (defaults to 0.0)
    pub fn resolved_rotate_x(&self) -> f32 {
        self.rotate_x.unwrap_or(0.0)
    }

    /// Get the resolved Y rotation in degrees (defaults to 0.0)
    pub fn resolved_rotate_y(&self) -> f32 {
        self.rotate_y.unwrap_or(0.0)
    }

    /// Get the resolved perspective distance (defaults to 0.0 = no perspective)
    pub fn resolved_perspective(&self) -> f32 {
        self.perspective.unwrap_or(0.0)
    }

    /// Get the resolved 3D depth (defaults to 0.0 = flat)
    pub fn resolved_depth(&self) -> f32 {
        self.depth.unwrap_or(0.0)
    }
}

/// Helper to interpolate optional values
fn lerp_opt(a: Option<f32>, b: Option<f32>, t: f32) -> Option<f32> {
    match (a, b) {
        (Some(a), Some(b)) => Some(a + (b - a) * t),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Helper to interpolate optional [f32; 2] arrays
fn lerp_opt_array2(a: Option<[f32; 2]>, b: Option<[f32; 2]>, t: f32) -> Option<[f32; 2]> {
    match (a, b) {
        (Some(a), Some(b)) => Some([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Helper to interpolate optional [f32; 3] arrays
fn lerp_opt_array3(a: Option<[f32; 3]>, b: Option<[f32; 3]>, t: f32) -> Option<[f32; 3]> {
    match (a, b) {
        (Some(a), Some(b)) => Some([
            a[0] + (b[0] - a[0]) * t,
            a[1] + (b[1] - a[1]) * t,
            a[2] + (b[2] - a[2]) * t,
        ]),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// Helper to interpolate optional SVG path data strings via morph engine
fn lerp_path_data(a: &Option<String>, b: &Option<String>, t: f32) -> Option<String> {
    match (a, b) {
        (Some(from), Some(to)) => {
            crate::morph::interpolate_paths(from, to, t).or_else(|| Some(to.clone()))
        }
        (Some(s), None) => Some(s.clone()),
        (None, Some(s)) => Some(s.clone()),
        (None, None) => None,
    }
}

/// Helper to interpolate optional [f32; 4] arrays
fn lerp_opt_array4(a: Option<[f32; 4]>, b: Option<[f32; 4]>, t: f32) -> Option<[f32; 4]> {
    match (a, b) {
        (Some(a), Some(b)) => Some([
            a[0] + (b[0] - a[0]) * t,
            a[1] + (b[1] - a[1]) * t,
            a[2] + (b[2] - a[2]) * t,
            a[3] + (b[3] - a[3]) * t,
        ]),
        // Fade towards zero when one side is None (e.g. color → transparent,
        // padding → removed). This is correct for CSS transitions where None
        // means "property not set in this state" rather than "keep previous value".
        (Some(a), None) => Some([
            a[0] * (1.0 - t),
            a[1] * (1.0 - t),
            a[2] * (1.0 - t),
            a[3] * (1.0 - t),
        ]),
        (None, Some(b)) => Some([b[0] * t, b[1] * t, b[2] * t, b[3] * t]),
        (None, None) => None,
    }
}

fn lerp_opt_array8(a: Option<[f32; 8]>, b: Option<[f32; 8]>, t: f32) -> Option<[f32; 8]> {
    match (a, b) {
        (Some(a), Some(b)) => Some([
            a[0] + (b[0] - a[0]) * t,
            a[1] + (b[1] - a[1]) * t,
            a[2] + (b[2] - a[2]) * t,
            a[3] + (b[3] - a[3]) * t,
            a[4] + (b[4] - a[4]) * t,
            a[5] + (b[5] - a[5]) * t,
            a[6] + (b[6] - a[6]) * t,
            a[7] + (b[7] - a[7]) * t,
        ]),
        (Some(a), None) => {
            let s = 1.0 - t;
            Some([
                a[0] * s,
                a[1] * s,
                a[2] * s,
                a[3] * s,
                a[4] * s,
                a[5] * s,
                a[6] * s,
                a[7] * s,
            ])
        }
        (None, Some(b)) => Some([
            b[0] * t,
            b[1] * t,
            b[2] * t,
            b[3] * t,
            b[4] * t,
            b[5] * t,
            b[6] * t,
            b[7] * t,
        ]),
        (None, None) => None,
    }
}

/// A keyframe with multiple animated properties
#[derive(Clone, Debug)]
pub struct MultiKeyframe {
    /// Time position (0.0 to 1.0)
    pub time: f32,
    /// Properties at this keyframe
    pub properties: KeyframeProperties,
    /// Easing function to use when transitioning TO this keyframe
    pub easing: Easing,
}

impl MultiKeyframe {
    /// Create a new multi-property keyframe
    pub fn new(time: f32, properties: KeyframeProperties, easing: Easing) -> Self {
        Self {
            time,
            properties,
            easing,
        }
    }
}

/// Playback direction for animations
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlayDirection {
    /// Play forward (0.0 -> 1.0)
    #[default]
    Forward,
    /// Play in reverse (1.0 -> 0.0)
    Reverse,
    /// Alternate between forward and reverse each iteration
    Alternate,
}

/// Fill mode determines the animation state before/after playback
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FillMode {
    /// No fill - reset to initial state after animation
    #[default]
    None,
    /// Hold the final keyframe value after animation completes
    Forwards,
    /// Apply the first keyframe value before animation starts
    Backwards,
    /// Apply both forwards and backwards fill
    Both,
}

/// Multi-property keyframe animation
#[derive(Clone, Debug)]
pub struct MultiKeyframeAnimation {
    /// Duration in milliseconds
    duration_ms: u32,
    /// Keyframes sorted by time
    keyframes: Vec<MultiKeyframe>,
    /// Current time in milliseconds
    current_time: f32,
    /// Whether animation is playing
    playing: bool,
    /// Playback direction
    direction: PlayDirection,
    /// Fill mode
    fill_mode: FillMode,
    /// Number of iterations (-1 for infinite)
    iterations: i32,
    /// Current iteration count
    current_iteration: i32,
    /// Whether currently playing in reverse (for Alternate)
    reversed: bool,
    /// Delay before animation starts (ms)
    delay_ms: u32,
}

impl MultiKeyframeAnimation {
    /// Create a new multi-property animation with given duration
    pub fn new(duration_ms: u32) -> Self {
        Self {
            duration_ms,
            keyframes: Vec::new(),
            current_time: 0.0,
            playing: false,
            direction: PlayDirection::Forward,
            fill_mode: FillMode::Forwards,
            iterations: 1,
            current_iteration: 0,
            reversed: false,
            delay_ms: 0,
        }
    }

    /// Add a keyframe to the animation (builder pattern)
    pub fn keyframe(mut self, time: f32, properties: KeyframeProperties, easing: Easing) -> Self {
        self.keyframes
            .push(MultiKeyframe::new(time, properties, easing));
        // Keep keyframes sorted by time
        self.keyframes
            .sort_by(|a, b| a.time.partial_cmp(&b.time).unwrap());
        self
    }

    /// Set playback direction
    pub fn direction(mut self, direction: PlayDirection) -> Self {
        self.direction = direction;
        self
    }

    /// Set fill mode
    pub fn fill_mode(mut self, fill_mode: FillMode) -> Self {
        self.fill_mode = fill_mode;
        self
    }

    /// Set number of iterations (-1 for infinite)
    pub fn iterations(mut self, count: i32) -> Self {
        self.iterations = count;
        self
    }

    /// Set delay before animation starts
    pub fn delay(mut self, delay_ms: u32) -> Self {
        self.delay_ms = delay_ms;
        self
    }

    // =========================================================================
    // Mutating setters (for post-construction configuration)
    // =========================================================================

    /// Set playback direction (mutating)
    pub fn set_direction(&mut self, direction: PlayDirection) {
        self.direction = direction;
    }

    /// Set fill mode (mutating)
    pub fn set_fill_mode(&mut self, fill_mode: FillMode) {
        self.fill_mode = fill_mode;
    }

    /// Set number of iterations (mutating, -1 for infinite)
    pub fn set_iterations(&mut self, count: i32) {
        self.iterations = count;
    }

    /// Set delay before animation starts (mutating)
    pub fn set_delay(&mut self, delay_ms: u32) {
        self.delay_ms = delay_ms;
    }

    /// Set reversed state (mutating)
    ///
    /// When true, animation plays in reverse direction for the current iteration.
    /// Used internally for Alternate direction and for AlternateReverse start.
    pub fn set_reversed(&mut self, reversed: bool) {
        self.reversed = reversed;
    }

    /// Start the animation
    pub fn start(&mut self) {
        self.current_time = -(self.delay_ms as f32);
        self.current_iteration = 0;
        self.reversed = self.direction == PlayDirection::Reverse;
        self.playing = true;
    }

    /// Stop the animation
    pub fn stop(&mut self) {
        self.playing = false;
    }

    /// Check if the animation is currently playing
    pub fn is_playing(&self) -> bool {
        self.playing
    }

    /// Get the current progress (0.0 to 1.0)
    pub fn progress(&self) -> f32 {
        if self.current_time < 0.0 {
            return 0.0;
        }
        (self.current_time / self.duration_ms as f32).clamp(0.0, 1.0)
    }

    /// Get the current interpolated properties
    pub fn current_properties(&self) -> KeyframeProperties {
        if self.keyframes.is_empty() {
            return KeyframeProperties::default();
        }

        // Handle delay period
        if self.current_time < 0.0 {
            return match self.fill_mode {
                FillMode::Backwards | FillMode::Both => self.keyframes[0].properties.clone(),
                _ => KeyframeProperties::default(),
            };
        }

        let mut progress = self.progress();

        // Apply reverse if needed
        if self.reversed {
            progress = 1.0 - progress;
        }

        // Find surrounding keyframes
        let mut prev_kf = &self.keyframes[0];
        let mut next_kf = &self.keyframes[0];

        for kf in &self.keyframes {
            if kf.time <= progress {
                prev_kf = kf;
            }
            if kf.time >= progress {
                next_kf = kf;
                break;
            }
        }

        if (prev_kf.time - next_kf.time).abs() < f32::EPSILON {
            return prev_kf.properties.clone();
        }

        // Interpolate between keyframes
        let local_progress = (progress - prev_kf.time) / (next_kf.time - prev_kf.time);
        let eased = next_kf.easing.apply(local_progress);

        prev_kf.properties.lerp(&next_kf.properties, eased)
    }

    /// Advance the animation by delta time (in milliseconds)
    pub fn tick(&mut self, dt_ms: f32) {
        if !self.playing {
            return;
        }

        self.current_time += dt_ms;

        // Check if we've completed an iteration
        if self.current_time >= self.duration_ms as f32 {
            self.current_iteration += 1;

            // Check if we should continue (infinite or more iterations remaining)
            if self.iterations < 0 || self.current_iteration < self.iterations {
                // Reset for next iteration
                self.current_time = 0.0;

                // Handle alternate direction
                if self.direction == PlayDirection::Alternate {
                    self.reversed = !self.reversed;
                }
            } else {
                // Animation complete
                self.current_time = self.duration_ms as f32;
                self.playing = false;
            }
        }
    }

    /// Get the duration in milliseconds
    pub fn duration_ms(&self) -> u32 {
        self.duration_ms
    }

    /// Get the delay in milliseconds
    pub fn delay_ms(&self) -> u32 {
        self.delay_ms
    }

    /// Get total duration including delay
    pub fn total_duration_ms(&self) -> u32 {
        self.delay_ms + self.duration_ms
    }

    /// Get the first keyframe (if any)
    pub fn first_keyframe(&self) -> Option<&MultiKeyframe> {
        self.keyframes.first()
    }

    /// Get the last keyframe (if any)
    pub fn last_keyframe(&self) -> Option<&MultiKeyframe> {
        self.keyframes.last()
    }

    /// Get all keyframes
    pub fn keyframes(&self) -> &[MultiKeyframe] {
        &self.keyframes
    }

    /// Sample the animation at a specific progress (0.0 to 1.0)
    ///
    /// This is useful for externally-timed animations where you manage
    /// the progress yourself rather than using tick().
    pub fn sample_at(&self, progress: f32) -> KeyframeProperties {
        if self.keyframes.is_empty() {
            return KeyframeProperties::default();
        }

        let progress = progress.clamp(0.0, 1.0);

        // Find surrounding keyframes
        let mut prev_kf = &self.keyframes[0];
        let mut next_kf = &self.keyframes[0];

        for kf in &self.keyframes {
            if kf.time <= progress {
                prev_kf = kf;
            }
            if kf.time >= progress {
                next_kf = kf;
                break;
            }
        }

        if (prev_kf.time - next_kf.time).abs() < f32::EPSILON {
            return prev_kf.properties.clone();
        }

        // Interpolate between keyframes
        let local_progress = (progress - prev_kf.time) / (next_kf.time - prev_kf.time);
        let eased = next_kf.easing.apply(local_progress);

        prev_kf.properties.lerp(&next_kf.properties, eased)
    }
}

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

// ============================================================================
// Keyframe Track Builder - Fluent API for single-value keyframe animations
// ============================================================================

/// A point in time with a value for keyframe animation
#[derive(Clone, Debug)]
pub struct KeyframePoint {
    /// Time in milliseconds
    pub time_ms: u32,
    /// Value at this time
    pub value: f32,
    /// Easing to use when transitioning TO this point
    pub easing: Easing,
}

/// Builder for creating keyframe animations with a fluent API
///
/// # Example
///
/// ```ignore
/// let track = KeyframeTrackBuilder::new()
///     .at(0, 0.8)
///     .at(800, 1.2)
///     .ease(Easing::EaseInOut)
///     .ping_pong()
///     .loop_infinite()
///     .build();
/// ```
#[derive(Clone, Debug)]
pub struct KeyframeTrackBuilder {
    /// Keyframe points (time_ms, value)
    points: Vec<KeyframePoint>,
    /// Default easing for all keyframes (can be overridden per-keyframe)
    default_easing: Easing,
    /// Play direction
    direction: PlayDirection,
    /// Number of iterations (-1 for infinite)
    iterations: i32,
    /// Delay before starting (ms)
    delay_ms: u32,
    /// Fill mode
    fill_mode: FillMode,
    /// Whether to auto-start
    auto_start: bool,
}

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

impl KeyframeTrackBuilder {
    /// Create a new keyframe track builder
    pub fn new() -> Self {
        Self {
            points: Vec::new(),
            default_easing: Easing::Linear,
            direction: PlayDirection::Forward,
            iterations: 1,
            delay_ms: 0,
            fill_mode: FillMode::Forwards,
            auto_start: false,
        }
    }

    /// Add a keyframe at a specific time (in milliseconds)
    pub fn at(mut self, time_ms: u32, value: f32) -> Self {
        self.points.push(KeyframePoint {
            time_ms,
            value,
            easing: self.default_easing,
        });
        self
    }

    /// Add a keyframe with specific easing
    pub fn at_with_ease(mut self, time_ms: u32, value: f32, easing: Easing) -> Self {
        self.points.push(KeyframePoint {
            time_ms,
            value,
            easing,
        });
        self
    }

    /// Set the default easing for all keyframes
    ///
    /// This applies to keyframes added after this call, and updates
    /// existing keyframes that haven't had explicit easing set.
    pub fn ease(mut self, easing: Easing) -> Self {
        self.default_easing = easing;
        // Update existing points that use the default
        for point in &mut self.points {
            point.easing = easing;
        }
        self
    }

    /// Enable ping-pong mode (alternate between forward and reverse)
    ///
    /// The animation plays forward, then backward, creating a smooth
    /// back-and-forth effect without needing duplicate keyframes.
    pub fn ping_pong(mut self) -> Self {
        self.direction = PlayDirection::Alternate;
        self
    }

    /// Alias for ping_pong()
    pub fn alternate(self) -> Self {
        self.ping_pong()
    }

    /// Play in reverse direction
    pub fn reverse(mut self) -> Self {
        self.direction = PlayDirection::Reverse;
        self
    }

    /// Set the number of loop iterations
    pub fn loop_count(mut self, count: i32) -> Self {
        self.iterations = count;
        self
    }

    /// Loop infinitely
    pub fn loop_infinite(mut self) -> Self {
        self.iterations = -1;
        self
    }

    /// Set delay before animation starts (in milliseconds)
    pub fn delay(mut self, delay_ms: u32) -> Self {
        self.delay_ms = delay_ms;
        self
    }

    /// Set fill mode (what happens before/after animation)
    pub fn fill(mut self, fill_mode: FillMode) -> Self {
        self.fill_mode = fill_mode;
        self
    }

    /// Auto-start the animation when built
    pub fn start(mut self) -> Self {
        self.auto_start = true;
        self
    }

    /// Get the total duration based on keyframe times
    pub fn duration_ms(&self) -> u32 {
        self.points.iter().map(|p| p.time_ms).max().unwrap_or(0)
    }

    /// Build into a KeyframeTrack
    pub fn build(mut self) -> KeyframeTrack {
        // Sort points by time
        self.points.sort_by_key(|p| p.time_ms);

        let duration = self.duration_ms();

        // Convert to normalized keyframes (time as 0.0-1.0)
        let keyframes: Vec<Keyframe> = self
            .points
            .iter()
            .map(|p| {
                let time = if duration > 0 {
                    p.time_ms as f32 / duration as f32
                } else {
                    0.0
                };
                Keyframe {
                    time,
                    value: p.value,
                    easing: p.easing,
                }
            })
            .collect();

        let mut animation = KeyframeAnimation::new(duration, keyframes);

        if self.auto_start {
            animation.start();
        }

        KeyframeTrack {
            animation,
            direction: self.direction,
            iterations: self.iterations,
            current_iteration: 0,
            reversed: self.direction == PlayDirection::Reverse,
            delay_ms: self.delay_ms,
            fill_mode: self.fill_mode,
            duration_ms: duration,
        }
    }
}

/// A complete keyframe track with playback controls
///
/// Wraps KeyframeAnimation with additional features like ping-pong,
/// looping, and fill modes.
#[derive(Clone, Debug)]
pub struct KeyframeTrack {
    animation: KeyframeAnimation,
    direction: PlayDirection,
    iterations: i32,
    current_iteration: i32,
    reversed: bool,
    #[allow(dead_code)] // Reserved for future delay support
    delay_ms: u32,
    #[allow(dead_code)] // Reserved for future fill mode support
    fill_mode: FillMode,
    duration_ms: u32,
}

impl KeyframeTrack {
    /// Create a new builder
    pub fn builder() -> KeyframeTrackBuilder {
        KeyframeTrackBuilder::new()
    }

    /// Start the animation
    pub fn start(&mut self) {
        self.current_iteration = 0;
        self.reversed = self.direction == PlayDirection::Reverse;
        self.animation.start();
    }

    /// Stop the animation
    pub fn stop(&mut self) {
        self.animation.stop();
    }

    /// Restart the animation from the beginning
    pub fn restart(&mut self) {
        self.start();
    }

    /// Check if the animation is playing
    pub fn is_playing(&self) -> bool {
        self.animation.is_playing() || self.should_continue()
    }

    /// Check if we should continue to next iteration
    fn should_continue(&self) -> bool {
        self.iterations < 0 || self.current_iteration < self.iterations
    }

    /// Get the current value with ping-pong and iteration support
    pub fn value(&self) -> f32 {
        let keyframes = self.animation.keyframes();
        if keyframes.is_empty() {
            return 0.0;
        }

        let progress = self.animation.progress().clamp(0.0, 1.0);

        // Apply reverse if in ping-pong mode and on reverse phase
        let effective_progress = if self.reversed {
            1.0 - progress
        } else {
            progress
        };

        // Find surrounding keyframes
        let mut prev_kf = &keyframes[0];
        let mut next_kf = &keyframes[0];

        for kf in keyframes {
            if kf.time <= effective_progress {
                prev_kf = kf;
            }
            if kf.time >= effective_progress {
                next_kf = kf;
                break;
            }
        }

        if (prev_kf.time - next_kf.time).abs() < f32::EPSILON {
            return prev_kf.value;
        }

        // Interpolate between keyframes
        let local_progress = (effective_progress - prev_kf.time) / (next_kf.time - prev_kf.time);
        let eased = next_kf.easing.apply(local_progress);

        prev_kf.value + (next_kf.value - prev_kf.value) * eased
    }

    /// Get the current progress (0.0 to 1.0)
    pub fn progress(&self) -> f32 {
        let progress = self.animation.progress();
        if self.reversed {
            1.0 - progress
        } else {
            progress
        }
    }

    /// Advance the animation by delta time (in milliseconds)
    pub fn tick(&mut self, dt_ms: f32) {
        self.animation.tick(dt_ms);

        // Check if we've completed an iteration
        if self.animation.progress() >= 1.0 && !self.animation.is_playing() {
            self.current_iteration += 1;

            // Check if we should continue
            if self.iterations < 0 || self.current_iteration < self.iterations {
                // Reset for next iteration
                self.animation.start();

                // Handle alternate direction
                if self.direction == PlayDirection::Alternate {
                    self.reversed = !self.reversed;
                }
            }
        }
    }

    /// Get the duration in milliseconds
    pub fn duration_ms(&self) -> u32 {
        self.duration_ms
    }
}