ratatui-interact 0.5.3

Interactive TUI components for ratatui with focus management and mouse support
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
//! MenuBar component - Horizontal menu bar with dropdown menus
//!
//! A traditional desktop-style menu bar (File, Edit, View, Help) with support
//! for dropdown menus, keyboard navigation, and mouse interaction.
//!
//! # Example
//!
//! ```rust
//! use ratatui_interact::components::{
//!     MenuBar, MenuBarState, MenuBarStyle, MenuBarItem, Menu,
//!     handle_menu_bar_key, handle_menu_bar_mouse,
//! };
//! use ratatui::layout::Rect;
//!
//! // Create menus
//! let menus = vec![
//!     Menu::new("File")
//!         .items(vec![
//!             MenuBarItem::action("new", "New").shortcut("Ctrl+N"),
//!             MenuBarItem::action("open", "Open").shortcut("Ctrl+O"),
//!             MenuBarItem::separator(),
//!             MenuBarItem::action("save", "Save").shortcut("Ctrl+S"),
//!             MenuBarItem::action("quit", "Quit").shortcut("Ctrl+Q"),
//!         ]),
//!     Menu::new("Edit")
//!         .items(vec![
//!             MenuBarItem::action("undo", "Undo").shortcut("Ctrl+Z"),
//!             MenuBarItem::action("redo", "Redo").shortcut("Ctrl+Y"),
//!         ]),
//! ];
//!
//! // Create state
//! let mut state = MenuBarState::new();
//!
//! // Create menu bar widget
//! let menu_bar = MenuBar::new(&menus, &state);
//!
//! // Render and handle events (see handle_menu_bar_key, handle_menu_bar_mouse)
//! ```

use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
};

use crate::traits::ClickRegion;

/// Actions a menu bar can emit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuBarAction {
    /// A menu was opened (menu index).
    MenuOpen(usize),
    /// The active menu was closed.
    MenuClose,
    /// An action item was selected (item ID).
    ItemSelect(String),
    /// Highlight changed (menu index, optional item index within dropdown).
    HighlightChange(usize, Option<usize>),
    /// A submenu was opened (parent menu index, parent item index).
    SubmenuOpen(usize, usize),
    /// A submenu was closed.
    SubmenuClose,
}

/// A single item in a menu dropdown.
#[derive(Debug, Clone)]
pub enum MenuBarItem {
    /// A clickable action item.
    Action {
        /// Unique identifier for this action.
        id: String,
        /// Display label.
        label: String,
        /// Optional keyboard shortcut display.
        shortcut: Option<String>,
        /// Whether the item is enabled.
        enabled: bool,
    },
    /// A visual separator line.
    Separator,
    /// A submenu that opens additional items.
    Submenu {
        /// Display label.
        label: String,
        /// Child menu items.
        items: Vec<MenuBarItem>,
        /// Whether the submenu is enabled.
        enabled: bool,
    },
}

impl MenuBarItem {
    /// Create a new action item.
    pub fn action(id: impl Into<String>, label: impl Into<String>) -> Self {
        Self::Action {
            id: id.into(),
            label: label.into(),
            shortcut: None,
            enabled: true,
        }
    }

    /// Create a separator.
    pub fn separator() -> Self {
        Self::Separator
    }

    /// Create a submenu.
    pub fn submenu(label: impl Into<String>, items: Vec<MenuBarItem>) -> Self {
        Self::Submenu {
            label: label.into(),
            items,
            enabled: true,
        }
    }

    /// Add a shortcut display to this item.
    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
        if let Self::Action { shortcut: s, .. } = &mut self {
            *s = Some(shortcut.into());
        }
        self
    }

    /// Set whether this item is enabled.
    pub fn enabled(mut self, enabled: bool) -> Self {
        match &mut self {
            Self::Action { enabled: e, .. } => *e = enabled,
            Self::Submenu { enabled: e, .. } => *e = enabled,
            Self::Separator => {}
        }
        self
    }

    /// Check if this item is selectable (not a separator and enabled).
    pub fn is_selectable(&self) -> bool {
        match self {
            Self::Action { enabled, .. } => *enabled,
            Self::Separator => false,
            Self::Submenu { enabled, .. } => *enabled,
        }
    }

    /// Check if this item has a submenu.
    pub fn has_submenu(&self) -> bool {
        matches!(self, Self::Submenu { .. })
    }

    /// Get the ID if this is an action item.
    pub fn id(&self) -> Option<&str> {
        if let Self::Action { id, .. } = self {
            Some(id)
        } else {
            None
        }
    }

    /// Get the label for this item.
    pub fn label(&self) -> Option<&str> {
        match self {
            Self::Action { label, .. } => Some(label),
            Self::Submenu { label, .. } => Some(label),
            Self::Separator => None,
        }
    }

    /// Get the shortcut for this item.
    pub fn get_shortcut(&self) -> Option<&str> {
        if let Self::Action { shortcut, .. } = self {
            shortcut.as_deref()
        } else {
            None
        }
    }

    /// Check if this item is enabled.
    pub fn is_enabled(&self) -> bool {
        match self {
            Self::Action { enabled, .. } => *enabled,
            Self::Separator => false,
            Self::Submenu { enabled, .. } => *enabled,
        }
    }

    /// Get submenu items if this is a submenu.
    pub fn submenu_items(&self) -> Option<&[MenuBarItem]> {
        if let Self::Submenu { items, .. } = self {
            Some(items)
        } else {
            None
        }
    }
}

/// A top-level menu in the menu bar.
#[derive(Debug, Clone)]
pub struct Menu {
    /// Display label for the menu.
    pub label: String,
    /// Items in this menu's dropdown.
    pub items: Vec<MenuBarItem>,
    /// Whether this menu is enabled.
    pub enabled: bool,
}

impl Menu {
    /// Create a new menu with a label.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            items: Vec::new(),
            enabled: true,
        }
    }

    /// Set the items for this menu.
    pub fn items(mut self, items: Vec<MenuBarItem>) -> Self {
        self.items = items;
        self
    }

    /// Set whether this menu is enabled.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

/// State for a menu bar.
#[derive(Debug, Clone)]
pub struct MenuBarState {
    /// Whether any menu is currently open.
    pub is_open: bool,
    /// Index of the currently active/highlighted menu (always set when focused).
    pub active_menu: usize,
    /// Currently highlighted item index within the dropdown (if open).
    pub highlighted_item: Option<usize>,
    /// Scroll offset for long dropdown menus.
    pub scroll_offset: u16,
    /// Whether the menu bar has focus.
    pub focused: bool,
    /// Index of active submenu item (if any).
    pub active_submenu: Option<usize>,
    /// State for active submenu.
    pub submenu_highlighted: Option<usize>,
    /// Submenu scroll offset.
    pub submenu_scroll_offset: u16,
}

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

