migui 0.4.1

Immediate Mode GUI in pure Rust for game engines
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
//! # migui - Immediate Mode GUI puro en Rust
//!
//! **Sistema de GUI independiente sin dependencias gráficas**
//!
//! ## Filosofía
//! - **Immediate Mode**: Cada frame se evalúa desde cero
//! - **Sin dependencias**: Funciona en cualquier plataforma
//! - **Backend agnóstico**: Se conecta a raylib, terminal, web, etc.
//!
//! ## Ejemplo
//! ```rust
//! use migui::{Migui, Event, WidgetId};
//!
//! let mut gui = Migui::new();
//! let mut contador = 0;
//!
//! // En tu game loop:
//! // gui.begin_frame();
//! // if gui.button(WidgetId::new("btn"), rect(10, 10, 100, 30)) {
//! //     contador += 1;
//! // }
//! // gui.end_frame();
//! ```

// Backend SDL2 para MiGUI
#[cfg(feature = "sdl2")]
pub mod backend_sdl2;

// Fuentes nativas en Rust (sin FFI)
pub mod font_native;

use std::str::FromStr;

// ============================================================================
// TIPOS BÁSICOS
// ============================================================================

/// Identificador único para widgets
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WidgetId(pub String);

impl WidgetId {
    pub fn new(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Rectángulo para layout
#[derive(Debug, Clone, Copy, Default)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
}

impl Rect {
    pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
        Self { x, y, w, h }
    }

    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.w && py >= self.y && py <= self.y + self.h
    }
}

/// Colores básicos
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Color {
    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }
    pub const BLACK: Color = Color::new(0, 0, 0, 255);
    pub const WHITE: Color = Color::new(255, 255, 255, 255);
    pub const RED: Color = Color::new(230, 41, 55, 255);
    pub const GREEN: Color = Color::new(117, 203, 100, 255);
    pub const BLUE: Color = Color::new(51, 122, 206, 255);
    pub const YELLOW: Color = Color::new(253, 249, 0, 255);
    pub const GRAY: Color = Color::new(128, 128, 128, 255);
    pub const BG: Color = Color::new(30, 30, 30, 255);
    pub const PANEL: Color = Color::new(50, 50, 50, 255);
    pub const BUTTON: Color = Color::new(70, 70, 70, 255);
    pub const BUTTON_HOVER: Color = Color::new(90, 90, 90, 255);
    pub const BUTTON_ACTIVE: Color = Color::new(110, 110, 110, 255);
    pub const BORDER: Color = Color::new(100, 100, 100, 255);
    pub const TEXT: Color = Color::new(240, 240, 240, 255);
    pub const ACCENT: Color = Color::new(51, 122, 206, 255);
}

impl FromStr for Color {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "rojo" | "red" => Ok(Color::RED),
            "verde" | "green" => Ok(Color::GREEN),
            "azul" | "blue" => Ok(Color::BLUE),
            "amarillo" | "yellow" => Ok(Color::YELLOW),
            "blanco" | "white" => Ok(Color::WHITE),
            "negro" | "black" => Ok(Color::BLACK),
            "gris" | "gray" => Ok(Color::GRAY),
            "panel" => Ok(Color::PANEL),
            "boton" | "button" => Ok(Color::BUTTON),
            "borde" | "border" => Ok(Color::BORDER),
            "texto" | "text" => Ok(Color::TEXT),
            "acento" | "accent" => Ok(Color::ACCENT),
            _ => Ok(Color::WHITE),
        }
    }
}

// ============================================================================
// EVENTOS
// ============================================================================

