hyperchad_actions 0.2.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
//! Action system for `HyperChad` UI framework
//!
//! This crate provides a comprehensive action system for building interactive UI behaviors
//! in the `HyperChad` framework. It enables declarative definition of UI actions triggered by
//! events such as clicks, hovers, and HTTP requests.
//!
//! # Main Components
//!
//! * [`Action`] - Combines a trigger event with an effect to execute
//! * [`ActionTrigger`] - Event types that can trigger actions (click, hover, HTTP events, etc.)
//! * [`ActionEffect`] - Wrapper for actions with timing modifiers (throttle, delay)
//! * [`ActionType`] - Concrete action types (style changes, navigation, logging, custom actions)
//! * [`Key`] - Keyboard key representations for key events
//!
//! # Feature Flags
//!
//! * `logic` - Enables conditional logic and dynamic value evaluation in actions
//! * `handler` - Provides action handler implementation for processing actions
//! * `arb` - Adds property-based testing support via `proptest`
//! * `serde` - Enables serialization/deserialization support
//!
//! # Example
//!
//! ```rust
//! use hyperchad_actions::{Action, ActionTrigger, ActionType};
//! use hyperchad_transformer_models::Visibility;
//!
//! // Create an action that hides an element when clicked
//! let action = Action {
//!     trigger: ActionTrigger::Click,
//!     effect: ActionType::hide_by_id("my-element").into(),
//! };
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use std::collections::BTreeMap;

use hyperchad_transformer_models::Visibility;

/// Logic and conditional evaluation for actions
#[cfg(feature = "logic")]
pub mod logic;

/// Arbitrary value generation for property-based testing
#[cfg(feature = "arb")]
pub mod arb;

/// Action handler implementation for processing and executing actions
#[cfg(feature = "handler")]
pub mod handler;

/// Domain-specific language (DSL) for defining actions in templates
pub mod dsl;

pub use hyperchad_transformer_models::{ElementTarget, Target};

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

/// Keyboard key representation for key events
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Key {
    /// Escape key
    Escape,
    /// Tab key
    Tab,
    /// Up arrow key
    ArrowUp,
    /// Down arrow key
    ArrowDown,
    /// Left arrow key
    ArrowLeft,
    /// Right arrow key
    ArrowRight,
    /// Home key
    Home,
    /// End key
    End,
    /// Page Up key
    PageUp,
    /// Page Down key
    PageDown,
    /// Delete key
    Delete,
    /// Backspace key
    Backspace,
    /// Enter key
    Enter,
    /// Insert key
    Insert,
    /// F1 function key
    F1,
    /// F2 function key
    F2,
    /// F3 function key
    F3,
    /// F4 function key
    F4,
    /// F5 function key
    F5,
    /// F6 function key
    F6,
    /// F7 function key
    F7,
    /// F8 function key
    F8,
    /// F9 function key
    F9,
    /// F10 function key
    F10,
    /// F11 function key
    F11,
    /// F12 function key
    F12,
    /// Num Lock key
    NumLock,
    /// Scroll Lock key
    ScrollLock,
    /// Caps Lock key
    CapsLock,
    /// Shift modifier key
    Shift,
    /// Control modifier key
    Control,
    /// Alt modifier key
    Alt,
    /// Meta/Command/Windows modifier key
    Meta,
    /// Letter A key
    A,
    /// Letter B key
    B,
    /// Letter C key
    C,
    /// Letter D key
    D,
    /// Letter E key
    E,
    /// Letter F key
    F,
    /// Letter G key
    G,
    /// Letter H key
    H,
    /// Letter I key
    I,
    /// Letter J key
    J,
    /// Letter K key
    K,
    /// Letter L key
    L,
    /// Letter M key
    M,
    /// Letter N key
    N,
    /// Letter O key
    O,
    /// Letter P key
    P,
    /// Letter Q key
    Q,
    /// Letter R key
    R,
    /// Letter S key
    S,
    /// Letter T key
    T,
    /// Letter U key
    U,
    /// Letter V key
    V,
    /// Letter W key
    W,
    /// Letter X key
    X,
    /// Letter Y key
    Y,
    /// Letter Z key
    Z,
    /// Number 0 key (top row)
    Key0,
    /// Number 1 key (top row)
    Key1,
    /// Number 2 key (top row)
    Key2,
    /// Number 3 key (top row)
    Key3,
    /// Number 4 key (top row)
    Key4,
    /// Number 5 key (top row)
    Key5,
    /// Number 6 key (top row)
    Key6,
    /// Number 7 key (top row)
    Key7,
    /// Number 8 key (top row)
    Key8,
    /// Number 9 key (top row)
    Key9,
    /// Numpad 0 key
    Numpad0,
    /// Numpad 1 key
    Numpad1,
    /// Numpad 2 key
    Numpad2,
    /// Numpad 3 key
    Numpad3,
    /// Numpad 4 key
    Numpad4,
    /// Numpad 5 key
    Numpad5,
    /// Numpad 6 key
    Numpad6,
    /// Numpad 7 key
    Numpad7,
    /// Numpad 8 key
    Numpad8,
    /// Numpad 9 key
    Numpad9,
}