impl MenuBarState {
    /// Create a new menu bar state.
    pub fn new() -> Self {
        Self {
            is_open: false,
            active_menu: 0,
            highlighted_item: None,
            scroll_offset: 0,
            focused: false,
            active_submenu: None,
            submenu_highlighted: None,
            submenu_scroll_offset: 0,
        }
    }

    /// Open the menu at the given index.
    pub fn open_menu(&mut self, index: usize) {
        self.is_open = true;
        self.active_menu = index;
        self.highlighted_item = None;
        self.scroll_offset = 0;
        self.close_submenu();
    }

    /// Close any open menu.
    pub fn close_menu(&mut self) {
        self.is_open = false;
        self.highlighted_item = None;
        self.scroll_offset = 0;
        self.close_submenu();
    }

    /// Toggle the menu at the given index.
    pub fn toggle_menu(&mut self, index: usize) {
        if self.is_open && self.active_menu == index {
            self.close_menu();
        } else {
            self.open_menu(index);
        }
    }

    /// Move to the next menu in the bar.
    pub fn next_menu(&mut self, menu_count: usize) {
        if menu_count == 0 {
            return;
        }
        self.active_menu = (self.active_menu + 1) % menu_count;
        if self.is_open {
            self.highlighted_item = None;
            self.scroll_offset = 0;
            self.close_submenu();
        }
    }

    /// Move to the previous menu in the bar.
    pub fn prev_menu(&mut self, menu_count: usize) {
        if menu_count == 0 {
            return;
        }
        if self.active_menu == 0 {
            self.active_menu = menu_count - 1;
        } else {
            self.active_menu -= 1;
        }
        if self.is_open {
            self.highlighted_item = None;
            self.scroll_offset = 0;
            self.close_submenu();
        }
    }

    /// Move highlight to the next item in the dropdown.
    pub fn next_item(&mut self, items: &[MenuBarItem]) {
        if items.is_empty() {
            return;
        }

        let current = self.highlighted_item.unwrap_or(0);
        let mut new_index = current;

        loop {
            new_index += 1;
            if new_index >= items.len() {
                // Wrap around to start
                new_index = 0;
            }
            if new_index == current {
                // We've gone full circle
                break;
            }
            if items.get(new_index).is_some_and(|i| i.is_selectable()) {
                self.highlighted_item = Some(new_index);
                break;
            }
        }
    }

    /// Move highlight to the previous item in the dropdown.
    pub fn prev_item(&mut self, items: &[MenuBarItem]) {
        if items.is_empty() {
            return;
        }

        let current = self.highlighted_item.unwrap_or(0);
        let mut new_index = current;

        loop {
            if new_index == 0 {
                new_index = items.len() - 1;
            } else {
                new_index -= 1;
            }
            if new_index == current {
                // We've gone full circle
                break;
            }
            if items.get(new_index).is_some_and(|i| i.is_selectable()) {
                self.highlighted_item = Some(new_index);
                break;
            }
        }
    }

    /// Move to first selectable item.
    pub fn highlight_first(&mut self, items: &[MenuBarItem]) {
        for (i, item) in items.iter().enumerate() {
            if item.is_selectable() {
                self.highlighted_item = Some(i);
                self.scroll_offset = 0;
                break;
            }
        }
    }

    /// Move to last selectable item.
    pub fn highlight_last(&mut self, items: &[MenuBarItem]) {
        for (i, item) in items.iter().enumerate().rev() {
            if item.is_selectable() {
                self.highlighted_item = Some(i);
                break;
            }
        }
    }

    /// Select an item by index.
    pub fn select_item(&mut self, index: usize) {
        self.highlighted_item = Some(index);
    }

    /// Open submenu at the highlighted index.
    pub fn open_submenu(&mut self) {
        if let Some(idx) = self.highlighted_item {
            self.active_submenu = Some(idx);
            self.submenu_highlighted = None;
            self.submenu_scroll_offset = 0;
        }
    }

    /// Close any open submenu.
    pub fn close_submenu(&mut self) {
        self.active_submenu = None;
        self.submenu_highlighted = None;
        self.submenu_scroll_offset = 0;
    }

    /// Check if a submenu is open.
    pub fn has_open_submenu(&self) -> bool {
        self.active_submenu.is_some()
    }

    /// Move to next item in submenu.
    pub fn next_submenu_item(&mut self, items: &[MenuBarItem]) {
        if items.is_empty() {
            return;
        }

        let current = self.submenu_highlighted.unwrap_or(0);
        let mut new_index = current;

        loop {
            new_index += 1;
            if new_index >= items.len() {
                new_index = 0;
            }
            if new_index == current {
                break;
            }
            if items.get(new_index).is_some_and(|i| i.is_selectable()) {
                self.submenu_highlighted = Some(new_index);
                break;
            }
        }
    }

    /// Move to previous item in submenu.
    pub fn prev_submenu_item(&mut self, items: &[MenuBarItem]) {
        if items.is_empty() {
            return;
        }

        let current = self.submenu_highlighted.unwrap_or(0);
        let mut new_index = current;

        loop {
            if new_index == 0 {
                new_index = items.len() - 1;
            } else {
                new_index -= 1;
            }
            if new_index == current {
                break;
            }
            if items.get(new_index).is_some_and(|i| i.is_selectable()) {
                self.submenu_highlighted = Some(new_index);
                break;
            }
        }
    }

    /// Ensure highlighted item is visible in viewport.
    pub fn ensure_visible(&mut self, viewport_height: usize) {
        if viewport_height == 0 {
            return;
        }
        if let Some(idx) = self.highlighted_item {
            if idx < self.scroll_offset as usize {
                self.scroll_offset = idx as u16;
            } else if idx >= self.scroll_offset as usize + viewport_height {
                self.scroll_offset = (idx - viewport_height + 1) as u16;
            }
        }
    }
}

/// Style configuration for menu bar.
#[derive(Debug, Clone)]
pub struct MenuBarStyle {
    /// Background color for the menu bar.
    pub bar_bg: Color,
    /// Foreground color for menu labels.
    pub bar_fg: Color,
    /// Background color for highlighted menu label.
    pub bar_highlight_bg: Color,
    /// Foreground color for highlighted menu label.
    pub bar_highlight_fg: Color,
    /// Background color for dropdown.
    pub dropdown_bg: Color,
    /// Border color for dropdown.
    pub dropdown_border: Color,
    /// Normal item foreground color.
    pub item_fg: Color,
    /// Highlighted item background.
    pub item_highlight_bg: Color,
    /// Highlighted item foreground.
    pub item_highlight_fg: Color,
    /// Shortcut text color.
    pub shortcut_fg: Color,
    /// Disabled item/menu foreground.
    pub disabled_fg: Color,
    /// Separator color.
    pub separator_fg: Color,
    /// Minimum dropdown width.
    pub dropdown_min_width: u16,
    /// Maximum dropdown height (items visible).
    pub dropdown_max_height: u16,
    /// Padding between menu labels.
    pub menu_padding: u16,
    /// Horizontal padding inside dropdown.
    pub dropdown_padding: u16,
    /// Submenu indicator.
    pub submenu_indicator: &'static str,
    /// Separator character.
    pub separator_char: char,
}

