hyperchad_actions 0.3.0

HyperChad actions package
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
//! Conditional logic and dynamic value evaluation for actions
//!
//! This module provides types and functions for creating conditional actions that respond to
//! runtime state, such as element visibility, display properties, mouse position, and more.
//!
//! # Core Types
//!
//! * [`crate::logic::Value`] - Dynamic values that can be calculated at runtime
//! * [`crate::logic::CalcValue`] - Computed values from element state (visibility, dimensions, position, etc.)
//! * [`crate::logic::Condition`] - Conditional expressions for if-then-else logic
//! * [`crate::logic::If`] - Conditional action execution based on conditions
//! * [`crate::logic::Arithmetic`] - Mathematical operations on dynamic values
//!
//! # Example
//!
//! ```rust
//! use hyperchad_actions::logic::{get_visibility_by_id, visible, If};
//! use hyperchad_actions::ActionType;
//!
//! // Create a conditional action that shows an element if another is visible
//! let condition = get_visibility_by_id("other-element").eq(visible());
//! let if_action = condition.then(ActionType::show_by_id("my-element"));
//! ```

use hyperchad_transformer_models::{LayoutDirection, Visibility};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{Action, ActionEffect, ActionType, ElementTarget, Key, Target};

/// Computed value from element or event state
///
/// Represents a value that is calculated at runtime based on element properties,
/// mouse position, or event data. These values are used in conditional logic and
/// parameterized actions.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CalcValue {
    /// Get visibility state of an element
    Visibility {
        /// Target element
        target: ElementTarget,
    },
    /// Get display state of an element
    Display {
        /// Target element
        target: ElementTarget,
    },
    /// Get element ID of an element
    Id {
        /// Target element
        target: ElementTarget,
    },
    /// Get data attribute value from an element
    DataAttrValue {
        /// Attribute name
        attr: String,
        /// Target element
        target: ElementTarget,
    },
    /// Get current event value (e.g., input field value)
    EventValue,
    /// Get width in pixels of an element
    WidthPx {
        /// Target element
        target: ElementTarget,
    },
    /// Get height in pixels of an element
    HeightPx {
        /// Target element
        target: ElementTarget,
    },
    /// Get X position of an element
    PositionX {
        /// Target element
        target: ElementTarget,
    },
    /// Get Y position of an element
    PositionY {
        /// Target element
        target: ElementTarget,
    },
    /// Get mouse X coordinate (optionally relative to element)
    MouseX {
        /// Optional target element for relative coordinates
        target: Option<ElementTarget>,
    },
    /// Get mouse Y coordinate (optionally relative to element)
    MouseY {
        /// Optional target element for relative coordinates
        target: Option<ElementTarget>,
    },
    /// Get keyboard key value
    Key {
        /// Keyboard key
        key: Key,
    },
}

impl CalcValue {
    /// Creates an equality condition comparing this value to another
    #[must_use]
    pub fn eq(self, other: impl Into<Value>) -> Condition {
        Condition::Eq(self.into(), other.into())
    }

    /// Adds another value to this value
    #[must_use]
    pub fn plus(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Plus(self.into(), other.into())
    }

    /// Subtracts another value from this value
    #[must_use]
    pub fn minus(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Minus(self.into(), other.into())
    }

    /// Multiplies this value by another value
    #[must_use]
    pub fn multiply(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Multiply(self.into(), other.into())
    }

    /// Divides this value by another value
    #[must_use]
    pub fn divide(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Divide(self.into(), other.into())
    }

    /// Returns the minimum of this value and another
    #[must_use]
    pub fn min(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Min(self.into(), other.into())
    }

    /// Returns the maximum of this value and another
    #[must_use]
    pub fn max(self, other: impl Into<Value>) -> Arithmetic {
        Arithmetic::Max(self.into(), other.into())
    }

    /// Clamps this value between min and max bounds
    #[must_use]
    pub fn clamp(self, min: impl Into<Value>, max: impl Into<Value>) -> Arithmetic {
        Arithmetic::Min(max.into(), Arithmetic::Max(self.into(), min.into()).into())
    }

    /// Creates a parameterized action that passes this value to the action
    #[must_use]
    pub fn then_pass_to(self, other: impl Into<ActionType>) -> ActionType {
        ActionType::Parameterized {
            action: Box::new(other.into()),
            value: Value::Calc(self),
        }
    }
}

/// Dynamic value type that can be calculated or provided at runtime
///
/// Values can be computed from element state, arithmetic operations, or literal values.
/// They are evaluated during action execution to enable conditional and data-driven behaviors.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum Value {
    // IF YOU ADD A NEW VALUE TYPE, ADD IT TO THE DESERIALIZE IMPL BELOW
    /// Computed value from element or event state
    Calc(CalcValue),
    /// Arithmetic operation result
    Arithmetic(Box<Arithmetic>),
    /// Numeric value
    Real(f32),
    /// Visibility state value
    Visibility(Visibility),
    /// Display state value
    Display(bool),
    /// Layout direction value
    LayoutDirection(LayoutDirection),
    /// String value
    String(String),
    /// Keyboard key value
    Key(Key),
}

impl From<Key> for Value {
    /// Converts a keyboard `Key` into a `Value`
    fn from(value: Key) -> Self {
        Self::Key(value)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Value {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error as _;

        #[derive(Deserialize)]
        #[serde(rename = "Value")]
        enum ValueInner {
            Calc(CalcValue),
            Arithmetic(Box<Arithmetic>),
            Real(f32),
            Visibility(Visibility),
            Display(bool),
            LayoutDirection(LayoutDirection),
            String(String),
        }

        impl From<ValueInner> for Value {
            fn from(value: ValueInner) -> Self {
                match value {
                    ValueInner::Calc(x) => Self::Calc(x),
                    ValueInner::Arithmetic(x) => Self::Arithmetic(x),
                    ValueInner::Real(x) => Self::Real(x),
                    ValueInner::Visibility(x) => Self::Visibility(x),
                    ValueInner::Display(x) => Self::Display(x),
                    ValueInner::LayoutDirection(x) => Self::LayoutDirection(x),
                    ValueInner::String(x) => Self::String(x),
                }
            }
        }

        log::trace!("attempting to deserialize Value");
        let value: serde_json::Value = serde_json::Value::deserialize(deserializer)?;
        log::trace!("deserialized Value to {value:?}");

        Ok(if value.is_i64() {
            #[allow(clippy::cast_precision_loss)]
            Self::Real(value.as_i64().unwrap() as f32)
        } else if value.is_u64() {
            #[allow(clippy::cast_precision_loss)]
            Self::Real(value.as_u64().unwrap() as f32)
        } else if value.is_f64() {
            #[allow(clippy::cast_possible_truncation)]
            Self::Real(value.as_f64().unwrap() as f32)
        } else {
            serde_json::from_value::<ValueInner>(value)
                .map_err(D::Error::custom)?
                .into()
        })
    }
}

impl Value {
    /// Creates an equality condition comparing this value to another
    #[must_use]
    pub fn eq(self, other: impl Into<Self>) -> Condition {
        Condition::Eq(self, other.into())
    }