impl Key {
    /// Returns the string representation of the key
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Escape => "Escape",
            Self::Tab => "Tab",
            Self::ArrowUp => "ArrowUp",
            Self::ArrowDown => "ArrowDown",
            Self::ArrowLeft => "ArrowLeft",
            Self::ArrowRight => "ArrowRight",
            Self::Home => "Home",
            Self::End => "End",
            Self::PageUp => "PageUp",
            Self::PageDown => "PageDown",
            Self::Delete => "Delete",
            Self::Backspace => "Backspace",
            Self::Enter => "Enter",
            Self::Insert => "Insert",
            Self::F1 => "F1",
            Self::F2 => "F2",
            Self::F3 => "F3",
            Self::F4 => "F4",
            Self::F5 => "F5",
            Self::F6 => "F6",
            Self::F7 => "F7",
            Self::F8 => "F8",
            Self::F9 => "F9",
            Self::F10 => "F10",
            Self::F11 => "F11",
            Self::F12 => "F12",
            Self::NumLock => "NumLock",
            Self::ScrollLock => "ScrollLock",
            Self::CapsLock => "CapsLock",
            Self::Shift => "Shift",
            Self::Control => "Control",
            Self::Alt => "Alt",
            Self::Meta => "Meta",
            Self::A => "A",
            Self::B => "B",
            Self::C => "C",
            Self::D => "D",
            Self::E => "E",
            Self::F => "F",
            Self::G => "G",
            Self::H => "H",
            Self::I => "I",
            Self::J => "J",
            Self::K => "K",
            Self::L => "L",
            Self::M => "M",
            Self::N => "N",
            Self::O => "O",
            Self::P => "P",
            Self::Q => "Q",
            Self::R => "R",
            Self::S => "S",
            Self::T => "T",
            Self::U => "U",
            Self::V => "V",
            Self::W => "W",
            Self::X => "X",
            Self::Y => "Y",
            Self::Z => "Z",
            Self::Key0 => "Key0",
            Self::Key1 => "Key1",
            Self::Key2 => "Key2",
            Self::Key3 => "Key3",
            Self::Key4 => "Key4",
            Self::Key5 => "Key5",
            Self::Key6 => "Key6",
            Self::Key7 => "Key7",
            Self::Key8 => "Key8",
            Self::Key9 => "Key9",
            Self::Numpad0 => "Numpad0",
            Self::Numpad1 => "Numpad1",
            Self::Numpad2 => "Numpad2",
            Self::Numpad3 => "Numpad3",
            Self::Numpad4 => "Numpad4",
            Self::Numpad5 => "Numpad5",
            Self::Numpad6 => "Numpad6",
            Self::Numpad7 => "Numpad7",
            Self::Numpad8 => "Numpad8",
            Self::Numpad9 => "Numpad9",
        }
    }
}

impl std::fmt::Display for Key {
    /// Formats the key as its string representation
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Context information for HTTP-related action events
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct HttpEventContext {
    /// URL of the HTTP request
    pub url: String,
    /// HTTP method (GET, POST, etc.)
    pub method: String,
    /// HTTP status code if response received
    pub status: Option<u16>,
    /// HTTP response headers if available
    pub headers: Option<BTreeMap<String, String>>,
    /// Request duration in milliseconds
    pub duration_ms: Option<u64>,
    /// Error message if request failed
    pub error: Option<String>,
}

/// Event trigger that determines when an action should execute
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ActionTrigger {
    /// Triggered on mouse click
    Click,
    /// Triggered when clicking outside the element
    ClickOutside,
    /// Triggered on mouse button down
    MouseDown,
    /// Triggered on key down event
    KeyDown,
    /// Triggered when mouse hovers over element
    Hover,
    /// Triggered when element value changes
    Change,
    /// Triggered when element is resized
    Resize,
    /// Triggered on custom named event
    Event(String),
    /// Triggered immediately when action is registered
    #[default]
    Immediate,
    /// Triggered before HTTP request is sent
    HttpBeforeRequest,
    /// Triggered after HTTP request completes (success or failure)
    HttpAfterRequest,
    /// Triggered when HTTP request succeeds
    HttpRequestSuccess,
    /// Triggered when HTTP request fails with error
    HttpRequestError,
    /// Triggered when HTTP request is aborted
    HttpRequestAbort,
    /// Triggered when HTTP request times out
    HttpRequestTimeout,
}

impl ActionTrigger {
    /// Returns the trigger type name as a string
    #[must_use]
    pub const fn trigger_type(&self) -> &'static str {
        match self {
            Self::Click => "Click",
            Self::ClickOutside => "ClickOutside",
            Self::MouseDown => "MouseDown",
            Self::KeyDown => "KeyDown",
            Self::Hover => "Hover",
            Self::Change => "Change",
            Self::Resize => "Resize",
            Self::Event(_) => "Event",
            Self::Immediate => "Immediate",
            Self::HttpBeforeRequest => "HttpBeforeRequest",
            Self::HttpAfterRequest => "HttpAfterRequest",
            Self::HttpRequestSuccess => "HttpRequestSuccess",
            Self::HttpRequestError => "HttpRequestError",
            Self::HttpRequestAbort => "HttpRequestAbort",
            Self::HttpRequestTimeout => "HttpRequestTimeout",
        }
    }
}