impl Default for MenuBarStyle {
    fn default() -> Self {
        Self {
            bar_bg: Color::Rgb(50, 50, 50),
            bar_fg: Color::White,
            bar_highlight_bg: Color::Rgb(70, 70, 70),
            bar_highlight_fg: Color::White,
            dropdown_bg: Color::Rgb(40, 40, 40),
            dropdown_border: Color::Rgb(80, 80, 80),
            item_fg: Color::White,
            item_highlight_bg: Color::Rgb(60, 100, 180),
            item_highlight_fg: Color::White,
            shortcut_fg: Color::Rgb(140, 140, 140),
            disabled_fg: Color::DarkGray,
            separator_fg: Color::Rgb(80, 80, 80),
            dropdown_min_width: 15,
            dropdown_max_height: 15,
            menu_padding: 2,
            dropdown_padding: 1,
            submenu_indicator: "â–¶",
            separator_char: '─',
        }
    }
}

impl From<&crate::theme::Theme> for MenuBarStyle {
    fn from(theme: &crate::theme::Theme) -> Self {
        let p = &theme.palette;
        Self {
            bar_bg: p.surface_raised,
            bar_fg: p.text,
            bar_highlight_bg: Color::Rgb(70, 70, 70),
            bar_highlight_fg: p.text,
            dropdown_bg: p.surface,
            dropdown_border: p.separator,
            item_fg: p.text,
            item_highlight_bg: p.menu_highlight_bg,
            item_highlight_fg: p.menu_highlight_fg,
            shortcut_fg: p.text_muted,
            disabled_fg: p.text_disabled,
            separator_fg: p.separator,
            dropdown_min_width: 15,
            dropdown_max_height: 15,
            menu_padding: 2,
            dropdown_padding: 1,
            submenu_indicator: "â–¶",
            separator_char: '─',
        }
    }
}

impl MenuBarStyle {
    /// Create a light theme style.
    pub fn light() -> Self {
        Self {
            bar_bg: Color::Rgb(240, 240, 240),
            bar_fg: Color::Rgb(30, 30, 30),
            bar_highlight_bg: Color::Rgb(200, 200, 200),
            bar_highlight_fg: Color::Rgb(30, 30, 30),
            dropdown_bg: Color::Rgb(250, 250, 250),
            dropdown_border: Color::Rgb(180, 180, 180),
            item_fg: Color::Rgb(30, 30, 30),
            item_highlight_bg: Color::Rgb(0, 120, 215),
            item_highlight_fg: Color::White,
            shortcut_fg: Color::Rgb(100, 100, 100),
            disabled_fg: Color::Rgb(160, 160, 160),
            separator_fg: Color::Rgb(200, 200, 200),
            ..Default::default()
        }
    }

    /// Create a minimal style.
    pub fn minimal() -> Self {
        Self {
            bar_bg: Color::Reset,
            bar_fg: Color::White,
            bar_highlight_bg: Color::Blue,
            bar_highlight_fg: Color::White,
            dropdown_bg: Color::Reset,
            dropdown_border: Color::Gray,
            item_fg: Color::White,
            item_highlight_bg: Color::Blue,
            item_highlight_fg: Color::White,
            shortcut_fg: Color::Gray,
            disabled_fg: Color::DarkGray,
            separator_fg: Color::DarkGray,
            ..Default::default()
        }
    }

    /// Set bar colors.
    pub fn bar_colors(mut self, fg: Color, bg: Color) -> Self {
        self.bar_fg = fg;
        self.bar_bg = bg;
        self
    }

    /// Set bar highlight colors.
    pub fn bar_highlight(mut self, fg: Color, bg: Color) -> Self {
        self.bar_highlight_fg = fg;
        self.bar_highlight_bg = bg;
        self
    }

    /// Set dropdown colors.
    pub fn dropdown_colors(mut self, fg: Color, bg: Color, border: Color) -> Self {
        self.item_fg = fg;
        self.dropdown_bg = bg;
        self.dropdown_border = border;
        self
    }

    /// Set item highlight colors.
    pub fn item_highlight(mut self, fg: Color, bg: Color) -> Self {
        self.item_highlight_fg = fg;
        self.item_highlight_bg = bg;
        self
    }

    /// Set minimum dropdown width.
    pub fn dropdown_min_width(mut self, width: u16) -> Self {
        self.dropdown_min_width = width;
        self
    }

    /// Set maximum dropdown height.
    pub fn dropdown_max_height(mut self, height: u16) -> Self {
        self.dropdown_max_height = height;
        self
    }

    /// Set the submenu indicator.
    pub fn submenu_indicator(mut self, indicator: &'static str) -> Self {
        self.submenu_indicator = indicator;
        self
    }
}

/// Click region identifier for menu bar.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuBarClickTarget {
    /// A menu label in the bar.
    MenuLabel(usize),
    /// An item in the dropdown.
    DropdownItem(usize),
    /// An item in a submenu.
    SubmenuItem(usize),
}

/// Menu bar widget.
///
/// A horizontal menu bar with dropdown menus.
pub struct MenuBar<'a> {
    menus: &'a [Menu],
    state: &'a MenuBarState,
    style: MenuBarStyle,
}

impl<'a> MenuBar<'a> {
    /// Create a new menu bar.
    pub fn new(menus: &'a [Menu], state: &'a MenuBarState) -> Self {
        Self {
            menus,
            state,
            style: MenuBarStyle::default(),
        }
    }

    /// Set the style.
    pub fn style(mut self, style: MenuBarStyle) -> Self {
        self.style = style;
        self
    }

    /// Apply a theme to derive the style.
    pub fn theme(self, theme: &crate::theme::Theme) -> Self {
        self.style(MenuBarStyle::from(theme))
    }

    /// Calculate the required width for a dropdown.
    fn calculate_dropdown_width(&self, items: &[MenuBarItem]) -> u16 {
        let mut max_label_width = 0u16;
        let mut max_shortcut_width = 0u16;

        for item in items {
            match item {
                MenuBarItem::Action {
                    label, shortcut, ..
                } => {
                    max_label_width = max_label_width.max(label.chars().count() as u16);
                    if let Some(s) = shortcut {
                        max_shortcut_width = max_shortcut_width.max(s.chars().count() as u16);
                    }
                }
                MenuBarItem::Submenu { label, .. } => {
                    // +2 for submenu indicator
                    let label_width = label.chars().count() as u16 + 2;
                    max_label_width = max_label_width.max(label_width);
                }
                MenuBarItem::Separator => {}
            }
        }

        // Total width: padding + label + gap + shortcut + padding + borders
        let content_width = self.style.dropdown_padding
            + max_label_width
            + if max_shortcut_width > 0 {
                2 + max_shortcut_width
            } else {
                0
            }
            + self.style.dropdown_padding;

        (content_width + 2).max(self.style.dropdown_min_width)
    }