    /// Converts this value to a string slice if possible
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(str) => Some(str),
            Self::Key(key) => Some(key.as_str()),
            Self::Arithmetic(..)
            | Self::Calc(..)
            | Self::Real(..)
            | Self::Visibility(..)
            | Self::Display(..)
            | Self::LayoutDirection(..) => None,
        }
    }

    /// Converts this value to an `f32` if possible, optionally evaluating calculated values
    #[must_use]
    pub fn as_f32(&self, calc_func: Option<&impl Fn(&CalcValue) -> Option<Self>>) -> Option<f32> {
        match self {
            Self::Arithmetic(x) => x.as_f32(calc_func),
            Self::Calc(x) => calc_func
                .and_then(|func| func(x))
                .and_then(|x| x.as_f32(calc_func)),
            Self::Real(x) => Some(*x),
            Self::Visibility(..)
            | Self::Display(..)
            | Self::String(..)
            | Self::Key(..)
            | Self::LayoutDirection(..) => None,
        }
    }
}

impl From<CalcValue> for Value {
    /// Converts a `CalcValue` into a `Value`
    fn from(value: CalcValue) -> Self {
        Self::Calc(value)
    }
}

impl From<Visibility> for Value {
    /// Converts a `Visibility` into a `Value`
    fn from(value: Visibility) -> Self {
        Self::Visibility(value)
    }
}

impl From<f32> for Value {
    /// Converts an `f32` into a `Value`
    fn from(value: f32) -> Self {
        Self::Real(value)
    }
}

impl From<f64> for Value {
    /// Converts an `f64` into a `Value` (with precision loss)
    fn from(value: f64) -> Self {
        #[allow(clippy::cast_possible_truncation)]
        Self::Real(value as f32)
    }
}

impl From<LayoutDirection> for Value {
    /// Converts a `LayoutDirection` into a `Value`
    fn from(value: LayoutDirection) -> Self {
        Self::LayoutDirection(value)
    }
}

/// Conditional expression for if-then-else logic
///
/// Conditions are evaluated to determine which branch of actions to execute.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Condition {
    /// Boolean literal condition
    Bool(bool),
    /// Equality comparison between two values
    Eq(Value, Value),
}

impl Condition {
    /// Creates an if-then action with this condition
    #[must_use]
    pub fn then(self, action: impl Into<ActionEffect>) -> If {
        If {
            condition: self,
            actions: vec![action.into()],
            else_actions: vec![],
        }
    }

    /// Creates an if-else action with this condition
    #[must_use]
    pub fn or_else(self, action: impl Into<ActionEffect>) -> If {
        If {
            condition: self,
            actions: vec![],
            else_actions: vec![action.into()],
        }
    }
}

/// Conditional expression for value selection
///
/// Similar to [`Condition`] but used for selecting between values rather than actions.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ConditionExpression {
    /// Equality comparison between two values
    Eq(Value, Value),
}

impl ConditionExpression {
    /// Sets the value to use when the condition is true
    #[must_use]
    pub fn then<T>(self, value: impl Into<T>) -> IfExpression<T, Self> {
        IfExpression {
            condition: self,
            value: None,
            default: Some(value.into()),
        }
    }

    /// Sets the value to use when the condition is false
    #[must_use]
    pub fn or_else<T>(self, value: impl Into<T>) -> IfExpression<T, Self> {
        IfExpression {
            condition: self,
            value: None,
            default: Some(value.into()),
        }
    }
}

/// Conditional value expression (if-then-else for values)
///
/// Selects a value based on a condition, similar to a ternary operator.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IfExpression<T, C> {
    /// The condition to evaluate
    pub condition: C,
    /// Value to use when condition is true
    pub value: Option<T>,
    /// Value to use when condition is false
    pub default: Option<T>,
}

impl<T, C> IfExpression<T, C> {
    /// Sets the value to use when the condition is true
    #[must_use]
    pub fn then(mut self, value: impl Into<T>) -> Self {
        self.value.replace(value.into());
        self
    }

    /// Sets the value to use when the condition is false
    #[must_use]
    pub fn or_else(mut self, value: impl Into<T>) -> Self {
        self.default.replace(value.into());
        self
    }
}

#[cfg(feature = "serde")]
impl<T: Serialize, C: Serialize> std::fmt::Display for IfExpression<T, C> {
    /// Formats the conditional expression as JSON
    ///
    /// # Panics
    ///
    /// * If serialization fails (should not happen for valid conditional expressions)
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&serde_json::to_string(self).unwrap())
    }
}

#[cfg(feature = "serde")]
impl<'a, T: for<'de> Deserialize<'de>, C: for<'de> Deserialize<'de>> TryFrom<&'a str>
    for IfExpression<T, C>
{
    type Error = serde_json::Error;

    /// Parses an `IfExpression` from a JSON string
    ///
    /// # Errors
    ///
    /// * If the string is not valid JSON
    /// * If the JSON structure doesn't match `IfExpression`
    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        serde_json::from_str(value)
    }
}

/// Action with a dynamic parameter value
///
/// Associates an action with a dynamically computed value that is passed to the action
/// during execution.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ParameterizedAction {
    /// The action to execute
    action: Action,
    /// The dynamic value parameter
    value: Value,
}