/// Action that combines a trigger event with an effect
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
pub struct Action {
    /// Event that triggers this action
    pub trigger: ActionTrigger,
    /// Effect to execute when triggered
    pub effect: ActionEffect,
}

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

/// Effect that wraps an action with timing and execution modifiers
#[derive(Clone, Debug, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
pub struct ActionEffect {
    /// The action to execute
    pub action: ActionType,
    /// Milliseconds to delay before turning off the effect
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub delay_off: Option<u64>,
    /// Milliseconds to throttle repeated executions
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub throttle: Option<u64>,
    /// Whether this effect should be unique
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub unique: Option<bool>,
}

impl ActionEffect {
    /// Converts this effect into an `ActionEffect` (identity function for chaining)
    #[must_use]
    pub const fn into_action_effect(self) -> Self {
        self
    }
}

impl From<Vec<Self>> for ActionEffect {
    /// Converts a vector of `ActionEffect`s into a single multi-effect action
    fn from(value: Vec<Self>) -> Self {
        Self {
            action: ActionType::MultiEffect(value),
            ..Default::default()
        }
    }
}

impl From<Vec<ActionType>> for ActionEffect {
    /// Converts a vector of `ActionType`s into a single multi-action effect
    fn from(value: Vec<ActionType>) -> Self {
        Self {
            action: ActionType::Multi(value),
            ..Default::default()
        }
    }
}

impl ActionEffect {
    /// Sets the `delay_off` duration in milliseconds
    #[must_use]
    pub const fn delay_off(mut self, millis: u64) -> Self {
        self.delay_off = Some(millis);
        self
    }

    /// Sets the throttle duration in milliseconds
    #[must_use]
    pub const fn throttle(mut self, millis: u64) -> Self {
        self.throttle = Some(millis);
        self
    }

    /// Marks this effect as unique
    #[must_use]
    pub const fn unique(mut self) -> Self {
        self.unique = Some(true);
        self
    }
}

impl From<ActionType> for ActionEffect {
    /// Converts an `ActionType` into an `ActionEffect` with default timing settings
    fn from(value: ActionType) -> Self {
        Self {
            action: value,
            ..Default::default()
        }
    }
}

impl From<Box<ActionType>> for ActionEffect {
    /// Converts a boxed `ActionType` into an `ActionEffect`
    fn from(value: Box<ActionType>) -> Self {
        (*value).into()
    }
}

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

/// Log severity level for logging actions
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum LogLevel {
    /// Error log level for critical issues
    Error,
    /// Warning log level for concerning but non-critical issues
    Warn,
    /// Info log level for informational messages
    Info,
    /// Debug log level for debugging information
    Debug,
    /// Trace log level for detailed tracing information
    Trace,
}

/// Input-related action types
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum InputActionType {
    /// Select an input element
    Select {
        /// Target element to select
        target: ElementTarget,
    },
}

/// Types of actions that can be performed on UI elements
#[derive(Clone, Debug, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ActionType {
    /// No operation action
    #[default]
    NoOp,
    /// Variable assignment
    Let {
        /// Variable name
        name: String,
        /// Value expression
        value: dsl::Expression,
    },
    /// Style modification action
    Style {
        /// Target element
        target: ElementTarget,
        /// Style action to apply
        action: StyleAction,
    },
    /// Input-related action
    Input(InputActionType),
    /// Navigate to a URL
    Navigate {
        /// URL to navigate to
        url: String,
    },
    /// Log a message
    Log {
        /// Message to log
        message: String,
        /// Log level
        level: LogLevel,
    },
    /// Custom action
    Custom {
        /// Custom action name
        action: String,
    },
    /// Event-triggered action
    Event {
        /// Event name
        name: String,
        /// Action to execute on event
        action: Box<Self>,
    },
    /// Multiple actions executed sequentially
    Multi(Vec<Self>),
    /// Multiple effects executed sequentially
    MultiEffect(Vec<ActionEffect>),
    /// Parameterized action with dynamic value
    #[cfg(feature = "logic")]
    Parameterized {
        /// Action to execute
        action: Box<Self>,
        /// Dynamic value parameter
        value: logic::Value,
    },
    /// Conditional logic action
    #[cfg(feature = "logic")]
    Logic(logic::If),
}

impl ActionType {
    /// Converts this action into an `ActionEffect`
    #[must_use]
    pub fn into_action_effect(self) -> ActionEffect {
        self.into()
    }
}

impl ActionType {
    /// Creates an event-triggered action
    #[must_use]
    pub fn on_event(event: impl Into<String>, action: impl Into<Self>) -> Self {
        Self::Event {
            name: event.into(),
            action: Box::new(action.into()),
        }
    }