    /// Calculate the height for a dropdown.
    fn calculate_dropdown_height(&self, item_count: usize) -> u16 {
        let visible = (item_count as u16).min(self.style.dropdown_max_height);
        visible + 2 // +2 for borders
    }

    /// Calculate dropdown area based on menu position and screen bounds.
    fn calculate_dropdown_area(
        &self,
        menu_x: u16,
        bar_bottom: u16,
        items: &[MenuBarItem],
        screen: Rect,
    ) -> Rect {
        let width = self.calculate_dropdown_width(items);
        let height = self.calculate_dropdown_height(items.len());

        // Prefer below the menu bar
        let y = bar_bottom;

        // Prefer aligned with menu label, adjust if needed
        let x = if menu_x + width <= screen.x + screen.width {
            menu_x
        } else {
            screen.x + screen.width.saturating_sub(width)
        };

        // Ensure we stay within screen bounds
        let final_width = width.min(screen.width.saturating_sub(x.saturating_sub(screen.x)));
        let final_height = height.min(screen.height.saturating_sub(y.saturating_sub(screen.y)));

        Rect::new(x, y, final_width, final_height)
    }

    /// Render the menu bar and return click regions.
    ///
    /// Returns a tuple of (bar_area, dropdown_area, click_regions).
    pub fn render_stateful(
        &self,
        frame: &mut Frame,
        area: Rect,
    ) -> (Rect, Option<Rect>, Vec<ClickRegion<MenuBarClickTarget>>) {
        let mut regions = Vec::new();

        if area.height == 0 || self.menus.is_empty() {
            return (Rect::default(), None, regions);
        }

        // Render the bar (1 row high)
        let bar_area = Rect::new(area.x, area.y, area.width, 1);

        // Fill bar background
        let bar_style = Style::default().bg(self.style.bar_bg);
        let bar_line = " ".repeat(bar_area.width as usize);
        let bar_para = Paragraph::new(Span::styled(bar_line, bar_style));
        frame.render_widget(bar_para, bar_area);

        // Render menu labels
        let mut x = bar_area.x;
        let mut menu_positions: Vec<(u16, u16)> = Vec::new(); // (x, width) for each menu

        for (idx, menu) in self.menus.iter().enumerate() {
            let label = format!(" {} ", menu.label);
            let label_width = label.chars().count() as u16;

            let is_active = self.state.focused && idx == self.state.active_menu;
            let is_open = self.state.is_open && idx == self.state.active_menu;

            let (fg, bg) = if !menu.enabled {
                (self.style.disabled_fg, self.style.bar_bg)
            } else if is_active || is_open {
                (self.style.bar_highlight_fg, self.style.bar_highlight_bg)
            } else {
                (self.style.bar_fg, self.style.bar_bg)
            };

            let style = Style::default().fg(fg).bg(bg);
            let label_area = Rect::new(x, bar_area.y, label_width, 1);

            let para = Paragraph::new(Span::styled(label.clone(), style));
            frame.render_widget(para, label_area);

            menu_positions.push((x, label_width));

            // Register click region for menu label
            if menu.enabled {
                regions.push(ClickRegion::new(
                    label_area,
                    MenuBarClickTarget::MenuLabel(idx),
                ));
            }

            x += label_width + self.style.menu_padding;
        }

        // Render dropdown if a menu is open
        let dropdown_area = if self.state.is_open {
            if let Some(menu) = self.menus.get(self.state.active_menu) {
                if let Some(&(menu_x, _)) = menu_positions.get(self.state.active_menu) {
                    let screen = frame.area();
                    let dropdown_area =
                        self.calculate_dropdown_area(menu_x, bar_area.y + 1, &menu.items, screen);

                    // Clear background (overlay)
                    frame.render_widget(Clear, dropdown_area);

                    // Render border
                    let block = Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::default().fg(self.style.dropdown_border))
                        .style(Style::default().bg(self.style.dropdown_bg));

                    let inner = block.inner(dropdown_area);
                    frame.render_widget(block, dropdown_area);

                    // Render items
                    let visible_count = inner.height as usize;
                    let scroll = self.state.scroll_offset as usize;

                    for (display_idx, (item_idx, item)) in menu
                        .items
                        .iter()
                        .enumerate()
                        .skip(scroll)
                        .take(visible_count)
                        .enumerate()
                    {
                        let y = inner.y + display_idx as u16;
                        let item_area = Rect::new(inner.x, y, inner.width, 1);

                        let is_highlighted = self.state.highlighted_item == Some(item_idx);

                        self.render_menu_item(
                            frame,
                            item,
                            item_area,
                            is_highlighted,
                            &mut regions,
                            item_idx,
                            false,
                        );
                    }

                    // Render submenu if open
                    if let Some(submenu_idx) = self.state.active_submenu {
                        if let Some(MenuBarItem::Submenu { items, .. }) =
                            menu.items.get(submenu_idx)
                        {
                            let submenu_x = dropdown_area.x + dropdown_area.width;
                            let submenu_y = dropdown_area.y
                                + 1
                                + (submenu_idx as u16).saturating_sub(self.state.scroll_offset);

                            let submenu_width = self.calculate_dropdown_width(items);
                            let submenu_height = self.calculate_dropdown_height(items.len());

                            let screen = frame.area();

                            // Adjust submenu position to stay on screen
                            let final_x = if submenu_x + submenu_width <= screen.x + screen.width {
                                submenu_x
                            } else {
                                dropdown_area.x.saturating_sub(submenu_width)
                            };

                            let submenu_area = Rect::new(
                                final_x,
                                submenu_y.min(screen.y + screen.height - submenu_height),
                                submenu_width,
                                submenu_height,
                            );

                            // Clear and render submenu
                            frame.render_widget(Clear, submenu_area);

                            let block = Block::default()
                                .borders(Borders::ALL)
                                .border_style(Style::default().fg(self.style.dropdown_border))
                                .style(Style::default().bg(self.style.dropdown_bg));

                            let sub_inner = block.inner(submenu_area);
                            frame.render_widget(block, submenu_area);

                            let sub_visible = sub_inner.height as usize;
                            let sub_scroll = self.state.submenu_scroll_offset as usize;

                            for (display_idx, (item_idx, item)) in items
                                .iter()
                                .enumerate()
                                .skip(sub_scroll)
                                .take(sub_visible)
                                .enumerate()
                            {
                                let y = sub_inner.y + display_idx as u16;
                                let item_area = Rect::new(sub_inner.x, y, sub_inner.width, 1);

                                let is_highlighted =
                                    self.state.submenu_highlighted == Some(item_idx);

                                self.render_menu_item(
                                    frame,
                                    item,
                                    item_area,
                                    is_highlighted,
                                    &mut regions,
                                    item_idx,
                                    true,
                                );
                            }
                        }
                    }

                    Some(dropdown_area)
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        };

        (bar_area, dropdown_area, regions)
    }

    /// Render a single menu item.
    #[allow(clippy::too_many_arguments)]
    fn render_menu_item(
        &self,
        frame: &mut Frame,
        item: &MenuBarItem,
        item_area: Rect,
        is_highlighted: bool,
        regions: &mut Vec<ClickRegion<MenuBarClickTarget>>,
        item_idx: usize,
        is_submenu: bool,
    ) {
        match item {
            MenuBarItem::Separator => {
                let sep_line: String =
                    std::iter::repeat_n(self.style.separator_char, item_area.width as usize)
                        .collect();
                let para = Paragraph::new(Span::styled(
                    sep_line,
                    Style::default()
                        .fg(self.style.separator_fg)
                        .bg(self.style.dropdown_bg),
                ));
                frame.render_widget(para, item_area);
            }
            MenuBarItem::Action {
                label,
                shortcut,
                enabled,
                id,
            } => {
                let (fg, bg) = if !enabled {
                    (self.style.disabled_fg, self.style.dropdown_bg)
                } else if is_highlighted {
                    (self.style.item_highlight_fg, self.style.item_highlight_bg)
                } else {
                    (self.style.item_fg, self.style.dropdown_bg)
                };

                let style = Style::default().fg(fg).bg(bg);
                let shortcut_style = Style::default()
                    .fg(if *enabled {
                        self.style.shortcut_fg
                    } else {
                        self.style.disabled_fg
                    })
                    .bg(bg);

                let mut spans = Vec::new();

                // Padding
                spans.push(Span::styled(
                    " ".repeat(self.style.dropdown_padding as usize),
                    style,
                ));

                // Label
                spans.push(Span::styled(label.clone(), style));

                // Fill space before shortcut
                let current_len: usize = spans.iter().map(|s| s.content.chars().count()).sum();
                let shortcut_len = shortcut.as_ref().map(|s| s.chars().count()).unwrap_or(0);
                let fill_len = (item_area.width as usize)
                    .saturating_sub(current_len)
                    .saturating_sub(shortcut_len)
                    .saturating_sub(self.style.dropdown_padding as usize);

                if fill_len > 0 {
                    spans.push(Span::styled(" ".repeat(fill_len), style));
                }

                // Shortcut
                if let Some(sc) = shortcut {
                    spans.push(Span::styled(sc.clone(), shortcut_style));
                }

                // Right padding
                spans.push(Span::styled(
                    " ".repeat(self.style.dropdown_padding as usize),
                    style,
                ));

                let para = Paragraph::new(Line::from(spans));
                frame.render_widget(para, item_area);

                // Register click region
                if *enabled {
                    let target = if is_submenu {
                        MenuBarClickTarget::SubmenuItem(item_idx)
                    } else {
                        MenuBarClickTarget::DropdownItem(item_idx)
                    };
                    regions.push(ClickRegion::new(item_area, target));
                }

                // Silence unused variable warning
                let _ = id;
            }
            MenuBarItem::Submenu { label, enabled, .. } => {
                let (fg, bg) = if !enabled {
                    (self.style.disabled_fg, self.style.dropdown_bg)
                } else if is_highlighted {
                    (self.style.item_highlight_fg, self.style.item_highlight_bg)
                } else {
                    (self.style.item_fg, self.style.dropdown_bg)
                };

                let style = Style::default().fg(fg).bg(bg);

                let mut spans = Vec::new();

                // Padding
                spans.push(Span::styled(
                    " ".repeat(self.style.dropdown_padding as usize),
                    style,
                ));

                // Label
                spans.push(Span::styled(label.clone(), style));

                // Fill and submenu indicator
                let current_len: usize = spans.iter().map(|s| s.content.chars().count()).sum();
                let indicator_len = self.style.submenu_indicator.chars().count();
                let fill_len = (item_area.width as usize)
                    .saturating_sub(current_len)
                    .saturating_sub(indicator_len)
                    .saturating_sub(self.style.dropdown_padding as usize);

                if fill_len > 0 {
                    spans.push(Span::styled(" ".repeat(fill_len), style));
                }

                spans.push(Span::styled(self.style.submenu_indicator, style));

                // Right padding
                spans.push(Span::styled(
                    " ".repeat(self.style.dropdown_padding as usize),
                    style,
                ));

                let para = Paragraph::new(Line::from(spans));
                frame.render_widget(para, item_area);

                // Register click region (only for parent dropdown, not for nested submenus)
                if *enabled && !is_submenu {
                    regions.push(ClickRegion::new(
                        item_area,
                        MenuBarClickTarget::DropdownItem(item_idx),
                    ));
                }
            }
        }
    }
}

/// Handle keyboard events for menu bar.
///
/// Returns `Some(MenuBarAction)` if an action was triggered, `None` otherwise.
///
/// # Key Bindings
///
/// - `Left/Right` - Navigate between menus
/// - `Up/Down` - Navigate within dropdown (opens menu if closed)
/// - `Enter/Space` - Select item or toggle menu
/// - `Escape` - Close menu
/// - `Home` - Jump to first item
/// - `End` - Jump to last item
#[allow(clippy::collapsible_match)]
pub fn handle_menu_bar_key(
    key: &KeyEvent,
    state: &mut MenuBarState,
    menus: &[Menu],
) -> Option<MenuBarAction> {
    if menus.is_empty() {
        return None;
    }

    // If submenu is open, handle submenu navigation
    if state.has_open_submenu() {
        if let Some(menu) = menus.get(state.active_menu) {
            if let Some(submenu_idx) = state.active_submenu {
                if let Some(MenuBarItem::Submenu { items, .. }) = menu.items.get(submenu_idx) {
                    match key.code {
                        KeyCode::Esc | KeyCode::Left => {
                            state.close_submenu();
                            return Some(MenuBarAction::SubmenuClose);
                        }
                        KeyCode::Up => {
                            state.prev_submenu_item(items);
                            return Some(MenuBarAction::HighlightChange(
                                state.active_menu,
                                state.submenu_highlighted,
                            ));
                        }
                        KeyCode::Down => {
                            state.next_submenu_item(items);
                            return Some(MenuBarAction::HighlightChange(
                                state.active_menu,
                                state.submenu_highlighted,
                            ));
                        }
                        KeyCode::Enter | KeyCode::Char(' ') => {
                            if let Some(idx) = state.submenu_highlighted {
                                if let Some(item) = items.get(idx) {
                                    if let MenuBarItem::Action { id, enabled, .. } = item {
                                        if *enabled {
                                            let action_id = id.clone();
                                            state.close_menu();
                                            return Some(MenuBarAction::ItemSelect(action_id));
                                        }
                                    }
                                }
                            }
                            return None;
                        }
                        _ => return None,
                    }
                }
            }
        }
    }

    match key.code {
        KeyCode::Left => {
            state.prev_menu(menus.len());
            Some(MenuBarAction::HighlightChange(state.active_menu, None))
        }
        KeyCode::Right => {
            // If on a submenu item, open it
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    if let Some(idx) = state.highlighted_item {
                        if let Some(item) = menu.items.get(idx) {
                            if item.has_submenu() && item.is_enabled() {
                                state.open_submenu();
                                return Some(MenuBarAction::SubmenuOpen(state.active_menu, idx));
                            }
                        }
                    }
                }
            }
            state.next_menu(menus.len());
            Some(MenuBarAction::HighlightChange(state.active_menu, None))
        }
        KeyCode::Down => {
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    state.next_item(&menu.items);
                    state.ensure_visible(8);
                    Some(MenuBarAction::HighlightChange(
                        state.active_menu,
                        state.highlighted_item,
                    ))
                } else {
                    None
                }
            } else {
                state.open_menu(state.active_menu);
                if let Some(menu) = menus.get(state.active_menu) {
                    state.highlight_first(&menu.items);
                }
                Some(MenuBarAction::MenuOpen(state.active_menu))
            }
        }
        KeyCode::Up => {
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    state.prev_item(&menu.items);
                    state.ensure_visible(8);
                    Some(MenuBarAction::HighlightChange(
                        state.active_menu,
                        state.highlighted_item,
                    ))
                } else {
                    None
                }
            } else {
                None
            }
        }
        KeyCode::Enter | KeyCode::Char(' ') => {
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    if let Some(idx) = state.highlighted_item {
                        if let Some(item) = menu.items.get(idx) {
                            match item {
                                MenuBarItem::Action { id, enabled, .. } if *enabled => {
                                    let action_id = id.clone();
                                    state.close_menu();
                                    return Some(MenuBarAction::ItemSelect(action_id));
                                }
                                MenuBarItem::Submenu { enabled, .. } if *enabled => {
                                    state.open_submenu();
                                    return Some(MenuBarAction::SubmenuOpen(
                                        state.active_menu,
                                        idx,
                                    ));
                                }
                                _ => {}
                            }
                        }
                    }
                }
                None
            } else {
                state.open_menu(state.active_menu);
                if let Some(menu) = menus.get(state.active_menu) {
                    state.highlight_first(&menu.items);
                }
                Some(MenuBarAction::MenuOpen(state.active_menu))
            }
        }
        KeyCode::Esc => {
            if state.is_open {
                state.close_menu();
                Some(MenuBarAction::MenuClose)
            } else {
                None
            }
        }
        KeyCode::Home => {
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    state.highlight_first(&menu.items);
                    Some(MenuBarAction::HighlightChange(
                        state.active_menu,
                        state.highlighted_item,
                    ))
                } else {
                    None
                }
            } else {
                state.active_menu = 0;
                Some(MenuBarAction::HighlightChange(0, None))
            }
        }
        KeyCode::End => {
            if state.is_open {
                if let Some(menu) = menus.get(state.active_menu) {
                    state.highlight_last(&menu.items);
                    state.ensure_visible(menu.items.len());
                    Some(MenuBarAction::HighlightChange(
                        state.active_menu,
                        state.highlighted_item,
                    ))
                } else {
                    None
                }
            } else {
                state.active_menu = menus.len().saturating_sub(1);
                Some(MenuBarAction::HighlightChange(state.active_menu, None))
            }
        }
        _ => None,
    }
}