/// Arithmetic operation on dynamic values
///
/// Supports basic mathematical operations and aggregations on values that can be
/// computed at runtime.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Arithmetic {
    /// Addition of two values
    Plus(Value, Value),
    /// Subtraction of two values
    Minus(Value, Value),
    /// Multiplication of two values
    Multiply(Value, Value),
    /// Division of two values
    Divide(Value, Value),
    /// Minimum of two values
    Min(Value, Value),
    /// Maximum of two values
    Max(Value, Value),
    /// Grouped arithmetic expression
    Grouping(Box<Self>),
}

impl Arithmetic {
    /// Evaluates this arithmetic expression to an `f32` value
    #[must_use]
    pub fn as_f32(&self, calc_func: Option<&impl Fn(&CalcValue) -> Option<Value>>) -> Option<f32> {
        match self {
            Self::Plus(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| a + b)),
            Self::Minus(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| a - b)),
            Self::Multiply(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| a * b)),
            Self::Divide(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| a / b)),
            Self::Min(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| if b < a { b } else { a })),
            Self::Max(a, b) => a
                .as_f32(calc_func)
                .and_then(|a| b.as_f32(calc_func).map(|b| if b > a { b } else { a })),
            Self::Grouping(x) => x.as_f32(calc_func),
        }
    }

    /// Creates an equality condition comparing this arithmetic result to another value
    #[must_use]
    pub fn eq(self, other: impl Into<Value>) -> Condition {
        Condition::Eq(self.into(), other.into())
    }

    /// Creates a parameterized action that passes this arithmetic result to the action
    #[must_use]
    pub fn then_pass_to(self, other: impl Into<ActionType>) -> ActionType {
        ActionType::Parameterized {
            action: Box::new(other.into()),
            value: self.into(),
        }
    }

    /// Adds another value to this arithmetic expression
    #[must_use]
    pub fn plus(self, other: impl Into<Value>) -> Self {
        Self::Plus(self.into(), other.into())
    }

    /// Subtracts another value from this arithmetic expression
    #[must_use]
    pub fn minus(self, other: impl Into<Value>) -> Self {
        Self::Minus(self.into(), other.into())
    }

    /// Multiplies this arithmetic expression by another value
    #[must_use]
    pub fn multiply(self, other: impl Into<Value>) -> Self {
        Self::Multiply(self.into(), other.into())
    }

    /// Divides this arithmetic expression by another value
    #[must_use]
    pub fn divide(self, other: impl Into<Value>) -> Self {
        Self::Divide(self.into(), other.into())
    }

    /// Returns the minimum of this arithmetic expression and another value
    #[must_use]
    pub fn min(self, other: impl Into<Value>) -> Self {
        Self::Min(self.into(), other.into())
    }

    /// Returns the maximum of this arithmetic expression and another value
    #[must_use]
    pub fn max(self, other: impl Into<Value>) -> Self {
        Self::Max(self.into(), other.into())
    }

    /// Groups an arithmetic expression for explicit precedence
    #[must_use]
    pub fn group(value: impl Into<Self>) -> Self {
        Self::Grouping(Box::new(value.into()))
    }

    /// Clamps this arithmetic expression between min and max bounds
    #[must_use]
    pub fn clamp(self, min: impl Into<Value>, max: impl Into<Value>) -> Self {
        Self::Min(max.into(), Self::Max(self.into(), min.into()).into())
    }
}

impl From<Arithmetic> for Value {
    /// Converts an `Arithmetic` operation into a `Value`
    fn from(value: Arithmetic) -> Self {
        Self::Arithmetic(Box::new(value))
    }
}

/// Conditional action execution (if-then-else for actions)
///
/// Executes different sets of actions based on a condition evaluated at runtime.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct If {
    /// The condition to evaluate
    pub condition: Condition,
    /// Actions to execute when condition is true
    pub actions: Vec<ActionEffect>,
    /// Actions to execute when condition is false
    pub else_actions: Vec<ActionEffect>,
}

impl If {
    /// Adds an action to execute when the condition is true
    #[must_use]
    pub fn then(mut self, action: impl Into<ActionEffect>) -> Self {
        self.actions.push(action.into());
        self
    }

    /// Adds an action to execute when the condition is false
    #[must_use]
    pub fn or_else(mut self, action: impl Into<ActionEffect>) -> Self {
        self.else_actions.push(action.into());
        self
    }
}

#[cfg(feature = "serde")]
impl std::fmt::Display for If {
    /// Formats the conditional as JSON
    ///
    /// # Panics
    ///
    /// * If serialization fails (should not happen for valid conditionals)
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&serde_json::to_string(self).unwrap())
    }
}

#[cfg(feature = "serde")]
impl<'a> TryFrom<&'a str> for If {
    type Error = serde_json::Error;

    /// Parses an `If` conditional from a JSON string
    ///
    /// # Errors
    ///
    /// * If the string is not valid JSON
    /// * If the JSON structure doesn't match `If`
    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
        serde_json::from_str(value)
    }
}

/// Creates a conditional if statement with a single action
#[must_use]
pub fn if_stmt(condition: Condition, action: impl Into<ActionEffect>) -> If {
    If {
        condition,
        actions: vec![action.into()],
        else_actions: vec![],
    }
}

/// Converts a value into a [`Value`] type
pub fn value(value: impl Into<Value>) -> Value {
    value.into()
}

/// Returns a hidden visibility value
#[must_use]
pub const fn hidden() -> Value {
    Value::Visibility(Visibility::Hidden)
}

/// Returns a visible visibility value
#[must_use]
pub const fn visible() -> Value {
    Value::Visibility(Visibility::Visible)
}

/// Returns a displayed value (display = true)
#[must_use]
pub const fn displayed() -> Value {
    Value::Display(true)
}

/// Returns a not displayed value (display = false)
#[must_use]
pub const fn not_displayed() -> Value {
    Value::Display(false)
}

/// Creates an equality condition between two values
pub fn eq(a: impl Into<Value>, b: impl Into<Value>) -> Condition {
    Condition::Eq(a.into(), b.into())
}

/// Gets the visibility value of an element by numeric ID
#[must_use]
pub const fn get_visibility_id(id: usize) -> CalcValue {
    CalcValue::Visibility {
        target: ElementTarget::Id(id),
    }
}