    /// Sets focus on an element identified by element ID
    #[must_use]
    pub fn set_focus_by_id(focus: bool, target: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ById(target.into()),
            action: StyleAction::SetFocus(focus),
        }
    }

    /// Sets focus on an element identified by class name
    #[must_use]
    pub fn set_focus_class(focus: bool, class: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::Class(class.into()),
            action: StyleAction::SetFocus(focus),
        }
    }

    /// Sets focus on a child element identified by class name
    #[must_use]
    pub fn set_focus_child_class(focus: bool, class: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ChildClass(class.into()),
            action: StyleAction::SetFocus(focus),
        }
    }

    /// Selects an input element identified by element ID
    #[must_use]
    pub fn select_by_id(target: impl Into<Target>) -> Self {
        Self::Input(InputActionType::Select {
            target: ElementTarget::ById(target.into()),
        })
    }

    /// Selects an input element identified by class name
    #[must_use]
    pub fn select_class(class: impl Into<Target>) -> Self {
        Self::Input(InputActionType::Select {
            target: ElementTarget::Class(class.into()),
        })
    }

    /// Selects a child input element identified by class name
    #[must_use]
    pub fn select_child_class(class: impl Into<Target>) -> Self {
        Self::Input(InputActionType::Select {
            target: ElementTarget::ChildClass(class.into()),
        })
    }

    /// Sets visibility on an element identified by element ID
    #[must_use]
    pub fn set_visibility_by_id(visibility: Visibility, target: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ById(target.into()),
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Sets visibility on a child element identified by class name
    #[must_use]
    pub fn set_visibility_child_class(visibility: Visibility, class: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ChildClass(class.into()),
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Hides an element identified by element ID
    #[must_use]
    pub fn hide_by_id(target: impl Into<Target>) -> Self {
        Self::set_visibility_by_id(Visibility::Hidden, target)
    }

    /// Shows an element identified by element ID
    #[must_use]
    pub fn show_by_id(target: impl Into<Target>) -> Self {
        Self::set_visibility_by_id(Visibility::Visible, target)
    }

    /// Hides an element identified by class name
    #[must_use]
    pub fn hide_class(class_name: impl Into<Target>) -> Self {
        Self::set_visibility_class(Visibility::Hidden, class_name)
    }

    /// Shows an element identified by class name
    #[must_use]
    pub fn show_class(class_name: impl Into<Target>) -> Self {
        Self::set_visibility_class(Visibility::Visible, class_name)
    }

    /// Focuses an element identified by element ID
    #[must_use]
    pub fn focus_by_id(target: impl Into<Target>) -> Self {
        Self::set_focus_by_id(true, target)
    }

    /// Focuses an element identified by class name
    #[must_use]
    pub fn focus_class(class_name: impl Into<Target>) -> Self {
        Self::set_focus_class(true, class_name)
    }

    /// Sets visibility on an element identified by class name
    #[must_use]
    pub fn set_visibility_class(visibility: Visibility, class_name: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::Class(class_name.into()),
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Sets visibility on an element identified by numeric ID
    #[must_use]
    pub const fn set_visibility_id(visibility: Visibility, target: usize) -> Self {
        Self::Style {
            target: ElementTarget::Id(target),
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Hides an element identified by numeric ID
    #[must_use]
    pub const fn hide_id(target: usize) -> Self {
        Self::set_visibility_id(Visibility::Hidden, target)
    }

    /// Shows an element identified by numeric ID
    #[must_use]
    pub const fn show_id(target: usize) -> Self {
        Self::set_visibility_id(Visibility::Visible, target)
    }

    /// Sets visibility on the element itself
    #[must_use]
    pub const fn set_visibility_self(visibility: Visibility) -> Self {
        Self::Style {
            target: ElementTarget::SelfTarget,
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Hides the element itself
    #[must_use]
    pub const fn hide_self() -> Self {
        Self::set_visibility_self(Visibility::Hidden)
    }

    /// Shows the element itself
    #[must_use]
    pub const fn show_self() -> Self {
        Self::set_visibility_self(Visibility::Visible)
    }

    /// Sets visibility on the last child element
    #[must_use]
    pub const fn set_visibility_last_child(visibility: Visibility) -> Self {
        Self::Style {
            target: ElementTarget::LastChild,
            action: StyleAction::SetVisibility(visibility),
        }
    }

    /// Hides the last child element
    #[must_use]
    pub const fn hide_last_child() -> Self {
        Self::set_visibility_last_child(Visibility::Hidden)
    }

    /// Shows the last child element
    #[must_use]
    pub const fn show_last_child() -> Self {
        Self::set_visibility_last_child(Visibility::Visible)
    }

    /// Toggles visibility on an element identified by element ID
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_visibility_by_id(target: impl Into<Target>) -> Self {
        let target = target.into();
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::get_visibility_by_id(&target).into(),
                crate::logic::Value::Visibility(hyperchad_transformer_models::Visibility::Visible),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::ById(target.clone()),
                    action: crate::StyleAction::SetVisibility(
                        hyperchad_transformer_models::Visibility::Hidden,
                    ),
                },
                ..Default::default()
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::ById(target),
                    action: crate::StyleAction::SetVisibility(
                        hyperchad_transformer_models::Visibility::Visible,
                    ),
                },
                ..Default::default()
            }],
        })
    }

    /// Toggles visibility on an element identified by CSS selector
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_visibility_selector(target: impl Into<Target>) -> Self {
        let target = target.into();
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::get_visibility_selector(&target).into(),
                crate::logic::Value::Visibility(hyperchad_transformer_models::Visibility::Visible),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::Selector(target.clone()),
                    action: crate::StyleAction::SetVisibility(
                        hyperchad_transformer_models::Visibility::Hidden,
                    ),
                },
                ..Default::default()
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::Selector(target),
                    action: crate::StyleAction::SetVisibility(
                        hyperchad_transformer_models::Visibility::Visible,
                    ),
                },
                ..Default::default()
            }],
        })
    }

    /// Sets display property on an element identified by element ID
    #[must_use]
    pub fn set_display_by_id(display: bool, target: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ById(target.into()),
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Sets display property on an element identified by class name
    #[must_use]
    pub fn set_display_class(display: bool, class_name: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::Class(class_name.into()),
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Disables display on an element identified by element ID
    #[must_use]
    pub fn no_display_by_id(target: impl Into<Target>) -> Self {
        Self::set_display_by_id(false, target)
    }

    /// Enables display on an element identified by element ID
    #[must_use]
    pub fn display_by_id(target: impl Into<Target>) -> Self {
        Self::set_display_by_id(true, target)
    }

    /// Disables display on an element identified by class name
    #[must_use]
    pub fn no_display_class(class_name: impl Into<Target>) -> Self {
        Self::set_display_class(false, class_name)
    }

    /// Enables display on an element identified by class name
    #[must_use]
    pub fn display_class(class_name: impl Into<Target>) -> Self {
        Self::set_display_class(true, class_name)
    }

    /// Sets display property on an element identified by numeric ID
    #[must_use]
    pub const fn set_display_id(display: bool, target: usize) -> Self {
        Self::Style {
            target: ElementTarget::Id(target),
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Disables display on an element identified by numeric ID
    #[must_use]
    pub const fn no_display_id(target: usize) -> Self {
        Self::set_display_id(false, target)
    }

    /// Enables display on an element identified by numeric ID
    #[must_use]
    pub const fn display_id(target: usize) -> Self {
        Self::set_display_id(true, target)
    }

    /// Sets display property on the element itself
    #[must_use]
    pub const fn set_display_self(display: bool) -> Self {
        Self::Style {
            target: ElementTarget::SelfTarget,
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Disables display on the element itself
    #[must_use]
    pub const fn no_display_self() -> Self {
        Self::set_display_self(false)
    }

    /// Enables display on the element itself
    #[must_use]
    pub const fn display_self() -> Self {
        Self::set_display_self(true)
    }

    /// Sets display property on the last child element
    #[must_use]
    pub const fn set_display_last_child(display: bool) -> Self {
        Self::Style {
            target: ElementTarget::LastChild,
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Disables display on the last child element
    #[must_use]
    pub const fn no_display_last_child() -> Self {
        Self::set_display_last_child(false)
    }

    /// Enables display on the last child element
    #[must_use]
    pub const fn display_last_child() -> Self {
        Self::set_display_last_child(true)
    }

    /// Sets display property on a child element identified by class name
    #[must_use]
    pub fn set_display_child_class(display: bool, class: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ChildClass(class.into()),
            action: StyleAction::SetDisplay(display),
        }
    }

    /// Disables display on a child element identified by class name
    #[must_use]
    pub fn no_display_child_class(class: impl Into<Target>) -> Self {
        Self::set_display_child_class(false, class)
    }

    /// Enables display on a child element identified by class name
    #[must_use]
    pub fn display_child_class(class: impl Into<Target>) -> Self {
        Self::set_display_child_class(true, class)
    }

    /// Toggles display property on an element identified by element ID
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_by_id(target: impl Into<Target>) -> Self {
        let target = target.into();
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::get_display_by_id(&target).into(),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::by_id(&target),
                    action: crate::StyleAction::SetDisplay(false),
                },
                ..Default::default()
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::by_id(&target),
                    action: crate::StyleAction::SetDisplay(true),
                },
                ..Default::default()
            }],
        })
    }

    /// Toggles display property on an element identified by class name
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_str_class(target: impl Into<Target>) -> Self {
        let target = target.into();
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::get_display_class(&target).into(),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::class(&target),
                    action: crate::StyleAction::SetDisplay(false),
                },
                ..Default::default()
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::class(&target),
                    action: crate::StyleAction::SetDisplay(true),
                },
                ..Default::default()
            }],
        })
    }

    /// Toggles display property on a child element identified by class name
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_child_class(target: impl Into<Target>) -> Self {
        let target = target.into();
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::get_display_child_class(&target).into(),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::child_class(&target),
                    action: crate::StyleAction::SetDisplay(false),
                },
                ..Default::default()
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::child_class(&target),
                    action: crate::StyleAction::SetDisplay(true),
                },
                ..Default::default()
            }],
        })
    }

    /// Toggles display property on an element identified by numeric ID
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_id(target: usize) -> Self {
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::Value::Calc(crate::logic::get_display_id(target)),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::Id(target),
                    action: crate::StyleAction::SetDisplay(false),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::Id(target),
                    action: crate::StyleAction::SetDisplay(true),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
        })
    }

    /// Toggles display property on the element itself
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_self() -> Self {
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::Value::Calc(crate::logic::get_display_self()),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::SelfTarget,
                    action: crate::StyleAction::SetDisplay(false),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::SelfTarget,
                    action: crate::StyleAction::SetDisplay(true),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
        })
    }

    /// Toggles display property on the last child element
    #[cfg(feature = "logic")]
    #[must_use]
    pub fn toggle_display_last_child() -> Self {
        Self::Logic(crate::logic::If {
            condition: crate::logic::Condition::Eq(
                crate::logic::Value::Calc(crate::logic::get_display_last_child()),
                crate::logic::Value::Display(true),
            ),
            actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::LastChild,
                    action: crate::StyleAction::SetDisplay(false),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
            else_actions: vec![crate::ActionEffect {
                action: Self::Style {
                    target: crate::ElementTarget::LastChild,
                    action: crate::StyleAction::SetDisplay(true),
                },
                delay_off: None,
                throttle: None,
                unique: None,
            }],
        })
    }

    /// Sets background on an element identified by element ID
    #[must_use]
    pub fn set_background_by_id(background: impl Into<String>, target: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ById(target.into()),
            action: StyleAction::SetBackground(Some(background.into())),
        }
    }

    /// Sets background on an element identified by numeric ID
    #[must_use]
    pub fn set_background_id(background: impl Into<String>, target: usize) -> Self {
        Self::Style {
            target: ElementTarget::Id(target),
            action: StyleAction::SetBackground(Some(background.into())),
        }
    }

    /// Sets background on the element itself
    #[must_use]
    pub fn set_background_self(background: impl Into<String>) -> Self {
        Self::Style {
            target: ElementTarget::SelfTarget,
            action: StyleAction::SetBackground(Some(background.into())),
        }
    }

    /// Removes background from the element itself
    #[must_use]
    pub const fn remove_background_self() -> Self {
        Self::Style {
            target: ElementTarget::SelfTarget,
            action: StyleAction::SetBackground(None),
        }
    }

    /// Removes background from an element identified by element ID
    #[must_use]
    pub fn remove_background_by_id(target: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ById(target.into()),
            action: StyleAction::SetBackground(None),
        }
    }

    /// Removes background from an element identified by numeric ID
    #[must_use]
    pub const fn remove_background_id(target: usize) -> Self {
        Self::Style {
            target: ElementTarget::Id(target),
            action: StyleAction::SetBackground(None),
        }
    }

    /// Removes background from an element identified by class name
    #[must_use]
    pub fn remove_background_class(class_name: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::Class(class_name.into()),
            action: StyleAction::SetBackground(None),
        }
    }

    /// Removes background from a child element identified by class name
    #[must_use]
    pub fn remove_background_child_class(class_name: impl Into<Target>) -> Self {
        Self::Style {
            target: ElementTarget::ChildClass(class_name.into()),
            action: StyleAction::SetBackground(None),
        }
    }

    /// Removes background from the last child element
    #[must_use]
    pub const fn remove_background_last_child() -> Self {
        Self::Style {
            target: ElementTarget::LastChild,
            action: StyleAction::SetBackground(None),
        }
    }

    /// Sets background on the last child element
    #[must_use]
    pub fn set_background_last_child(background: impl Into<String>) -> Self {
        Self::Style {
            target: ElementTarget::LastChild,
            action: StyleAction::SetBackground(Some(background.into())),
        }
    }

    /// Chains this action with another action
    #[must_use]
    pub fn and(self, action: impl Into<Self>) -> Self {
        if let Self::Multi(mut actions) = self {
            actions.push(action.into());
            Self::Multi(actions)
        } else {
            Self::Multi(vec![self, action.into()])
        }
    }

    /// Wraps this action with a throttle delay
    #[must_use]
    pub const fn throttle(self, millis: u64) -> ActionEffect {
        ActionEffect {
            action: self,
            throttle: Some(millis),
            delay_off: None,
            unique: None,
        }
    }

    /// Wraps this action with a `delay_off` duration
    #[must_use]
    pub const fn delay_off(self, millis: u64) -> ActionEffect {
        ActionEffect {
            action: self,
            throttle: None,
            delay_off: Some(millis),
            unique: None,
        }
    }

    /// Marks this action as unique
    #[must_use]
    pub const fn unique(self) -> ActionEffect {
        ActionEffect {
            action: self,
            throttle: None,
            delay_off: None,
            unique: Some(true),
        }
    }
}