/// Handle mouse events for menu bar.
///
/// Returns `Some(MenuBarAction)` if an action was triggered, `None` otherwise.
///
/// # Arguments
///
/// * `mouse` - The mouse event
/// * `state` - Mutable reference to menu bar state
/// * `bar_area` - The rendered bar area
/// * `dropdown_area` - The rendered dropdown area (if any)
/// * `click_regions` - Click regions from `render_stateful`
/// * `menus` - The menu definitions
#[allow(clippy::collapsible_match)]
pub fn handle_menu_bar_mouse(
    mouse: &MouseEvent,
    state: &mut MenuBarState,
    bar_area: Rect,
    dropdown_area: Option<Rect>,
    click_regions: &[ClickRegion<MenuBarClickTarget>],
    menus: &[Menu],
) -> Option<MenuBarAction> {
    let col = mouse.column;
    let row = mouse.row;

    match mouse.kind {
        MouseEventKind::Down(MouseButton::Left) => {
            // Check if clicked on a menu label
            for region in click_regions {
                if region.contains(col, row) {
                    match &region.data {
                        MenuBarClickTarget::MenuLabel(idx) => {
                            state.toggle_menu(*idx);
                            if state.is_open {
                                if let Some(menu) = menus.get(*idx) {
                                    state.highlight_first(&menu.items);
                                }
                                return Some(MenuBarAction::MenuOpen(*idx));
                            } else {
                                return Some(MenuBarAction::MenuClose);
                            }
                        }
                        MenuBarClickTarget::DropdownItem(idx) => {
                            if let Some(menu) = menus.get(state.active_menu) {
                                if let Some(item) = menu.items.get(*idx) {
                                    match item {
                                        MenuBarItem::Action { id, enabled, .. } if *enabled => {
                                            let action_id = id.clone();
                                            state.close_menu();
                                            return Some(MenuBarAction::ItemSelect(action_id));
                                        }
                                        MenuBarItem::Submenu { enabled, .. } if *enabled => {
                                            state.highlighted_item = Some(*idx);
                                            state.open_submenu();
                                            return Some(MenuBarAction::SubmenuOpen(
                                                state.active_menu,
                                                *idx,
                                            ));
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                        MenuBarClickTarget::SubmenuItem(idx) => {
                            if let Some(menu) = menus.get(state.active_menu) {
                                if let Some(submenu_idx) = state.active_submenu {
                                    if let Some(MenuBarItem::Submenu { items, .. }) =
                                        menu.items.get(submenu_idx)
                                    {
                                        if let Some(item) = items.get(*idx) {
                                            if let MenuBarItem::Action { id, enabled, .. } = item {
                                                if *enabled {
                                                    let action_id = id.clone();
                                                    state.close_menu();
                                                    return Some(MenuBarAction::ItemSelect(
                                                        action_id,
                                                    ));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Check if clicked outside menu
            let in_bar = bar_area.intersects(Rect::new(col, row, 1, 1));
            let in_dropdown = dropdown_area
                .map(|d| d.intersects(Rect::new(col, row, 1, 1)))
                .unwrap_or(false);

            if state.is_open && !in_bar && !in_dropdown {
                state.close_menu();
                return Some(MenuBarAction::MenuClose);
            }

            None
        }
        MouseEventKind::Moved => {
            // Update highlight on hover
            for region in click_regions {
                if region.contains(col, row) {
                    match &region.data {
                        MenuBarClickTarget::MenuLabel(idx) => {
                            // If a menu is open and we hover over a different menu label, switch to it
                            if state.is_open && state.active_menu != *idx {
                                state.open_menu(*idx);
                                if let Some(menu) = menus.get(*idx) {
                                    state.highlight_first(&menu.items);
                                }
                                return Some(MenuBarAction::MenuOpen(*idx));
                            }
                        }
                        MenuBarClickTarget::DropdownItem(idx) => {
                            if state.highlighted_item != Some(*idx) {
                                state.highlighted_item = Some(*idx);
                                // Close submenu when moving to different item
                                if state.active_submenu.is_some()
                                    && state.active_submenu != Some(*idx)
                                {
                                    state.close_submenu();
                                }
                                return Some(MenuBarAction::HighlightChange(
                                    state.active_menu,
                                    Some(*idx),
                                ));
                            }
                        }
                        MenuBarClickTarget::SubmenuItem(idx) => {
                            if state.submenu_highlighted != Some(*idx) {
                                state.submenu_highlighted = Some(*idx);
                                return Some(MenuBarAction::HighlightChange(
                                    state.active_menu,
                                    Some(*idx),
                                ));
                            }
                        }
                    }
                    break;
                }
            }
            None
        }
        _ => None,
    }
}

/// Calculate the height needed for a menu bar (always 1).
pub fn calculate_menu_bar_height() -> u16 {
    1
}

/// Calculate the height needed for a dropdown menu.
pub fn calculate_dropdown_height(item_count: usize, max_visible: u16) -> u16 {
    let visible = (item_count as u16).min(max_visible);
    visible + 2 // +2 for borders
}

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

    #[test]
    fn test_menu_bar_item_action() {
        let item = MenuBarItem::action("save", "Save").shortcut("Ctrl+S");

        assert!(item.is_selectable());
        assert!(!item.has_submenu());
        assert_eq!(item.id(), Some("save"));
        assert_eq!(item.label(), Some("Save"));
        assert_eq!(item.get_shortcut(), Some("Ctrl+S"));
    }

    #[test]
    fn test_menu_bar_item_separator() {
        let item = MenuBarItem::separator();

        assert!(!item.is_selectable());
        assert!(!item.has_submenu());
        assert_eq!(item.label(), None);
    }

    #[test]
    fn test_menu_bar_item_submenu() {
        let items = vec![MenuBarItem::action("sub1", "Sub Item 1")];
        let item = MenuBarItem::submenu("More", items);

        assert!(item.is_selectable());
        assert!(item.has_submenu());
        assert_eq!(item.label(), Some("More"));
        assert!(item.submenu_items().is_some());
    }

    #[test]
    fn test_menu_bar_item_disabled() {
        let item = MenuBarItem::action("delete", "Delete").enabled(false);

        assert!(!item.is_selectable());
        assert!(!item.is_enabled());
    }

    #[test]
    fn test_menu_creation() {
        let menu = Menu::new("File")
            .items(vec![
                MenuBarItem::action("new", "New"),
                MenuBarItem::separator(),
                MenuBarItem::action("quit", "Quit"),
            ])
            .enabled(true);

        assert_eq!(menu.label, "File");
        assert_eq!(menu.items.len(), 3);
        assert!(menu.enabled);
    }

    #[test]
    fn test_menu_bar_state_new() {
        let state = MenuBarState::new();

        assert!(!state.is_open);
        assert_eq!(state.active_menu, 0);
        assert_eq!(state.highlighted_item, None);
        assert!(!state.focused);
    }

    #[test]
    fn test_menu_bar_state_open_close() {
        let mut state = MenuBarState::new();

        state.open_menu(1);
        assert!(state.is_open);
        assert_eq!(state.active_menu, 1);
        assert_eq!(state.highlighted_item, None);

        state.close_menu();
        assert!(!state.is_open);
    }

    #[test]
    fn test_menu_bar_state_toggle() {
        let mut state = MenuBarState::new();

        state.toggle_menu(0);
        assert!(state.is_open);
        assert_eq!(state.active_menu, 0);

        state.toggle_menu(0);
        assert!(!state.is_open);

        state.toggle_menu(0);
        assert!(state.is_open);

        // Toggle different menu while open
        state.toggle_menu(1);
        assert!(state.is_open);
        assert_eq!(state.active_menu, 1);
    }

    #[test]
    fn test_menu_bar_state_navigation() {
        let mut state = MenuBarState::new();
        state.active_menu = 0;

        state.next_menu(3);
        assert_eq!(state.active_menu, 1);

        state.next_menu(3);
        assert_eq!(state.active_menu, 2);

        state.next_menu(3);
        assert_eq!(state.active_menu, 0); // Wrap around

        state.prev_menu(3);
        assert_eq!(state.active_menu, 2); // Wrap around

        state.prev_menu(3);
        assert_eq!(state.active_menu, 1);
    }

    #[test]
    fn test_menu_bar_state_item_navigation() {
        let mut state = MenuBarState::new();
        state.open_menu(0);

        let items = vec![
            MenuBarItem::action("a", "A"),
            MenuBarItem::separator(),
            MenuBarItem::action("b", "B"),
            MenuBarItem::action("c", "C"),
        ];

        // Move down (should skip separator)
        state.next_item(&items);
        // With no initial highlighted item, wraps from 0
        assert!(state.highlighted_item.is_some());

        state.highlight_first(&items);
        assert_eq!(state.highlighted_item, Some(0));

        state.next_item(&items);
        assert_eq!(state.highlighted_item, Some(2)); // Skipped separator

        state.next_item(&items);
        assert_eq!(state.highlighted_item, Some(3));

        state.prev_item(&items);
        assert_eq!(state.highlighted_item, Some(2));

        state.prev_item(&items);
        assert_eq!(state.highlighted_item, Some(0));
    }

    #[test]
    fn test_menu_bar_state_submenu() {
        let mut state = MenuBarState::new();
        state.open_menu(0);
        state.highlighted_item = Some(2);

        assert!(!state.has_open_submenu());

        state.open_submenu();
        assert!(state.has_open_submenu());
        assert_eq!(state.active_submenu, Some(2));

        state.close_submenu();
        assert!(!state.has_open_submenu());
    }

    #[test]
    fn test_menu_bar_style_default() {
        let style = MenuBarStyle::default();
        assert_eq!(style.dropdown_min_width, 15);
        assert_eq!(style.dropdown_max_height, 15);
        assert_eq!(style.submenu_indicator, "â–¶");
    }

    #[test]
    fn test_menu_bar_style_builders() {
        let style = MenuBarStyle::default()
            .dropdown_min_width(20)
            .dropdown_max_height(10)
            .submenu_indicator("→");

        assert_eq!(style.dropdown_min_width, 20);
        assert_eq!(style.dropdown_max_height, 10);
        assert_eq!(style.submenu_indicator, "→");
    }

    #[test]
    fn test_menu_bar_style_presets() {
        let light = MenuBarStyle::light();
        assert_eq!(light.bar_bg, Color::Rgb(240, 240, 240));

        let minimal = MenuBarStyle::minimal();
        assert_eq!(minimal.bar_bg, Color::Reset);
    }

    #[test]
    fn test_handle_key_left_right() {
        let mut state = MenuBarState::new();
        state.focused = true;

        let menus = vec![
            Menu::new("File").items(vec![]),
            Menu::new("Edit").items(vec![]),
            Menu::new("View").items(vec![]),
        ];

        let key = KeyEvent::from(KeyCode::Right);
        let action = handle_menu_bar_key(&key, &mut state, &menus);
        assert_eq!(action, Some(MenuBarAction::HighlightChange(1, None)));
        assert_eq!(state.active_menu, 1);

        let key = KeyEvent::from(KeyCode::Left);
        let action = handle_menu_bar_key(&key, &mut state, &menus);
        assert_eq!(action, Some(MenuBarAction::HighlightChange(0, None)));
        assert_eq!(state.active_menu, 0);
    }

    #[test]
    fn test_handle_key_down_opens_menu() {
        let mut state = MenuBarState::new();
        state.focused = true;

        let menus = vec![Menu::new("File").items(vec![MenuBarItem::action("new", "New")])];

        let key = KeyEvent::from(KeyCode::Down);
        let action = handle_menu_bar_key(&key, &mut state, &menus);

        assert_eq!(action, Some(MenuBarAction::MenuOpen(0)));
        assert!(state.is_open);
    }

    #[test]
    fn test_handle_key_escape_closes() {
        let mut state = MenuBarState::new();
        state.open_menu(0);

        let menus = vec![Menu::new("File").items(vec![])];

        let key = KeyEvent::from(KeyCode::Esc);
        let action = handle_menu_bar_key(&key, &mut state, &menus);

        assert_eq!(action, Some(MenuBarAction::MenuClose));
        assert!(!state.is_open);
    }

    #[test]
    fn test_handle_key_enter_selects_item() {
        let mut state = MenuBarState::new();
        state.open_menu(0);
        state.highlighted_item = Some(0);

        let menus = vec![Menu::new("File").items(vec![MenuBarItem::action("new", "New")])];

        let key = KeyEvent::from(KeyCode::Enter);
        let action = handle_menu_bar_key(&key, &mut state, &menus);

        assert_eq!(action, Some(MenuBarAction::ItemSelect("new".to_string())));
        assert!(!state.is_open);
    }

    #[test]
    fn test_handle_key_enter_opens_submenu() {
        let mut state = MenuBarState::new();
        state.open_menu(0);
        state.highlighted_item = Some(0);

        let menus = vec![Menu::new("File").items(vec![MenuBarItem::submenu(
            "Recent",
            vec![MenuBarItem::action("file1", "File 1")],
        )])];

        let key = KeyEvent::from(KeyCode::Enter);
        let action = handle_menu_bar_key(&key, &mut state, &menus);

        assert_eq!(action, Some(MenuBarAction::SubmenuOpen(0, 0)));
        assert!(state.has_open_submenu());
    }

    #[test]
    fn test_handle_key_empty_menus() {
        let mut state = MenuBarState::new();
        let menus: Vec<Menu> = vec![];

        let key = KeyEvent::from(KeyCode::Down);
        let action = handle_menu_bar_key(&key, &mut state, &menus);

        assert!(action.is_none());
    }

    #[test]
    fn test_menu_bar_action_equality() {
        assert_eq!(MenuBarAction::MenuOpen(0), MenuBarAction::MenuOpen(0));
        assert_ne!(MenuBarAction::MenuOpen(0), MenuBarAction::MenuOpen(1));
        assert_eq!(MenuBarAction::MenuClose, MenuBarAction::MenuClose);
        assert_eq!(
            MenuBarAction::ItemSelect("test".to_string()),
            MenuBarAction::ItemSelect("test".to_string())
        );
        assert_eq!(
            MenuBarAction::HighlightChange(0, Some(1)),
            MenuBarAction::HighlightChange(0, Some(1))
        );
    }

    #[test]
    fn test_calculate_heights() {
        assert_eq!(calculate_menu_bar_height(), 1);
        assert_eq!(calculate_dropdown_height(5, 15), 7); // 5 + 2
        assert_eq!(calculate_dropdown_height(20, 15), 17); // 15 + 2 (clamped)
    }

    #[test]
    fn test_menu_bar_widget_new() {
        let menus = vec![Menu::new("File").items(vec![])];
        let state = MenuBarState::new();
        let _menu_bar = MenuBar::new(&menus, &state);
    }

    #[test]
    fn test_menu_bar_widget_style() {
        let menus = vec![Menu::new("File").items(vec![])];
        let state = MenuBarState::new();
        let style = MenuBarStyle::light();
        let _menu_bar = MenuBar::new(&menus, &state).style(style);
    }

    #[test]
    fn test_click_target_equality() {
        assert_eq!(
            MenuBarClickTarget::MenuLabel(0),
            MenuBarClickTarget::MenuLabel(0)
        );
        assert_ne!(
            MenuBarClickTarget::MenuLabel(0),
            MenuBarClickTarget::MenuLabel(1)
        );
        assert_eq!(
            MenuBarClickTarget::DropdownItem(0),
            MenuBarClickTarget::DropdownItem(0)
        );
        assert_eq!(
            MenuBarClickTarget::SubmenuItem(0),
            MenuBarClickTarget::SubmenuItem(0)
        );
    }

    #[test]
    fn test_menu_bar_state_ensure_visible() {
        let mut state = MenuBarState::new();
        state.highlighted_item = Some(15);
        state.scroll_offset = 0;

        state.ensure_visible(10);
        assert!(state.scroll_offset >= 6);

        state.highlighted_item = Some(3);
        state.ensure_visible(10);
        assert!(state.scroll_offset <= 3);
    }

    #[test]
    fn test_menu_bar_state_highlight_first_last() {
        let mut state = MenuBarState::new();
        state.open_menu(0);

        let items = vec![
            MenuBarItem::separator(),
            MenuBarItem::action("a", "A"),
            MenuBarItem::action("b", "B"),
            MenuBarItem::separator(),
            MenuBarItem::action("c", "C"),
        ];

        state.highlight_first(&items);
        assert_eq!(state.highlighted_item, Some(1));

        state.highlight_last(&items);
        assert_eq!(state.highlighted_item, Some(4));
    }

    #[test]
    fn test_submenu_navigation() {
        let mut state = MenuBarState::new();
        state.open_menu(0);
        state.highlighted_item = Some(0);
        state.open_submenu();

        let items = vec![
            MenuBarItem::action("a", "A"),
            MenuBarItem::separator(),
            MenuBarItem::action("b", "B"),
        ];

        state.next_submenu_item(&items);
        // Should skip separator
        assert!(state.submenu_highlighted.is_some());

        state.prev_submenu_item(&items);
        assert!(state.submenu_highlighted.is_some());
    }
}