/// Gets the visibility value of the element itself
#[must_use]
pub const fn get_visibility_self() -> CalcValue {
    CalcValue::Visibility {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the visibility value of an element by class name
#[must_use]
pub fn get_visibility_class(class_name: impl Into<Target>) -> CalcValue {
    CalcValue::Visibility {
        target: ElementTarget::Class(class_name.into()),
    }
}

/// Gets the visibility value of an element by explicit ID lookup
#[must_use]
pub fn get_visibility_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::Visibility {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the visibility value of an element by CSS selector
#[must_use]
pub fn get_visibility_selector(selector: impl Into<Target>) -> CalcValue {
    CalcValue::Visibility {
        target: ElementTarget::Selector(selector.into()),
    }
}

/// Gets the display value of an element by element ID
#[must_use]
pub fn get_display_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the display value of an element by numeric ID
#[must_use]
pub const fn get_display_id(id: usize) -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::Id(id),
    }
}

/// Gets the display value of the element itself
#[must_use]
pub const fn get_display_self() -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the display value of an element by class name
#[must_use]
pub fn get_display_class(class_name: impl Into<Target>) -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::Class(class_name.into()),
    }
}

/// Gets the display value of a child element by class name
#[must_use]
pub fn get_display_child_class(class_name: impl Into<Target>) -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::ChildClass(class_name.into()),
    }
}

/// Gets the display value of the last child element
#[must_use]
pub const fn get_display_last_child() -> CalcValue {
    CalcValue::Display {
        target: ElementTarget::LastChild,
    }
}

/// Gets the current event value (e.g., input field value)
#[must_use]
pub const fn get_event_value() -> CalcValue {
    CalcValue::EventValue
}