/// Eventos de entrada
#[derive(Debug, Clone)]
pub enum Event {
    MouseMove { x: f32, y: f32 },
    MouseDown { button: MouseButton, x: f32, y: f32 },
    MouseUp { button: MouseButton, x: f32, y: f32 },
    KeyDown { key: Key },
    KeyUp { key: Key },
    CharTyped { ch: char },
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MouseButton {
    Left,
    Right,
    Middle,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Key {
    Escape,
    Enter,
    Backspace,
    ArrowUp,
    ArrowDown,
    ArrowLeft,
    ArrowRight,
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,
    Num0,
    Num1,
    Num2,
    Num3,
    Num4,
    Num5,
    Num6,
    Num7,
    Num8,
    Num9,
}

// ============================================================================
// ESTADO DE WIDGETS
// ============================================================================

#[derive(Debug, Clone, Default)]
pub struct WidgetState {
    pub hovered: bool,
    pub active: bool,
    pub clicked: bool,
}

#[derive(Debug, Clone, Default)]
pub struct WindowState {
    pub x: f32,
    pub y: f32,
    pub dragging: bool,
    pub drag_offset_x: f32,
    pub drag_offset_y: f32,
    pub open: bool,
}

#[derive(Debug, Clone, Default)]
pub struct TextboxState {
    pub text: String,
    pub cursor_pos: usize,
    pub selected: bool,
}

/// Estado para ListBox - v0.5.2
#[derive(Debug, Clone)]
pub struct ListboxState {
    pub items: Vec<String>,
    pub selected: Option<usize>,
    pub scroll_offset: usize,
    pub item_height: f32,
}

impl Default for ListboxState {
    fn default() -> Self {
        Self {
            items: Vec::new(),
            selected: None,
            scroll_offset: 0,
            item_height: 25.0,
        }
    }
}

/// Estado para Layout - v0.5.2
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LayoutDir {
    Vertical,
    Horizontal,
}

/// Estado para contenedor Layout - v0.5.2
#[derive(Debug, Clone)]
pub struct LayoutState {
    pub direction: LayoutDir,
    pub spacing: f32,
    pub padding: f32,
    pub current_pos: f32,
}

impl Default for LayoutState {
    fn default() -> Self {
        Self {
            direction: LayoutDir::Vertical,
            spacing: 5.0,
            padding: 10.0,
            current_pos: 0.0,
        }
    }
}

// ============================================================================
// COMANDOS DE DIBUJO (para el backend)
// ============================================================================

/// Comandos que el backend debe ejecutar
#[derive(Debug, Clone)]
pub enum DrawCommand {
    Clear {
        color: Color,
    },
    DrawRect {
        rect: Rect,
        color: Color,
    },
    DrawText {
        text: String,
        x: f32,
        y: f32,
        size: u32,
        color: Color,
    },
    DrawLine {
        x1: f32,
        y1: f32,
        x2: f32,
        y2: f32,
        color: Color,
        thickness: f32,
    },
}

// ============================================================================
// MENU BAR SYSTEM (Dear ImGui style)
// ============================================================================

pub struct MenuItem {
    pub label: String,
    pub enabled: bool,
    pub shortcut: String,
    pub selected: bool,
    pub submenu: Option<Vec<MenuItem>>,
}

impl MenuItem {
    pub fn new(label: &str) -> Self {
        Self { label: label.into(), enabled: true, shortcut: String::new(), selected: false, submenu: None }
    }
    pub fn separator() -> Self {
        Self { label: "---".into(), enabled: false, shortcut: String::new(), selected: false, submenu: None }
    }
    pub fn with_submenu(mut self, items: Vec<MenuItem>) -> Self {
        self.submenu = Some(items); self
    }
    pub fn shortcut(mut self, s: &str) -> Self {
        self.shortcut = s.into(); self
    }
}

pub struct Menu {
    pub label: String,
    pub items: Vec<MenuItem>,
    pub open: bool,
    pub hovered_item: Option<usize>,
}

impl Menu {
    pub fn new(label: &str, items: Vec<MenuItem>) -> Self {
        Self { label: label.into(), items, open: false, hovered_item: None }
    }
}

pub struct MenuBar {
    pub menus: Vec<Menu>,
    pub active_menu: Option<usize>,
    pub selected_item: Option<(usize, usize)>,
}

impl MenuBar {
    pub fn new(menus: Vec<Menu>) -> Self {
        Self { menus, active_menu: None, selected_item: None }
    }
}

// ============================================================================
// BACKEND TRAIT
// ============================================================================

/// Trait para backends de renderizado
///
/// Permite conectar migui con diferentes sistemas gráficos:
/// - Raylib (rydit-gfx)
/// - Terminal (futuro)
/// - Web (futuro)
pub trait MiguiBackend {
    /// Limpiar pantalla con un color
    fn clear(&mut self, color: Color);

    /// Dibujar rectángulo
    fn draw_rect(&mut self, rect: Rect, color: Color);

    /// Dibujar texto
    fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: Color);

    /// Dibujar línea
    fn draw_line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, color: Color, thickness: f32);

    /// Ejecutar todos los comandos de dibujo de un frame
    fn render_commands(&mut self, commands: &[DrawCommand]) {
        for cmd in commands {
            match cmd {
                DrawCommand::Clear { color } => self.clear(*color),
                DrawCommand::DrawRect { rect, color } => self.draw_rect(*rect, *color),
                DrawCommand::DrawText {
                    text,
                    x,
                    y,
                    size,
                    color,
                } => {
                    self.draw_text(text, *x, *y, *size as f32, *color);
                }
                DrawCommand::DrawLine {
                    x1,
                    y1,
                    x2,
                    y2,
                    color,
                    thickness,
                } => {
                    self.draw_line(*x1, *y1, *x2, *y2, *color, *thickness);
                }
            }
        }
    }
}

// ============================================================================
// MIGUI - MAIN STRUCT
// ============================================================================

pub struct Migui {
    mouse_x: f32,
    mouse_y: f32,
    mouse_down: bool,
    mouse_pressed: bool,
    mouse_released: bool,

    pub widget_states: std::collections::HashMap<String, WidgetState>,
    pub window_states: std::collections::HashMap<String, WindowState>,
    pub textbox_states: std::collections::HashMap<String, TextboxState>,
    pub listbox_states: std::collections::HashMap<String, ListboxState>,
    pub layout_states: std::collections::HashMap<String, LayoutState>,

    draw_commands: Vec<DrawCommand>,
    frame_count: u64,
}

impl Migui {
    pub fn new() -> Self {
        Self {
            mouse_x: 0.0,
            mouse_y: 0.0,
            mouse_down: false,
            mouse_pressed: false,
            mouse_released: false,
            widget_states: std::collections::HashMap::new(),
            window_states: std::collections::HashMap::new(),
            textbox_states: std::collections::HashMap::new(),
            listbox_states: std::collections::HashMap::new(),
            layout_states: std::collections::HashMap::new(),
            draw_commands: Vec::new(),
            frame_count: 0,
        }
    }

    // ========================================================================
    // FRAME MANAGEMENT
    // ========================================================================