#[cfg(feature = "logic")]
impl From<logic::If> for ActionType {
    /// Converts a conditional `If` into a `Logic` action type
    fn from(value: logic::If) -> Self {
        Self::Logic(value)
    }
}

impl From<ActionType> for Action {
    /// Converts an `ActionType` into an `Action` with immediate trigger and default timing
    fn from(value: ActionType) -> Self {
        Self {
            trigger: ActionTrigger::default(),
            effect: ActionEffect {
                action: value,
                delay_off: None,
                throttle: None,
                unique: None,
            },
        }
    }
}

#[cfg(feature = "serde")]
impl std::fmt::Display for ActionType {
    /// Formats the action type as JSON
    ///
    /// # Panics
    ///
    /// * If serialization fails (should not happen for valid action types)
    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 ActionType {
    type Error = serde_json::Error;

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

/// Style modification actions for UI elements
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum StyleAction {
    /// Set element visibility (visible or hidden)
    SetVisibility(Visibility),
    /// Set element focus state
    SetFocus(bool),
    /// Set element display property (true = displayed, false = not displayed)
    SetDisplay(bool),
    /// Set element background color (None to remove background)
    SetBackground(Option<String>),
}

#[cfg(feature = "serde")]
impl std::fmt::Display for StyleAction {
    /// Formats the style action as JSON
    ///
    /// # Panics
    ///
    /// * If serialization fails (should not happen for valid style actions)
    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 StyleAction {
    type Error = serde_json::Error;

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

pub mod prelude {
    //! Convenience re-exports for common action APIs.

    pub use crate::{
        Action, ActionEffect, ActionTrigger, ActionType, ElementTarget, LogLevel, StyleAction,
        dsl::*,
    };

    #[cfg(feature = "logic")]
    pub use crate::logic::*;
}

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

    #[test_log::test]
    fn test_action_effect_delay_off() {
        let action = ActionType::NoOp;
        let effect = action.delay_off(1000);

        assert_eq!(effect.delay_off, Some(1000));
        assert_eq!(effect.throttle, None);
        assert_eq!(effect.unique, None);
    }

    #[test_log::test]
    fn test_action_effect_throttle() {
        let action = ActionType::NoOp;
        let effect = action.throttle(500);

        assert_eq!(effect.throttle, Some(500));
        assert_eq!(effect.delay_off, None);
        assert_eq!(effect.unique, None);
    }

    #[test_log::test]
    fn test_action_effect_unique() {
        let action = ActionType::NoOp;
        let effect = action.unique();

        assert_eq!(effect.unique, Some(true));
        assert_eq!(effect.throttle, None);
        assert_eq!(effect.delay_off, None);
    }

    #[test_log::test]
    fn test_action_effect_chaining() {
        let effect = ActionEffect::default()
            .delay_off(1000)
            .throttle(500)
            .unique();

        assert_eq!(effect.delay_off, Some(1000));
        assert_eq!(effect.throttle, Some(500));
        assert_eq!(effect.unique, Some(true));
    }

    #[test_log::test]
    fn test_action_type_hide_by_id() {
        let action = ActionType::hide_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Hidden));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_show_by_id() {
        let action = ActionType::show_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Visible));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_hide_id() {
        let action = ActionType::hide_id(42);

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::Id(42));
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Hidden));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_show_id() {
        let action = ActionType::show_id(42);

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::Id(42));
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Visible));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_hide_self() {
        let action = ActionType::hide_self();

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::SelfTarget);
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Hidden));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_show_self() {
        let action = ActionType::show_self();

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::SelfTarget);
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Visible));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_display_by_id() {
        let action = ActionType::display_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetDisplay(true));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_no_display_by_id() {
        let action = ActionType::no_display_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetDisplay(false));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_set_focus() {
        let action = ActionType::set_focus_by_id(true, "my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetFocus(true));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_focus_by_id() {
        let action = ActionType::focus_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetFocus(true));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_set_background() {
        let action = ActionType::set_background_by_id("red", "my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetBackground(Some("red".to_string())));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_remove_background() {
        let action = ActionType::remove_background_by_id("my-element");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::ById(Target::from("my-element")));
                assert_eq!(action, StyleAction::SetBackground(None));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_navigate() {
        let action = ActionType::Navigate {
            url: "/home".to_string(),
        };

        match action {
            ActionType::Navigate { url } => {
                assert_eq!(url, "/home");
            }
            _ => panic!("Expected Navigate action"),
        }
    }

    #[test_log::test]
    fn test_action_type_log() {
        let action = ActionType::Log {
            message: "test".to_string(),
            level: LogLevel::Info,
        };

        match action {
            ActionType::Log { message, level } => {
                assert_eq!(message, "test");
                assert_eq!(level, LogLevel::Info);
            }
            _ => panic!("Expected Log action"),
        }
    }

    #[test_log::test]
    #[allow(clippy::similar_names)]
    fn test_action_type_and_chaining() {
        let action1 = ActionType::hide_by_id("element1");
        let action2 = ActionType::show_by_id("element2");
        let chained = action1.and(action2);

        match chained {
            ActionType::Multi(actions) => {
                assert_eq!(actions.len(), 2);
            }
            _ => panic!("Expected Multi action"),
        }
    }

    #[test_log::test]
    #[allow(clippy::similar_names)]
    fn test_action_type_and_chaining_with_existing_multi() {
        let action1 = ActionType::hide_by_id("element1");
        let action2 = ActionType::show_by_id("element2");
        let action3 = ActionType::no_display_by_id("element3");

        let chained = action1.and(action2).and(action3);

        match chained {
            ActionType::Multi(actions) => {
                assert_eq!(actions.len(), 3);
            }
            _ => panic!("Expected Multi action"),
        }
    }

    #[test_log::test]
    fn test_action_type_on_event() {
        let inner_action = ActionType::show_by_id("element");
        let event_action = ActionType::on_event("custom-event", inner_action);

        match event_action {
            ActionType::Event { name, action } => {
                assert_eq!(name, "custom-event");
                match *action {
                    ActionType::Style { .. } => {}
                    _ => panic!("Expected Style action inside Event"),
                }
            }
            _ => panic!("Expected Event action"),
        }
    }

    #[test_log::test]
    fn test_action_type_select_by_id() {
        let action = ActionType::select_by_id("input-field");

        match action {
            ActionType::Input(InputActionType::Select { target }) => {
                assert_eq!(target, ElementTarget::ById(Target::from("input-field")));
            }
            _ => panic!("Expected Input Select action"),
        }
    }

    #[test_log::test]
    fn test_action_effect_from_vec_action_types() {
        let actions = vec![
            ActionType::hide_by_id("element1"),
            ActionType::show_by_id("element2"),
        ];
        let effect: ActionEffect = actions.into();

        match effect.action {
            ActionType::Multi(inner_actions) => {
                assert_eq!(inner_actions.len(), 2);
            }
            _ => panic!("Expected Multi action"),
        }
    }

    #[test_log::test]
    fn test_action_effect_from_vec_action_effects() {
        let effects = vec![
            ActionEffect {
                action: ActionType::hide_by_id("element1"),
                delay_off: Some(100),
                throttle: None,
                unique: None,
            },
            ActionEffect {
                action: ActionType::show_by_id("element2"),
                delay_off: None,
                throttle: Some(200),
                unique: None,
            },
        ];
        let combined: ActionEffect = effects.into();

        match combined.action {
            ActionType::MultiEffect(inner_effects) => {
                assert_eq!(inner_effects.len(), 2);
                assert_eq!(inner_effects[0].delay_off, Some(100));
                assert_eq!(inner_effects[1].throttle, Some(200));
            }
            _ => panic!("Expected MultiEffect action"),
        }
    }

    #[test_log::test]
    fn test_action_from_action_type() {
        let action_type = ActionType::NoOp;
        let action: Action = action_type.into();

        assert_eq!(action.trigger, ActionTrigger::Immediate);
        assert_eq!(action.effect.action, ActionType::NoOp);
    }

    #[test_log::test]
    fn test_http_event_context_creation() {
        let context = HttpEventContext {
            url: "https://example.com".to_string(),
            method: "GET".to_string(),
            status: Some(200),
            headers: Some(BTreeMap::new()),
            duration_ms: Some(150),
            error: None,
        };

        assert_eq!(context.url, "https://example.com");
        assert_eq!(context.method, "GET");
        assert_eq!(context.status, Some(200));
        assert_eq!(context.duration_ms, Some(150));
        assert_eq!(context.error, None);
    }

    #[test_log::test]
    fn test_http_event_context_with_error() {
        let context = HttpEventContext {
            url: "https://example.com".to_string(),
            method: "POST".to_string(),
            status: None,
            headers: None,
            duration_ms: None,
            error: Some("Network timeout".to_string()),
        };

        assert_eq!(context.error, Some("Network timeout".to_string()));
        assert_eq!(context.status, None);
    }

    #[test_log::test]
    fn test_action_type_visibility_class() {
        let action = ActionType::hide_class("my-class");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::Class(Target::from("my-class")));
                assert_eq!(action, StyleAction::SetVisibility(Visibility::Hidden));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_display_class() {
        let action = ActionType::display_class("my-class");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::Class(Target::from("my-class")));
                assert_eq!(action, StyleAction::SetDisplay(true));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_background_last_child() {
        let action = ActionType::set_background_last_child("blue");

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::LastChild);
                assert_eq!(action, StyleAction::SetBackground(Some("blue".to_string())));
            }
            _ => panic!("Expected Style action"),
        }
    }

    #[test_log::test]
    fn test_action_type_remove_background_last_child() {
        let action = ActionType::remove_background_last_child();

        match action {
            ActionType::Style { target, action } => {
                assert_eq!(target, ElementTarget::LastChild);
                assert_eq!(action, StyleAction::SetBackground(None));
            }
            _ => panic!("Expected Style action"),
        }
    }
}