/// Gets the element ID of the element itself
#[must_use]
pub const fn get_id_self() -> CalcValue {
    CalcValue::Id {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets a data attribute value from the element itself
#[must_use]
pub fn get_data_attr_value_self(attr: impl Into<String>) -> CalcValue {
    CalcValue::DataAttrValue {
        attr: attr.into(),
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the width in pixels of an element by element ID
#[must_use]
pub fn get_width_px_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::WidthPx {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the width in pixels of an element by numeric ID
#[must_use]
pub const fn get_width_px_id(id: usize) -> CalcValue {
    CalcValue::WidthPx {
        target: ElementTarget::Id(id),
    }
}

/// Gets the width in pixels of the element itself
#[must_use]
pub const fn get_width_px_self() -> CalcValue {
    CalcValue::WidthPx {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the height in pixels of an element by element ID
#[must_use]
pub fn get_height_px_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::HeightPx {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the height in pixels of an element by numeric ID
#[must_use]
pub const fn get_height_px_id(id: usize) -> CalcValue {
    CalcValue::HeightPx {
        target: ElementTarget::Id(id),
    }
}

/// Gets the height in pixels of the element itself
#[must_use]
pub const fn get_height_px_self() -> CalcValue {
    CalcValue::HeightPx {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the X position of an element by element ID
#[must_use]
pub fn get_position_x_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::PositionX {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the X position of an element by numeric ID
#[must_use]
pub const fn get_position_x_id(id: usize) -> CalcValue {
    CalcValue::PositionX {
        target: ElementTarget::Id(id),
    }
}

/// Gets the X position of the element itself
#[must_use]
pub const fn get_position_x_self() -> CalcValue {
    CalcValue::PositionX {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the Y position of an element by element ID
#[must_use]
pub fn get_position_y_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::PositionY {
        target: ElementTarget::ById(id.into()),
    }
}

/// Gets the Y position of an element by numeric ID
#[must_use]
pub const fn get_position_y_id(id: usize) -> CalcValue {
    CalcValue::PositionY {
        target: ElementTarget::Id(id),
    }
}

/// Gets the Y position of the element itself
#[must_use]
pub const fn get_position_y_self() -> CalcValue {
    CalcValue::PositionY {
        target: ElementTarget::SelfTarget,
    }
}

/// Gets the global mouse X coordinate
#[must_use]
pub const fn get_mouse_x() -> CalcValue {
    CalcValue::MouseX { target: None }
}

/// Gets the mouse X coordinate relative to an element by element ID
#[must_use]
pub fn get_mouse_x_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::MouseX {
        target: Some(ElementTarget::ById(id.into())),
    }
}

/// Gets the mouse X coordinate relative to an element by numeric ID
#[must_use]
pub const fn get_mouse_x_id(id: usize) -> CalcValue {
    CalcValue::MouseX {
        target: Some(ElementTarget::Id(id)),
    }
}

/// Gets the mouse X coordinate relative to the element itself
#[must_use]
pub const fn get_mouse_x_self() -> CalcValue {
    CalcValue::MouseX {
        target: Some(ElementTarget::SelfTarget),
    }
}

/// Gets the global mouse Y coordinate
#[must_use]
pub const fn get_mouse_y() -> CalcValue {
    CalcValue::MouseY { target: None }
}

/// Gets the mouse Y coordinate relative to an element by element ID
#[must_use]
pub fn get_mouse_y_by_id(id: impl Into<Target>) -> CalcValue {
    CalcValue::MouseY {
        target: Some(ElementTarget::ById(id.into())),
    }
}

/// Gets the mouse Y coordinate relative to an element by numeric ID
#[must_use]
pub const fn get_mouse_y_id(id: usize) -> CalcValue {
    CalcValue::MouseY {
        target: Some(ElementTarget::Id(id)),
    }
}

/// Gets the mouse Y coordinate relative to the element itself
#[must_use]
pub const fn get_mouse_y_self() -> CalcValue {
    CalcValue::MouseY {
        target: Some(ElementTarget::SelfTarget),
    }
}

/// Responsive design condition for adaptive styling
///
/// Used to create conditional values based on responsive breakpoints or screen targets.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Responsive {
    /// Single responsive target
    Target(String),
    /// Multiple responsive targets (any match)
    Targets(Vec<String>),
}

impl Responsive {
    /// Sets the value to use when the responsive condition matches
    #[must_use]
    pub fn then<T>(self, value: impl Into<T>) -> IfExpression<T, Self> {
        IfExpression {
            condition: self,
            value: Some(value.into()),
            default: None,
        }
    }

    /// Sets the fallback value when the responsive condition doesn't match
    #[must_use]
    pub fn or_else<T>(self, value: impl Into<T>) -> IfExpression<T, Self> {
        IfExpression {
            condition: self,
            value: None,
            default: Some(value.into()),
        }
    }
}

/// Creates a responsive condition for a single target
#[must_use]
pub fn if_responsive(target: impl Into<String>) -> Responsive {
    let target = target.into();
    Responsive::Target(target)
}

/// Creates a responsive condition that matches any of the provided targets
#[must_use]
pub fn if_responsive_any<T: Into<String>>(targets: impl Into<Vec<T>>) -> Responsive {
    Responsive::Targets(targets.into().into_iter().map(Into::into).collect())
}

// Add From implementations for specific enum types to handle responsive expressions
impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::LayoutDirection {
    /// Converts a responsive conditional expression into a `LayoutDirection`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::TextAlign {
    /// Converts a responsive conditional expression into a `TextAlign`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::AlignItems {
    /// Converts a responsive conditional expression into an `AlignItems`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::JustifyContent {
    /// Converts a responsive conditional expression into a `JustifyContent`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::Position {
    /// Converts a responsive conditional expression into a `Position`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

impl From<IfExpression<Self, Responsive>> for hyperchad_transformer_models::LayoutOverflow {
    /// Converts a responsive conditional expression into a `LayoutOverflow`
    fn from(if_expr: IfExpression<Self, Responsive>) -> Self {
        if_expr
            .default
            .unwrap_or_else(|| if_expr.value.unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test_log::test]
    fn test_value_as_str() {
        let string_value = Value::String("test".to_string());
        assert_eq!(string_value.as_str(), Some("test"));

        let key_value = Value::Key(Key::Enter);
        assert_eq!(key_value.as_str(), Some("Enter"));

        let real_value = Value::Real(42.0);
        assert_eq!(real_value.as_str(), None);

        let visibility_value = Value::Visibility(Visibility::Hidden);
        assert_eq!(visibility_value.as_str(), None);
    }

    #[test_log::test]
    fn test_value_as_f32_real() {
        let value = Value::Real(42.5);
        assert_eq!(
            value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>),
            Some(42.5)
        );
    }

    #[test_log::test]
    fn test_arithmetic_plus_evaluation() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(15.0));
    }

    #[test_log::test]
    fn test_arithmetic_minus_evaluation() {
        let arith = Arithmetic::Minus(Value::Real(10.0), Value::Real(3.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(7.0));
    }

    #[test_log::test]
    fn test_arithmetic_multiply_evaluation() {
        let arith = Arithmetic::Multiply(Value::Real(4.0), Value::Real(3.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(12.0));
    }

    #[test_log::test]
    fn test_arithmetic_divide_evaluation() {
        let arith = Arithmetic::Divide(Value::Real(10.0), Value::Real(2.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(5.0));
    }

    #[test_log::test]
    fn test_arithmetic_min_evaluation() {
        let arith = Arithmetic::Min(Value::Real(10.0), Value::Real(5.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(5.0));

        let arith2 = Arithmetic::Min(Value::Real(3.0), Value::Real(8.0));
        let result2 = arith2.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result2, Some(3.0));
    }

    #[test_log::test]
    fn test_arithmetic_max_evaluation() {
        let arith = Arithmetic::Max(Value::Real(10.0), Value::Real(5.0));
        let result = arith.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(10.0));

        let arith2 = Arithmetic::Max(Value::Real(3.0), Value::Real(8.0));
        let result2 = arith2.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result2, Some(8.0));
    }

    #[test_log::test]
    fn test_arithmetic_grouping_evaluation() {
        let inner = Arithmetic::Plus(Value::Real(5.0), Value::Real(3.0));
        let grouped = Arithmetic::Grouping(Box::new(inner));
        let result = grouped.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(8.0));
    }

    #[test_log::test]
    fn test_arithmetic_complex_expression() {
        // (10 + 5) * 2
        let add = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let multiply = Arithmetic::Multiply(add.into(), Value::Real(2.0));
        let result = multiply.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(30.0));
    }

    #[test_log::test]
    fn test_arithmetic_chaining_plus() {
        let arith = Arithmetic::Plus(Value::Real(5.0), Value::Real(3.0));
        let chained = arith.plus(2.0);

        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(10.0));
    }

    #[test_log::test]
    fn test_arithmetic_chaining_minus() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let chained = arith.minus(3.0);

        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(12.0));
    }

    #[test_log::test]
    fn test_arithmetic_clamp() {
        // Test clamp with simple value
        let clamped = Arithmetic::Plus(Value::Real(15.0), Value::Real(0.0)).clamp(5.0, 10.0);
        let result = clamped.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(10.0)); // 15 clamped to max 10

        let clamped2 = Arithmetic::Plus(Value::Real(2.0), Value::Real(0.0)).clamp(5.0, 10.0);
        let result2 = clamped2.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result2, Some(5.0)); // 2 clamped to min 5

        let clamped3 = Arithmetic::Plus(Value::Real(7.0), Value::Real(0.0)).clamp(5.0, 10.0);
        let result3 = clamped3.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result3, Some(7.0)); // 7 is within range
    }

    #[test_log::test]
    fn test_calc_value_eq() {
        let calc = CalcValue::Display {
            target: ElementTarget::Id(1),
        };
        let condition = calc.eq(Value::Display(true));

        match condition {
            Condition::Eq(left, right) => {
                assert!(matches!(left, Value::Calc(_)));
                assert_eq!(right, Value::Display(true));
            }
            Condition::Bool(_) => panic!("Expected Eq condition, got Bool"),
        }
    }

    #[test_log::test]
    fn test_calc_value_plus() {
        let calc = CalcValue::WidthPx {
            target: ElementTarget::Id(1),
        };
        let arith = calc.plus(10.0);

        assert!(matches!(arith, Arithmetic::Plus(_, _)));
    }

    #[test_log::test]
    fn test_calc_value_clamp() {
        let calc = CalcValue::HeightPx {
            target: ElementTarget::Id(1),
        };
        let clamped = calc.clamp(100.0, 500.0);

        // Should create Min(500, Max(calc, 100))
        assert!(matches!(clamped, Arithmetic::Min(_, _)));
    }

    #[test_log::test]
    fn test_condition_then() {
        let condition = Condition::Bool(true);
        let if_action = condition.then(ActionType::NoOp);

        assert_eq!(if_action.condition, Condition::Bool(true));
        assert_eq!(if_action.actions.len(), 1);
        assert_eq!(if_action.else_actions.len(), 0);
    }

    #[test_log::test]
    fn test_condition_or_else() {
        let condition = Condition::Bool(false);
        let if_action = condition.or_else(ActionType::NoOp);

        assert_eq!(if_action.condition, Condition::Bool(false));
        assert_eq!(if_action.actions.len(), 0);
        assert_eq!(if_action.else_actions.len(), 1);
    }

    #[test_log::test]
    fn test_if_chaining() {
        let condition = Condition::Bool(true);
        let if_action = condition
            .then(ActionType::hide_by_id("element1"))
            .then(ActionType::show_by_id("element2"))
            .or_else(ActionType::no_display_by_id("element3"));

        assert_eq!(if_action.actions.len(), 2);
        assert_eq!(if_action.else_actions.len(), 1);
    }

    #[test_log::test]
    fn test_eq_condition_helper() {
        let condition = eq(Value::Real(5.0), Value::Real(5.0));

        match condition {
            Condition::Eq(left, right) => {
                assert_eq!(left, Value::Real(5.0));
                assert_eq!(right, Value::Real(5.0));
            }
            Condition::Bool(_) => panic!("Expected Eq condition, got Bool"),
        }
    }

    #[test_log::test]
    fn test_if_stmt_helper() {
        let condition = Condition::Bool(true);
        let if_action = if_stmt(condition, ActionType::NoOp);

        assert_eq!(if_action.actions.len(), 1);
        assert_eq!(if_action.else_actions.len(), 0);
    }

    #[test_log::test]
    fn test_visibility_helpers() {
        assert_eq!(hidden(), Value::Visibility(Visibility::Hidden));
        assert_eq!(visible(), Value::Visibility(Visibility::Visible));
    }

    #[test_log::test]
    fn test_display_helpers() {
        assert_eq!(displayed(), Value::Display(true));
        assert_eq!(not_displayed(), Value::Display(false));
    }

    #[test_log::test]
    fn test_get_visibility_by_id() {
        let calc = get_visibility_by_id("my-element");

        match calc {
            CalcValue::Visibility { target } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
            }
            _ => panic!("Expected Visibility CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_visibility_id() {
        let calc = get_visibility_id(42);

        match calc {
            CalcValue::Visibility { target } => {
                assert_eq!(target, ElementTarget::Id(42));
            }
            _ => panic!("Expected Visibility CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_display_by_id() {
        let calc = get_display_by_id("my-element");

        match calc {
            CalcValue::Display { target } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
            }
            _ => panic!("Expected Display CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_display_id() {
        let calc = get_display_id(42);

        match calc {
            CalcValue::Display { target } => {
                assert_eq!(target, ElementTarget::Id(42));
            }
            _ => panic!("Expected Display CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_width_px() {
        let calc = get_width_px_by_id("my-element");

        match calc {
            CalcValue::WidthPx { target } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
            }
            _ => panic!("Expected WidthPx CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_height_px() {
        let calc = get_height_px_id(42);

        match calc {
            CalcValue::HeightPx { target } => {
                assert_eq!(target, ElementTarget::Id(42));
            }
            _ => panic!("Expected HeightPx CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_x() {
        let calc = get_mouse_x();

        match calc {
            CalcValue::MouseX { target } => {
                assert_eq!(target, None);
            }
            _ => panic!("Expected MouseX CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_x_by_id() {
        let calc = get_mouse_x_by_id("my-element");

        match calc {
            CalcValue::MouseX { target } => {
                assert_eq!(
                    target,
                    Some(ElementTarget::ById(Target::from("my-element")))
                );
            }
            _ => panic!("Expected MouseX CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_y() {
        let calc = get_mouse_y();

        match calc {
            CalcValue::MouseY { target } => {
                assert_eq!(target, None);
            }
            _ => panic!("Expected MouseY CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_y_self() {
        let calc = get_mouse_y_self();

        match calc {
            CalcValue::MouseY { target } => {
                assert_eq!(target, Some(ElementTarget::SelfTarget));
            }
            _ => panic!("Expected MouseY CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_position_x() {
        let calc = get_position_x_id(42);

        match calc {
            CalcValue::PositionX { target } => {
                assert_eq!(target, ElementTarget::Id(42));
            }
            _ => panic!("Expected PositionX CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_position_y() {
        let calc = get_position_y_self();

        match calc {
            CalcValue::PositionY { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected PositionY CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_id_self() {
        let calc = get_id_self();

        match calc {
            CalcValue::Id { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected Id CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_event_value() {
        let calc = get_event_value();

        match calc {
            CalcValue::EventValue => {}
            _ => panic!("Expected EventValue CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_data_attr_value_self() {
        let calc = get_data_attr_value_self("data-value");

        match calc {
            CalcValue::DataAttrValue { attr, target } => {
                assert_eq!(attr, "data-value");
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected DataAttrValue CalcValue"),
        }
    }

    #[test_log::test]
    fn test_if_responsive_single_target() {
        let responsive = if_responsive("mobile");

        match responsive {
            Responsive::Target(target) => {
                assert_eq!(target, "mobile");
            }
            Responsive::Targets(_) => panic!("Expected single Target, got Targets"),
        }
    }

    #[test_log::test]
    fn test_if_responsive_multiple_targets() {
        let responsive = if_responsive_any(vec!["mobile", "tablet"]);

        match responsive {
            Responsive::Targets(targets) => {
                assert_eq!(targets.len(), 2);
                assert_eq!(targets[0], "mobile");
                assert_eq!(targets[1], "tablet");
            }
            Responsive::Target(_) => panic!("Expected multiple Targets, got Target"),
        }
    }

    #[test_log::test]
    fn test_responsive_then() {
        let responsive = if_responsive("mobile");
        let if_expr = responsive.then(10);

        assert_eq!(if_expr.value, Some(10));
        assert_eq!(if_expr.default, None);
    }

    #[test_log::test]
    fn test_responsive_or_else() {
        let responsive = if_responsive("desktop");
        let if_expr = responsive.or_else(20);

        assert_eq!(if_expr.value, None);
        assert_eq!(if_expr.default, Some(20));
    }

    #[test_log::test]
    fn test_if_expression_chaining() {
        let responsive = if_responsive("mobile");
        let if_expr = responsive.then(10).or_else(20);

        assert_eq!(if_expr.value, Some(10));
        assert_eq!(if_expr.default, Some(20));
    }

    #[test_log::test]
    fn test_value_from_conversions() {
        let from_f32: Value = 42.5f32.into();
        assert_eq!(from_f32, Value::Real(42.5));

        let from_f64: Value = 42.5f64.into();
        assert!(matches!(from_f64, Value::Real(x) if (x - 42.5).abs() < 0.001));

        let from_visibility: Value = Visibility::Hidden.into();
        assert_eq!(from_visibility, Value::Visibility(Visibility::Hidden));

        let from_key: Value = Key::Enter.into();
        assert_eq!(from_key, Value::Key(Key::Enter));
    }

    #[test_log::test]
    fn test_arithmetic_from_into_value() {
        let arith = Arithmetic::Plus(Value::Real(5.0), Value::Real(3.0));
        let value: Value = arith.into();

        assert!(matches!(value, Value::Arithmetic(_)));
    }

    #[test_log::test]
    fn test_calc_value_then_pass_to() {
        let calc = get_width_px_id(42);
        let action = calc.then_pass_to(ActionType::NoOp);

        match action {
            ActionType::Parameterized { action, value } => {
                assert!(matches!(*action, ActionType::NoOp));
                match value {
                    Value::Calc(CalcValue::WidthPx { target }) => {
                        assert_eq!(target, ElementTarget::Id(42));
                    }
                    _ => panic!("Expected Calc value with WidthPx"),
                }
            }
            _ => panic!("Expected Parameterized action"),
        }
    }

    #[test_log::test]
    fn test_arithmetic_then_pass_to() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let action = arith.then_pass_to(ActionType::show_by_id("element"));

        match action {
            ActionType::Parameterized { action, value } => {
                assert!(matches!(*action, ActionType::Style { .. }));
                match value {
                    Value::Arithmetic(_) => {}
                    _ => panic!("Expected Arithmetic value"),
                }
            }
            _ => panic!("Expected Parameterized action"),
        }
    }

    // ============================================
    // CalcValue arithmetic method tests
    // ============================================

    #[test_log::test]
    fn test_calc_value_minus() {
        let calc = CalcValue::WidthPx {
            target: ElementTarget::Id(1),
        };
        let arith = calc.minus(10.0);

        assert!(matches!(arith, Arithmetic::Minus(_, _)));
    }

    #[test_log::test]
    fn test_calc_value_multiply() {
        let calc = CalcValue::HeightPx {
            target: ElementTarget::Id(2),
        };
        let arith = calc.multiply(2.0);

        assert!(matches!(arith, Arithmetic::Multiply(_, _)));
    }

    #[test_log::test]
    fn test_calc_value_divide() {
        let calc = CalcValue::WidthPx {
            target: ElementTarget::SelfTarget,
        };
        let arith = calc.divide(4.0);

        assert!(matches!(arith, Arithmetic::Divide(_, _)));
    }

    #[test_log::test]
    fn test_calc_value_min() {
        let calc = CalcValue::MouseX { target: None };
        let arith = calc.min(500.0);

        assert!(matches!(arith, Arithmetic::Min(_, _)));
    }

    #[test_log::test]
    fn test_calc_value_max() {
        let calc = CalcValue::MouseY { target: None };
        let arith = calc.max(100.0);

        assert!(matches!(arith, Arithmetic::Max(_, _)));
    }

    // ============================================
    // Arithmetic chaining with multiply/divide/min/max tests
    // ============================================

    #[test_log::test]
    fn test_arithmetic_chaining_multiply() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let chained = arith.multiply(2.0);

        // (10 + 5) * 2 = 30
        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(30.0));
    }

    #[test_log::test]
    fn test_arithmetic_chaining_divide() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let chained = arith.divide(3.0);

        // (10 + 5) / 3 = 5
        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(5.0));
    }

    #[test_log::test]
    fn test_arithmetic_chaining_min() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(10.0));
        let chained = arith.min(15.0);

        // min(20, 15) = 15
        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(15.0));
    }

    #[test_log::test]
    fn test_arithmetic_chaining_max() {
        let arith = Arithmetic::Plus(Value::Real(3.0), Value::Real(2.0));
        let chained = arith.max(10.0);

        // max(5, 10) = 10
        let result = chained.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(10.0));
    }

    #[test_log::test]
    fn test_arithmetic_eq_creates_condition() {
        let arith = Arithmetic::Plus(Value::Real(5.0), Value::Real(5.0));
        let condition = arith.eq(10.0);

        match condition {
            Condition::Eq(left, right) => {
                assert!(matches!(left, Value::Arithmetic(_)));
                assert_eq!(right, Value::Real(10.0));
            }
            Condition::Bool(_) => panic!("Expected Eq condition"),
        }
    }

    // ============================================
    // Value::eq method test
    // ============================================

    #[test_log::test]
    fn test_value_eq_creates_condition() {
        let value = Value::Real(42.0);
        let condition = value.eq(42.0);

        match condition {
            Condition::Eq(left, right) => {
                assert_eq!(left, Value::Real(42.0));
                assert_eq!(right, Value::Real(42.0));
            }
            Condition::Bool(_) => panic!("Expected Eq condition"),
        }
    }

    // ============================================
    // Value::as_f32 with Arithmetic and Calc tests
    // ============================================

    #[test_log::test]
    fn test_value_as_f32_with_arithmetic() {
        let arith = Arithmetic::Plus(Value::Real(10.0), Value::Real(5.0));
        let value = Value::Arithmetic(Box::new(arith));

        let result = value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(15.0));
    }

    #[test_log::test]
    fn test_value_as_f32_non_numeric_returns_none() {
        let value = Value::String("not a number".to_string());
        let result = value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, None);

        let visibility_value = Value::Visibility(Visibility::Hidden);
        let result = visibility_value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, None);

        let display_value = Value::Display(true);
        let result = display_value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, None);
    }

    #[test_log::test]
    fn test_value_as_f32_with_calc_func() {
        let calc = CalcValue::WidthPx {
            target: ElementTarget::Id(1),
        };
        let value = Value::Calc(calc);

        // Without calc_func, Calc returns None
        let result_without = value.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result_without, None);

        // With calc_func that returns a Real value
        let calc_func = |_: &CalcValue| Some(Value::Real(100.0));
        let result_with = value.as_f32(Some(&calc_func));
        assert_eq!(result_with, Some(100.0));
    }

    // ============================================
    // Additional helper function tests
    // ============================================

    #[test_log::test]
    fn test_get_visibility_self() {
        let calc = get_visibility_self();

        match calc {
            CalcValue::Visibility { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected Visibility CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_visibility_class() {
        let calc = get_visibility_class("my-class");

        match calc {
            CalcValue::Visibility { target } => {
                assert_eq!(target, ElementTarget::Class(Target::from("my-class")));
            }
            _ => panic!("Expected Visibility CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_display_self() {
        let calc = get_display_self();

        match calc {
            CalcValue::Display { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected Display CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_display_class() {
        let calc = get_display_class("display-class");

        match calc {
            CalcValue::Display { target } => {
                assert_eq!(target, ElementTarget::Class(Target::from("display-class")));
            }
            _ => panic!("Expected Display CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_display_last_child() {
        let calc = get_display_last_child();

        match calc {
            CalcValue::Display { target } => {
                assert_eq!(target, ElementTarget::LastChild);
            }
            _ => panic!("Expected Display CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_width_px_self() {
        let calc = get_width_px_self();

        match calc {
            CalcValue::WidthPx { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected WidthPx CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_height_px_self() {
        let calc = get_height_px_self();

        match calc {
            CalcValue::HeightPx { target } => {
                assert_eq!(target, ElementTarget::SelfTarget);
            }
            _ => panic!("Expected HeightPx CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_position_x_by_id() {
        let calc = get_position_x_by_id("positioned-element");

        match calc {
            CalcValue::PositionX { target } => {
                assert_eq!(
                    target,
                    ElementTarget::ById(Target::from("positioned-element"))
                );
            }
            _ => panic!("Expected PositionX CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_position_y_by_id() {
        let calc = get_position_y_by_id("y-element");

        match calc {
            CalcValue::PositionY { target } => {
                assert_eq!(target, ElementTarget::ById(Target::from("y-element")));
            }
            _ => panic!("Expected PositionY CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_x_id() {
        let calc = get_mouse_x_id(42);

        match calc {
            CalcValue::MouseX { target } => {
                assert_eq!(target, Some(ElementTarget::Id(42)));
            }
            _ => panic!("Expected MouseX CalcValue"),
        }
    }

    #[test_log::test]
    fn test_get_mouse_y_id() {
        let calc = get_mouse_y_id(99);

        match calc {
            CalcValue::MouseY { target } => {
                assert_eq!(target, Some(ElementTarget::Id(99)));
            }
            _ => panic!("Expected MouseY CalcValue"),
        }
    }

    // ============================================
    // LayoutDirection conversion test
    // ============================================

    #[test_log::test]
    fn test_value_from_layout_direction() {
        let direction = LayoutDirection::Row;
        let value: Value = direction.into();

        assert_eq!(value, Value::LayoutDirection(LayoutDirection::Row));
    }

    // ============================================
    // Arithmetic::group test
    // ============================================

    #[test_log::test]
    fn test_arithmetic_group() {
        let inner = Arithmetic::Plus(Value::Real(3.0), Value::Real(2.0));
        let grouped = Arithmetic::group(inner);

        let result = grouped.as_f32(None::<&fn(&CalcValue) -> Option<Value>>);
        assert_eq!(result, Some(5.0));
    }

    // ============================================
    // Value serde deserialization tests
    // ============================================
    //
    // The custom Deserialize impl for Value converts raw JSON numbers
    // directly to Value::Real(f32) for ergonomic deserialization from
    // JSON payloads that include numeric literals.

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_i64_to_real() {
        // JSON integers should deserialize directly to Value::Real
        let json = "42";
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Real(42.0));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_negative_i64_to_real() {
        // Negative integers should also deserialize to Value::Real
        let json = "-123";
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Real(-123.0));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_f64_to_real() {
        // Floating point numbers should deserialize to Value::Real
        let json = "42.5";
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Real(42.5));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_large_u64_to_real() {
        // Large unsigned integers should deserialize to Value::Real
        // (with potential precision loss for very large values)
        let json = "999999";
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Real(999_999.0));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_zero_to_real() {
        let json = "0";
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Real(0.0));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_visibility_variant() {
        // Visibility uses internally tagged enum format (serde(tag = "type"))
        // so the JSON must contain the "type" field inside the nested object
        let json = r#"{"Visibility": {"type": "Hidden"}}"#;
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Visibility(Visibility::Hidden));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_display_variant() {
        let json = r#"{"Display": true}"#;
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::Display(true));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_string_variant() {
        let json = r#"{"String": "hello world"}"#;
        let value: Value = serde_json::from_str(json).unwrap();

        assert_eq!(value, Value::String("hello world".to_string()));
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_deserialize_real_variant() {
        // Explicit Real variant should also work
        let json = r#"{"Real": 2.71}"#;
        let value: Value = serde_json::from_str(json).unwrap();

        // Should be close to 2.71 (within f32 precision)
        match value {
            Value::Real(v) => assert!((v - 2.71).abs() < 0.001),
            _ => panic!("Expected Value::Real"),
        }
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_serialize_roundtrip() {
        // Test that values can be serialized and deserialized consistently
        let original = Value::Visibility(Visibility::Visible);
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Value = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, original);
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_serialize_roundtrip_string() {
        let original = Value::String("test-string".to_string());
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Value = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, original);
    }

    #[cfg(feature = "serde")]
    #[test_log::test]
    fn test_value_serialize_roundtrip_layout_direction() {
        let original = Value::LayoutDirection(LayoutDirection::Column);
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: Value = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized, original);
    }
}