    pub fn begin_frame(&mut self) {
        self.draw_commands.clear();
        self.mouse_pressed = false;
        self.mouse_released = false;
        self.frame_count += 1;
    }

    pub fn end_frame(&mut self) {
        // Los comandos están listos para el backend
    }

    pub fn handle_event(&mut self, event: Event) {
        match event {
            Event::MouseMove { x, y } => {
                self.mouse_x = x;
                self.mouse_y = y;
            }
            Event::MouseDown {
                button: MouseButton::Left,
                x,
                y,
            } => {
                self.mouse_x = x;
                self.mouse_y = y;
                self.mouse_down = true;
                self.mouse_pressed = true;
            }
            Event::MouseUp {
                button: MouseButton::Left,
                x,
                y,
            } => {
                self.mouse_x = x;
                self.mouse_y = y;
                self.mouse_down = false;
                self.mouse_released = true;
            }
            Event::KeyDown { key } => {
                // Manejo de teclado para textbox
                if let Some(ts) = self.textbox_states.values_mut().find(|t| t.selected) {
                    if key == Key::Backspace && ts.cursor_pos > 0 {
                        ts.cursor_pos -= 1;
                        ts.text.remove(ts.cursor_pos);
                    }
                }
            }
            Event::CharTyped { ch } => {
                if let Some(ts) = self.textbox_states.values_mut().find(|t| t.selected) {
                    ts.text.insert(ts.cursor_pos, ch);
                    ts.cursor_pos += 1;
                }
            }
            _ => {}
        }
    }

    // ========================================================================
    // QUERY METHODS
    // ========================================================================

    pub fn mouse_x(&self) -> f32 {
        self.mouse_x
    }
    pub fn mouse_y(&self) -> f32 {
        self.mouse_y
    }
    pub fn mouse_position(&self) -> (f32, f32) {
        (self.mouse_x, self.mouse_y)
    }
    pub fn is_mouse_pressed(&self) -> bool {
        self.mouse_pressed
    }
    pub fn is_mouse_down(&self) -> bool {
        self.mouse_down
    }

    pub fn draw_commands(&self) -> &[DrawCommand] {
        &self.draw_commands
    }

    // ========================================================================
    // WIDGETS
    // ========================================================================

    /// Button - retorna true si fue clickeado en este frame
    pub fn button(&mut self, id: WidgetId, rect: Rect, label: &str) -> bool {
        let state = self.widget_states.entry(id.0).or_default();

        state.hovered = rect.contains(self.mouse_x, self.mouse_y);
        if state.hovered && self.mouse_pressed {
            state.active = true;
        }
        let clicked = state.hovered && state.active && self.mouse_released;
        if !self.mouse_down {
            state.active = false;
        }

        // Comando de dibujo
        let color = if state.active {
            Color::BUTTON_ACTIVE
        } else if state.hovered {
            Color::BUTTON_HOVER
        } else {
            Color::BUTTON
        };

        self.draw_commands
            .push(DrawCommand::DrawRect { rect, color });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });
        // ... más líneas del borde

        // Texto centrado
        self.draw_commands.push(DrawCommand::DrawText {
            text: label.to_string(),
            x: rect.x + (rect.w - label.len() as f32 * 8.0) / 2.0,
            y: rect.y + rect.h / 2.0 - 8.0,
            size: 16,
            color: Color::TEXT,
        });

        clicked
    }

    /// Label - texto estático
    pub fn label(&mut self, _id: WidgetId, text: &str, rect: Rect) {
        self.draw_commands.push(DrawCommand::DrawText {
            text: text.to_string(),
            x: rect.x,
            y: rect.y + rect.h / 4.0,
            size: 16,
            color: Color::TEXT,
        });
    }

    /// Checkbox - retorna true si cambió el estado
    pub fn checkbox(&mut self, id: WidgetId, label: &str, checked: &mut bool, rect: Rect) -> bool {
        let state = self.widget_states.entry(id.0.clone()).or_default();

        let cb_rect = Rect::new(rect.x + 4.0, rect.y + 4.0, rect.h - 8.0, rect.h - 8.0);
        state.hovered = cb_rect.contains(self.mouse_x, self.mouse_y);

        let clicked = state.hovered && self.mouse_pressed && !state.active;
        if self.mouse_pressed {
            state.active = true;
        }
        if self.mouse_released {
            state.active = false;
        }

        // Dibujar checkbox
        let bg = if state.hovered {
            Color::BUTTON_HOVER
        } else {
            Color::BUTTON
        };
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: cb_rect,
            color: bg,
        });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: cb_rect.x,
            y1: cb_rect.y,
            x2: cb_rect.x + cb_rect.w,
            y2: cb_rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });

        if *checked {
            let margin = 4.0;
            self.draw_commands.push(DrawCommand::DrawRect {
                rect: Rect::new(
                    cb_rect.x + margin,
                    cb_rect.y + margin,
                    cb_rect.w - margin * 2.0,
                    cb_rect.h - margin * 2.0,
                ),
                color: Color::ACCENT,
            });
        }

        // Label
        self.draw_commands.push(DrawCommand::DrawText {
            text: label.to_string(),
            x: rect.x + cb_rect.w + 8.0,
            y: rect.y + rect.h / 4.0,
            size: 16,
            color: Color::TEXT,
        });

        if clicked {
            *checked = !*checked;
        }
        clicked
    }

    /// Slider - retorna el valor actual
    pub fn slider(&mut self, id: WidgetId, value: f32, min: f32, max: f32, rect: Rect) -> f32 {
        let state = self.widget_states.entry(id.0).or_default();

        let track_h = 8.0f32;
        let track_y = rect.y + (rect.h - track_h) / 2.0;
        let range = max - min;
        let norm = if range > 0.0 {
            (value - min) / range
        } else {
            0.0
        };
        let knob_w = track_h;
        let knob_x = rect.x + norm * (rect.w - knob_w);

        state.hovered = rect.contains(self.mouse_x, self.mouse_y);
        let knob_hovered =
            Rect::new(knob_x, track_y, knob_w, track_h).contains(self.mouse_x, self.mouse_y);

        if (knob_hovered || state.active) && self.mouse_pressed {
            state.active = true;
        }

        let mut new_value = value;
        if state.active && self.mouse_x >= rect.x && self.mouse_x <= rect.x + rect.w {
            new_value = min + ((self.mouse_x - rect.x) / rect.w) * range;
            new_value = new_value.clamp(min, max);
        }
        if !self.mouse_down {
            state.active = false;
        }

        // Dibujar track
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: Rect::new(rect.x, track_y, rect.w, track_h),
            color: Color::BUTTON,
        });

        // Dibujar knob
        let knob_color = if knob_hovered || state.active {
            Color::BUTTON_HOVER
        } else {
            Color::BUTTON
        };
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: Rect::new(knob_x, track_y, knob_w, track_h),
            color: knob_color,
        });

        // Valor
        self.draw_commands.push(DrawCommand::DrawText {
            text: format!("{:.1}", new_value),
            x: rect.x + rect.w - 50.0,
            y: rect.y + rect.h / 4.0,
            size: 14,
            color: Color::TEXT,
        });

        new_value
    }

    /// Panel - contenedor visual
    pub fn panel(&mut self, _id: WidgetId, rect: Rect, color: Color) {
        self.draw_commands
            .push(DrawCommand::DrawRect { rect, color });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });
    }

    /// Textbox - retorna referencia al texto
    pub fn textbox(&mut self, id: WidgetId, rect: Rect) -> &str {
        let state = self.widget_states.entry(id.0.clone()).or_default();
        let ts = self.textbox_states.entry(id.0).or_default();

        state.hovered = rect.contains(self.mouse_x, self.mouse_y);
        if state.hovered && self.mouse_pressed {
            ts.selected = true;
        } else if self.mouse_pressed {
            ts.selected = false;
        }

        let bg = if ts.selected {
            Color::ACCENT
        } else if state.hovered {
            Color::BUTTON_HOVER
        } else {
            Color::BUTTON
        };

        self.draw_commands
            .push(DrawCommand::DrawRect { rect, color: bg });

        let display = if ts.selected {
            format!("{}_", ts.text)
        } else {
            ts.text.clone()
        };
        self.draw_commands.push(DrawCommand::DrawText {
            text: display,
            x: rect.x + 5.0,
            y: rect.y + rect.h / 4.0,
            size: 16,
            color: Color::TEXT,
        });

        &ts.text
    }

    pub fn set_textbox_text(&mut self, id: &str, text: String) {
        if let Some(ts) = self.textbox_states.get_mut(id) {
            ts.text = text;
        }
    }

    /// Window - ventana arrastrable, retorna true si está abierta
    pub fn window(&mut self, id: WidgetId, title: &str, rect: Rect, open: &mut bool) -> bool {
        if !*open {
            return false;
        }

        let ws = self
            .window_states
            .entry(id.0.clone())
            .or_insert_with(|| WindowState {
                x: rect.x,
                y: rect.y,
                ..Default::default()
            });

        if ws.dragging {
            if self.mouse_down {
                ws.x = self.mouse_x - ws.drag_offset_x;
                ws.y = self.mouse_y - ws.drag_offset_y;
            } else {
                ws.dragging = false;
            }
        }

        let header_h = 30.0f32;
        let header_rect = Rect::new(ws.x, ws.y, rect.w, header_h);
        let header_hovered = header_rect.contains(self.mouse_x, self.mouse_y);

        if header_hovered && self.mouse_pressed {
            ws.dragging = true;
            ws.drag_offset_x = self.mouse_x - ws.x;
            ws.drag_offset_y = self.mouse_y - ws.y;
        }

        // Cuerpo de ventana
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: Rect::new(ws.x, ws.y, rect.w, rect.h),
            color: Color::PANEL,
        });

        // Header
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: header_rect,
            color: Color::ACCENT,
        });

        // Título
        self.draw_commands.push(DrawCommand::DrawText {
            text: title.to_string(),
            x: ws.x + 10.0,
            y: ws.y + 7.0,
            size: 18,
            color: Color::WHITE,
        });

        // Botón cerrar
        let close_x = ws.x + rect.w - 25.0;
        let close_rect = Rect::new(close_x, ws.y + 5.0, 20.0, 20.0);
        let close_hovered = close_rect.contains(self.mouse_x, self.mouse_y);

        self.draw_commands.push(DrawCommand::DrawRect {
            rect: close_rect,
            color: if close_hovered {
                Color::RED
            } else {
                Color::new(128, 0, 0, 255)
            },
        });

        self.draw_commands.push(DrawCommand::DrawText {
            text: "X".to_string(),
            x: close_x + 5.0,
            y: ws.y + 3.0,
            size: 18,
            color: Color::WHITE,
        });

        if close_hovered && self.mouse_pressed {
            *open = false;
        }
        true
    }

    /// Dropdown - lista desplegable, retorna true si se seleccionó una opción
    /// API: dropdown(id, options[], selected_index, x, y, w, h) -> bool (cambió selección)
    pub fn dropdown(
        &mut self,
        id: WidgetId,
        options: &[&str],
        selected: &mut usize,
        rect: Rect,
    ) -> bool {
        let state = self.widget_states.entry(id.0.clone()).or_default();

        // Verificar si está abierto
        let is_open = state.active;

        // Hover detection
        state.hovered = rect.contains(self.mouse_x, self.mouse_y);

        // Click para abrir/cerrar
        if state.hovered && self.mouse_pressed {
            state.active = !state.active;
            return false;
        }

        // Si está abierto y click fuera, cerrar
        if is_open && self.mouse_pressed && !state.hovered {
            state.active = false;
            return false;
        }

        // Dibujar botón principal
        let btn_color = if state.hovered {
            Color::BUTTON_HOVER
        } else {
            Color::BUTTON
        };
        self.draw_commands.push(DrawCommand::DrawRect {
            rect,
            color: btn_color,
        });

        // Borde
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });

        // Texto seleccionado
        let selected_text = if *selected < options.len() {
            options[*selected]
        } else {
            "Seleccionar"
        };
        self.draw_commands.push(DrawCommand::DrawText {
            text: selected_text.to_string(),
            x: rect.x + 8.0,
            y: rect.y + rect.h / 4.0,
            size: 16,
            color: Color::TEXT,
        });

        // Flecha
        let arrow_x = rect.x + rect.w - 20.0;
        let arrow_y = rect.y + rect.h / 3.0;
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: arrow_x,
            y1: arrow_y,
            x2: arrow_x + 10.0,
            y2: arrow_y,
            color: Color::TEXT,
            thickness: 2.0,
        });

        let mut changed = false;

        // Si está abierto, dibujar lista desplegada
        if is_open {
            let item_h = 30.0f32;
            let list_h = options.len() as f32 * item_h;
            let list_rect = Rect::new(rect.x, rect.y + rect.h, rect.w, list_h);

            // Fondo de lista
            self.draw_commands.push(DrawCommand::DrawRect {
                rect: list_rect,
                color: Color::PANEL,
            });

            // Borde de lista
            self.draw_commands.push(DrawCommand::DrawLine {
                x1: list_rect.x,
                y1: list_rect.y,
                x2: list_rect.x + list_rect.w,
                y2: list_rect.y,
                color: Color::BORDER,
                thickness: 2.0,
            });

            // Items
            for (i, option) in options.iter().enumerate() {
                let item_rect =
                    Rect::new(rect.x, rect.y + rect.h + i as f32 * item_h, rect.w, item_h);
                let item_hovered = item_rect.contains(self.mouse_x, self.mouse_y);

                // Hover en item
                if item_hovered {
                    self.draw_commands.push(DrawCommand::DrawRect {
                        rect: item_rect,
                        color: Color::BUTTON_HOVER,
                    });
                }

                // Texto del item
                self.draw_commands.push(DrawCommand::DrawText {
                    text: option.to_string(),
                    x: rect.x + 8.0,
                    y: item_rect.y + item_rect.h / 4.0,
                    size: 16,
                    color: Color::TEXT,
                });

                // Click en item
                if item_hovered && self.mouse_pressed {
                    *selected = i;
                    changed = true;
                    state.active = false;
                }
            }
        }

        changed
    }

    /// Progress Bar - barra de progreso, vertical u horizontal
    /// API: progress_bar(id, value, min, max, x, y, w, h, vertical) -> ()
    pub fn progress_bar(
        &mut self,
        _id: WidgetId,
        value: f32,
        min: f32,
        max: f32,
        rect: Rect,
        vertical: bool,
    ) {
        // Normalizar valor
        let range = max - min;
        let norm = if range > 0.0 {
            (value - min) / range
        } else {
            0.0
        };
        let norm = norm.clamp(0.0, 1.0);

        // Fondo (track)
        self.draw_commands.push(DrawCommand::DrawRect {
            rect,
            color: Color::BUTTON,
        });

        // Borde
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });

        // Barra de progreso
        if vertical {
            // Vertical: llena de abajo hacia arriba
            let fill_h = norm * rect.h;
            let fill_rect = Rect::new(rect.x + 4.0, rect.y + rect.h - fill_h, rect.w - 8.0, fill_h);
            self.draw_commands.push(DrawCommand::DrawRect {
                rect: fill_rect,
                color: Color::ACCENT,
            });
        } else {
            // Horizontal: llena de izquierda a derecha
            let fill_w = norm * rect.w;
            let fill_rect = Rect::new(rect.x + 4.0, rect.y + 4.0, fill_w, rect.h - 8.0);
            self.draw_commands.push(DrawCommand::DrawRect {
                rect: fill_rect,
                color: Color::GREEN,
            });
        }

        // Texto de porcentaje
        let percent = (norm * 100.0) as i32;
        let text = format!("{}%", percent);
        self.draw_commands.push(DrawCommand::DrawText {
            text,
            x: rect.x + (rect.w - 40.0) / 2.0,
            y: rect.y + rect.h / 4.0,
            size: 14,
            color: Color::TEXT,
        });
    }

    /// Message box - retorna índice del botón presionado
    pub fn message_box(&mut self, title: &str, message: &str, buttons: &[&str], rect: Rect) -> i32 {
        // Fondo
        self.draw_commands.push(DrawCommand::DrawRect {
            rect,
            color: Color::PANEL,
        });

        // Título
        self.draw_commands.push(DrawCommand::DrawText {
            text: title.to_string(),
            x: rect.x + 10.0,
            y: rect.y + 10.0,
            size: 18,
            color: Color::ACCENT,
        });

        // Mensaje
        self.draw_commands.push(DrawCommand::DrawText {
            text: message.to_string(),
            x: rect.x + 10.0,
            y: rect.y + 35.0,
            size: 16,
            color: Color::TEXT,
        });

        // Botones
        let btn_w = 80.0f32;
        let btn_h = 35.0f32;
        let btn_y = rect.y + rect.h - btn_h - 10.0;
        let total_w = buttons.len() as f32 * (btn_w + 10.0) - 10.0;
        let mut btn_x = rect.x + (rect.w - total_w) / 2.0;

        for (i, btn_text) in buttons.iter().enumerate() {
            if self.button(
                WidgetId::new(&format!("msgbox_{}_{}", title, i)),
                Rect::new(btn_x, btn_y, btn_w, btn_h),
                btn_text,
            ) {
                return i as i32;
            }
            btn_x += btn_w + 10.0;
        }

        -1
    }

    // ========================================================================
    // LISTBOX - v0.5.2
    // ========================================================================

    /// ListBox - lista de items seleccionables
    /// Retorna el índice seleccionado o None si no hay selección
    pub fn listbox(&mut self, id: WidgetId, items: &[String], rect: Rect) -> Option<usize> {
        let state = self
            .listbox_states
            .entry(id.0.clone())
            .or_insert_with(|| ListboxState {
                items: items.to_vec(),
                selected: None,
                scroll_offset: 0,
                item_height: 25.0,
            });

        // Actualizar items si cambiaron
        if state.items.len() != items.len() {
            state.items = items.to_vec();
        }

        // Fondo
        self.draw_commands.push(DrawCommand::DrawRect {
            rect,
            color: Color::BUTTON,
        });

        // Borde
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x + rect.w,
            y1: rect.y,
            x2: rect.x + rect.w,
            y2: rect.y + rect.h,
            color: Color::BORDER,
            thickness: 2.0,
        });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x + rect.w,
            y1: rect.y + rect.h,
            x2: rect.x,
            y2: rect.y + rect.h,
            color: Color::BORDER,
            thickness: 2.0,
        });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: rect.x,
            y1: rect.y + rect.h,
            x2: rect.x,
            y2: rect.y,
            color: Color::BORDER,
            thickness: 2.0,
        });

        // Items visibles
        let visible_items = ((rect.h - 10.0) / state.item_height) as usize;
        let _max_scroll = state.items.len().saturating_sub(visible_items);

        for i in 0..visible_items.min(state.items.len().saturating_sub(state.scroll_offset)) {
            let item_idx = i + state.scroll_offset;
            let y = rect.y + 5.0 + (i as f32 * state.item_height);
            let item_rect = Rect::new(rect.x + 5.0, y, rect.w - 10.0, state.item_height - 2.0);

            let hovered = item_rect.contains(self.mouse_x, self.mouse_y);

            // Fondo del item
            let bg_color = if Some(item_idx) == state.selected {
                Color::ACCENT
            } else if hovered {
                Color::BUTTON_HOVER
            } else {
                Color::BUTTON
            };

            self.draw_commands.push(DrawCommand::DrawRect {
                rect: item_rect,
                color: bg_color,
            });

            // Texto del item
            self.draw_commands.push(DrawCommand::DrawText {
                text: state.items[item_idx].clone(),
                x: item_rect.x + 5.0,
                y: y + 5.0,
                size: 16,
                color: Color::TEXT,
            });

            // Click en item
            if hovered && self.mouse_pressed {
                state.selected = Some(item_idx);
            }
        }

        // Scroll simple con rueda del mouse (futuro: scrollbar)
        if rect.contains(self.mouse_x, self.mouse_y) && state.items.len() > visible_items {
            // Se puede agregar scroll con rueda aquí
        }

        state.selected
    }

    // ========================================================================
    // LAYOUTS - v0.5.2
    // ========================================================================

    /// Layout vertical - organiza widgets en columna
    pub fn begin_vertical(&mut self, id: WidgetId, rect: Rect, spacing: f32) {
        let state = self
            .layout_states
            .entry(id.0.clone())
            .or_insert_with(|| LayoutState {
                direction: LayoutDir::Vertical,
                spacing,
                padding: 5.0,
                current_pos: rect.y + 5.0,
            });

        state.current_pos = rect.y + state.padding;
        state.direction = LayoutDir::Vertical;
        state.spacing = spacing;

        // Fondo opcional (descomentar para debug)
        // self.draw_commands.push(DrawCommand::DrawRect { rect, color: Color::new(40, 40, 40, 255) });
    }

    /// Obtener posición Y para siguiente widget en layout vertical
    pub fn next_y(&mut self, id: WidgetId, height: f32) -> f32 {
        if let Some(state) = self.layout_states.get_mut(&id.0) {
            let y = state.current_pos;
            state.current_pos += height + state.spacing;
            y
        } else {
            0.0
        }
    }

    /// Finalizar layout vertical
    pub fn end_vertical(&mut self, _id: WidgetId) {
        // Limpieza opcional
    }

    /// Layout horizontal - organiza widgets en fila
    pub fn begin_horizontal(&mut self, id: WidgetId, rect: Rect, spacing: f32) {
        let state = self
            .layout_states
            .entry(id.0.clone())
            .or_insert_with(|| LayoutState {
                direction: LayoutDir::Horizontal,
                spacing,
                padding: 5.0,
                current_pos: rect.x + 5.0,
            });

        state.current_pos = rect.x + state.padding;
        state.direction = LayoutDir::Horizontal;
        state.spacing = spacing;
    }

    /// Obtener posición X para siguiente widget en layout horizontal
    pub fn next_x(&mut self, id: WidgetId, width: f32) -> f32 {
        if let Some(state) = self.layout_states.get_mut(&id.0) {
            let x = state.current_pos;
            state.current_pos += width + state.spacing;
            x
        } else {
            0.0
        }
    }

    /// Finalizar layout horizontal
    pub fn end_horizontal(&mut self, _id: WidgetId) {
        // Limpieza opcional
    }

    // ========================================================================
    // MENU BAR (Dear ImGui style)
    // ========================================================================

    /// Renderizar barra de menús
    pub fn menu_bar(&mut self, menu_bar: &mut MenuBar, x: f32, y: f32, total_width: f32) {
        let bar_h = 24.0;
        let menu_w = total_width / menu_bar.menus.len() as f32;

        self.draw_commands.push(DrawCommand::DrawRect {
            rect: Rect { x, y, w: total_width, h: bar_h },
            color: Color { r: 45, g: 45, b: 55, a: 255 },
        });

        let num_menus = menu_bar.menus.len();
        for mi in 0..num_menus {
            let mx = x + mi as f32 * menu_w;
            let hovered = self.mouse_x >= mx && self.mouse_x < mx + menu_w
                && self.mouse_y >= y && self.mouse_y < y + bar_h;

            let is_open = menu_bar.menus[mi].open;
            let label = menu_bar.menus[mi].label.clone();
            let bg = if is_open || hovered {
                Color { r: 60, g: 60, b: 80, a: 255 }
            } else {
                Color { r: 45, g: 45, b: 55, a: 255 }
            };
            self.draw_commands.push(DrawCommand::DrawRect {
                rect: Rect { x: mx, y, w: menu_w, h: bar_h },
                color: bg,
            });
            self.draw_commands.push(DrawCommand::DrawText {
                text: label,
                x: mx + 8.0,
                y: y + 4.0,
                size: 14,
                color: Color { r: 220, g: 220, b: 230, a: 255 },
            });

            if hovered && self.mouse_pressed {
                if menu_bar.active_menu == Some(mi) {
                    menu_bar.menus[mi].open = false;
                    menu_bar.active_menu = None;
                } else {
                    if let Some(prev) = menu_bar.active_menu {
                        menu_bar.menus[prev].open = false;
                    }
                    menu_bar.active_menu = Some(mi);
                    menu_bar.menus[mi].open = true;
                }
            }

            if menu_bar.menus[mi].open {
                let mw = menu_w * 1.5;
                self.render_menu_items(&mut menu_bar.menus[mi], mx, y + bar_h, mw);
            }
        }
    }

    /// Renderizar items de un menú desplegable
    fn render_menu_items(&mut self, menu: &mut Menu, x: f32, y: f32, w: f32) {
        let item_h = 22.0;
        let total_h = menu.items.len() as f32 * item_h;

        // Fondo del dropdown
        self.draw_commands.push(DrawCommand::DrawRect {
            rect: Rect { x, y, w, h: total_h },
            color: Color { r: 50, g: 50, b: 65, a: 255 },
        });

        // Borde
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: x, y1: y, x2: x + w, y2: y,
            color: Color { r: 70, g: 70, b: 90, a: 255 }, thickness: 1.0,
        });
        self.draw_commands.push(DrawCommand::DrawLine {
            x1: x, y1: y + total_h, x2: x + w, y2: y + total_h,
            color: Color { r: 70, g: 70, b: 90, a: 255 }, thickness: 1.0,
        });

        for (ii, item) in menu.items.iter().enumerate() {
            let iy = y + ii as f32 * item_h;
            let hovered = self.mouse_x >= x && self.mouse_x < x + w
                && self.mouse_y >= iy && self.mouse_y < iy + item_h;

            if item.label == "---" {
                // Separador
                self.draw_commands.push(DrawCommand::DrawLine {
                    x1: x + 4.0, y1: iy + item_h / 2.0,
                    x2: x + w - 4.0, y2: iy + item_h / 2.0,
                    color: Color { r: 70, g: 70, b: 90, a: 255 }, thickness: 1.0,
                });
            } else {
                // Item normal o hover
                let bg = if hovered {
                    Color { r: 70, g: 100, b: 180, a: 255 }
                } else {
                    Color { r: 50, g: 50, b: 65, a: 0 }
                };
                if bg.a > 0 {
                    self.draw_commands.push(DrawCommand::DrawRect {
                        rect: Rect { x: x + 2.0, y: iy + 1.0, w: w - 4.0, h: item_h - 2.0 },
                        color: bg,
                    });
                }

                // Texto
                let text_color = if item.enabled {
                    Color { r: 220, g: 220, b: 230, a: 255 }
                } else {
                    Color { r: 120, g: 120, b: 130, a: 255 }
                };
                self.draw_commands.push(DrawCommand::DrawText {
                    text: item.label.clone(),
                    x: x + 12.0,
                    y: iy + 4.0,
                    size: 13,
                    color: text_color,
                });

                // Shortcut
                if !item.shortcut.is_empty() {
                    self.draw_commands.push(DrawCommand::DrawText {
                        text: item.shortcut.clone(),
                        x: x + w - 60.0,
                        y: iy + 4.0,
                        size: 11,
                        color: Color { r: 150, g: 150, b: 160, a: 255 },
                    });
                }

                // Submenu indicator
                if item.submenu.is_some() {
                    self.draw_commands.push(DrawCommand::DrawText {
                        text: "".into(),
                        x: x + w - 16.0,
                        y: iy + 4.0,
                        size: 12,
                        color: Color { r: 180, g: 180, b: 190, a: 255 },
                    });
                }
            }
        }
    }
}

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

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_rect_contains() {
        let r = Rect::new(0.0, 0.0, 100.0, 50.0);
        assert!(r.contains(50.0, 25.0));
        assert!(!r.contains(150.0, 25.0));
    }

    #[test]
    fn test_button_click() {
        let mut gui = Migui::new();
        gui.begin_frame();
        gui.handle_event(Event::MouseMove { x: 50.0, y: 50.0 });
        gui.handle_event(Event::MouseDown {
            button: MouseButton::Left,
            x: 50.0,
            y: 50.0,
        });
        gui.handle_event(Event::MouseUp {
            button: MouseButton::Left,
            x: 50.0,
            y: 50.0,
        });

        let clicked = gui.button(
            WidgetId::new("btn"),
            Rect::new(0.0, 0.0, 100.0, 100.0),
            "Click",
        );
        assert!(clicked);
    }

    #[test]
    fn test_slider_value() {
        let mut gui = Migui::new();
        gui.begin_frame();
        gui.handle_event(Event::MouseMove { x: 150.0, y: 50.0 });
        gui.handle_event(Event::MouseDown {
            button: MouseButton::Left,
            x: 150.0,
            y: 50.0,
        });

        let value = gui.slider(
            WidgetId::new("sld"),
            0.5,
            0.0,
            1.0,
            Rect::new(100.0, 40.0, 200.0, 20.0),
        );
        assert!((0.0..=1.0).contains(&value));
    }

    #[test]
    fn test_dropdown_select() {
        let mut gui = Migui::new();
        let mut selected = 0usize;
        let options = ["Opción 1", "Opción 2", "Opción 3"];

        gui.begin_frame();
        // Renderizar dropdown cerrado
        let changed = gui.dropdown(
            WidgetId::new("dd"),
            &options,
            &mut selected,
            Rect::new(0.0, 0.0, 200.0, 40.0),
        );

        assert!(!changed);
        assert_eq!(selected, 0);
        // Debería haber comandos de dibujo (botón, borde, texto)
        assert!(gui.draw_commands().len() >= 3);
    }

    #[test]
    fn test_dropdown_closed() {
        let mut gui = Migui::new();
        let mut selected = 0usize;
        let options = ["Opción 1", "Opción 2", "Opción 3"];

        gui.begin_frame();
        // No hacer click, solo renderizar
        let changed = gui.dropdown(
            WidgetId::new("dd"),
            &options,
            &mut selected,
            Rect::new(0.0, 0.0, 200.0, 40.0),
        );

        assert!(!changed);
        assert_eq!(selected, 0);
    }

    #[test]
    fn test_progress_bar_horizontal() {
        let mut gui = Migui::new();
        gui.begin_frame();

        gui.progress_bar(
            WidgetId::new("pb"),
            50.0,
            0.0,
            100.0,
            Rect::new(0.0, 0.0, 200.0, 30.0),
            false,
        );

        // Verificar que se generaron comandos de dibujo
        assert!(!gui.draw_commands().is_empty());
    }

    #[test]
    fn test_progress_bar_vertical() {
        let mut gui = Migui::new();
        gui.begin_frame();

        gui.progress_bar(
            WidgetId::new("pb"),
            75.0,
            0.0,
            100.0,
            Rect::new(0.0, 0.0, 30.0, 200.0),
            true,
        );

        // Verificar que se generaron comandos de dibujo
        assert!(!gui.draw_commands().is_empty());
    }

    #[test]
    fn test_progress_bar_bounds() {
        let mut gui = Migui::new();
        gui.begin_frame();

        // Valor fuera de rango (debería clampear)
        gui.progress_bar(
            WidgetId::new("pb"),
            150.0,
            0.0,
            100.0,
            Rect::new(0.0, 0.0, 200.0, 30.0),
            false,
        );
        assert!(!gui.draw_commands().is_empty());

        gui.begin_frame();
        // Valor negativo
        gui.progress_bar(
            WidgetId::new("pb"),
            -10.0,
            0.0,
            100.0,
            Rect::new(0.0, 0.0, 200.0, 30.0),
            false,
        );
        assert!(!gui.draw_commands().is_empty());
    }
}