aprender-test-showcase 0.36.0

100% test coverage calculator showcase demonstrating Probar TUI + WASM testing
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
//! Numerical Keypad for TUI Calculator
//!
//! Probar: Visual feedback - Visual buttons make calculator state obvious
//!
//! This module provides an interactive numerical keypad that can be:
//! - Clicked with mouse (TUI mouse events)
//! - Highlighted when corresponding key is pressed
//! - Used for visual demonstration of calculator operation

/// A rectangle for layout/hit-testing (u16 coordinates, terminal cells).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
    /// X position of top-left corner
    pub x: u16,
    /// Y position of top-left corner
    pub y: u16,
    /// Width in terminal cells
    pub width: u16,
    /// Height in terminal cells
    pub height: u16,
}

impl Rect {
    /// Create a new rectangle with the given position and dimensions.
    #[must_use]
    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// A simple text buffer for TUI rendering (replaces ratatui::Buffer).
#[derive(Debug, Clone)]
pub struct TextBuffer {
    cells: Vec<char>,
    width: u16,
    height: u16,
}

impl TextBuffer {
    /// Create an empty buffer filled with spaces.
    #[must_use]
    pub fn empty(area: Rect) -> Self {
        let size = (area.width as usize) * (area.height as usize);
        Self {
            cells: vec![' '; size],
            width: area.width,
            height: area.height,
        }
    }

    /// Write a string at the given position.
    pub fn write_str(&mut self, x: u16, y: u16, s: &str) {
        let mut cx = x;
        for ch in s.chars() {
            if cx >= self.width || y >= self.height {
                break;
            }
            let idx = (y as usize) * (self.width as usize) + (cx as usize);
            if idx < self.cells.len() {
                self.cells[idx] = ch;
            }
            cx += 1;
        }
    }

    /// Get the full buffer content as a string.
    #[must_use]
    pub fn to_string_content(&self) -> String {
        self.cells.iter().collect()
    }

    /// Check if the buffer contains a substring.
    #[must_use]
    pub fn contains(&self, text: &str) -> bool {
        self.to_string_content().contains(text)
    }
}

/// A single keypad button
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeypadButton {
    /// The character/symbol on the button
    pub label: char,
    /// Whether the button is currently pressed/highlighted
    pub pressed: bool,
    /// The action this button performs
    pub action: ButtonAction,
}

/// Actions that keypad buttons can perform
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ButtonAction {
    /// Insert a digit (0-9)
    Digit(u8),
    /// Insert a decimal point
    Decimal,
    /// Insert an operator
    Operator(char),
    /// Evaluate the expression
    Equals,
    /// Clear the input
    Clear,
    /// Open parenthesis
    OpenParen,
    /// Close parenthesis
    CloseParen,
}

impl KeypadButton {
    /// Creates a new digit button
    #[must_use]
    pub fn digit(d: u8) -> Self {
        Self {
            label: char::from_digit(d as u32, 10).unwrap_or('?'),
            pressed: false,
            action: ButtonAction::Digit(d),
        }
    }

    /// Creates a new operator button
    #[must_use]
    pub fn operator(op: char) -> Self {
        Self {
            label: op,
            pressed: false,
            action: ButtonAction::Operator(op),
        }
    }

    /// Creates the decimal point button
    #[must_use]
    pub fn decimal() -> Self {
        Self {
            label: '.',
            pressed: false,
            action: ButtonAction::Decimal,
        }
    }

    /// Creates the equals button
    #[must_use]
    pub fn equals() -> Self {
        Self {
            label: '=',
            pressed: false,
            action: ButtonAction::Equals,
        }
    }

    /// Creates the clear button
    #[must_use]
    pub fn clear() -> Self {
        Self {
            label: 'C',
            pressed: false,
            action: ButtonAction::Clear,
        }
    }

    /// Creates the open parenthesis button
    #[must_use]
    pub fn open_paren() -> Self {
        Self {
            label: '(',
            pressed: false,
            action: ButtonAction::OpenParen,
        }
    }

    /// Creates the close parenthesis button
    #[must_use]
    pub fn close_paren() -> Self {
        Self {
            label: ')',
            pressed: false,
            action: ButtonAction::CloseParen,
        }
    }

    /// Sets the pressed state
    pub fn set_pressed(&mut self, pressed: bool) {
        self.pressed = pressed;
    }

    /// Returns the character to insert for this button
    #[must_use]
    pub fn to_char(&self) -> Option<char> {
        match self.action {
            ButtonAction::Digit(d) => char::from_digit(d as u32, 10),
            ButtonAction::Decimal => Some('.'),
            ButtonAction::Operator(op) => Some(op),
            ButtonAction::OpenParen => Some('('),
            ButtonAction::CloseParen => Some(')'),
            ButtonAction::Equals | ButtonAction::Clear => None,
        }
    }
}

/// The keypad layout - a 5x4 grid of buttons
/// ```text
/// [ 7 ] [ 8 ] [ 9 ] [ / ]
/// [ 4 ] [ 5 ] [ 6 ] [ * ]
/// [ 1 ] [ 2 ] [ 3 ] [ - ]
/// [ 0 ] [ . ] [ = ] [ + ]
/// [ C ] [ ( ] [ ) ] [ ^ ]
/// ```
#[derive(Debug, Clone)]
pub struct Keypad {
    /// Buttons in row-major order (5 rows x 4 cols)
    buttons: Vec<KeypadButton>,
    /// Number of columns
    cols: usize,
    /// Number of rows
    rows: usize,
}

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

impl Keypad {
    /// Creates a new standard calculator keypad
    #[must_use]
    pub fn new() -> Self {
        let buttons = vec![
            // Row 1: 7 8 9 /
            KeypadButton::digit(7),
            KeypadButton::digit(8),
            KeypadButton::digit(9),
            KeypadButton::operator('/'),
            // Row 2: 4 5 6 *
            KeypadButton::digit(4),
            KeypadButton::digit(5),
            KeypadButton::digit(6),
            KeypadButton::operator('*'),
            // Row 3: 1 2 3 -
            KeypadButton::digit(1),
            KeypadButton::digit(2),
            KeypadButton::digit(3),
            KeypadButton::operator('-'),
            // Row 4: 0 . = +
            KeypadButton::digit(0),
            KeypadButton::decimal(),
            KeypadButton::equals(),
            KeypadButton::operator('+'),
            // Row 5: C ( ) ^
            KeypadButton::clear(),
            KeypadButton::open_paren(),
            KeypadButton::close_paren(),
            KeypadButton::operator('^'),
        ];

        Self {
            buttons,
            cols: 4,
            rows: 5,
        }
    }

    /// Returns the number of buttons
    #[must_use]
    pub fn button_count(&self) -> usize {
        self.buttons.len()
    }

    /// Returns the grid dimensions (rows, cols)
    #[must_use]
    pub fn dimensions(&self) -> (usize, usize) {
        (self.rows, self.cols)
    }

    /// Gets a button by index
    #[must_use]
    pub fn get_button(&self, index: usize) -> Option<&KeypadButton> {
        self.buttons.get(index)
    }

    /// Gets a mutable button by index
    pub fn get_button_mut(&mut self, index: usize) -> Option<&mut KeypadButton> {
        self.buttons.get_mut(index)
    }

    /// Gets a button by row and column
    #[must_use]
    pub fn get_button_at(&self, row: usize, col: usize) -> Option<&KeypadButton> {
        if row < self.rows && col < self.cols {
            self.buttons.get(row * self.cols + col)
        } else {
            None
        }
    }

    /// Finds a button by its label character
    #[must_use]
    pub fn find_button_by_label(&self, label: char) -> Option<usize> {
        self.buttons.iter().position(|b| b.label == label)
    }

    /// Finds a button by the character it would insert
    #[must_use]
    pub fn find_button_by_char(&self, ch: char) -> Option<usize> {
        self.buttons.iter().position(|b| b.to_char() == Some(ch))
    }

    /// Sets a button as pressed by index
    pub fn press_button(&mut self, index: usize) {
        if let Some(btn) = self.buttons.get_mut(index) {
            btn.set_pressed(true);
        }
    }

    /// Releases all buttons
    pub fn release_all(&mut self) {
        for btn in &mut self.buttons {
            btn.set_pressed(false);
        }
    }

    /// Highlights the button corresponding to a character
    pub fn highlight_char(&mut self, ch: char) {
        self.release_all();
        if let Some(idx) = self.find_button_by_char(ch) {
            self.press_button(idx);
        }
    }

    /// Returns an iterator over all buttons
    pub fn buttons(&self) -> impl Iterator<Item = &KeypadButton> {
        self.buttons.iter()
    }

    /// Returns an iterator over buttons with their (row, col) positions
    pub fn buttons_with_positions(&self) -> impl Iterator<Item = ((usize, usize), &KeypadButton)> {
        self.buttons.iter().enumerate().map(move |(i, btn)| {
            let row = i / self.cols;
            let col = i % self.cols;
            ((row, col), btn)
        })
    }

    /// Converts a click position to button index
    #[must_use]
    pub fn hit_test(&self, area: Rect, x: u16, y: u16) -> Option<usize> {
        if x < area.x || y < area.y || x >= area.x + area.width || y >= area.y + area.height {
            return None;
        }

        let rel_x = x - area.x;
        let rel_y = y - area.y;

        // Account for border (1 char on each side)
        if rel_x == 0 || rel_y == 0 || rel_x >= area.width - 1 || rel_y >= area.height - 1 {
            return None;
        }

        let inner_x = rel_x - 1;
        let inner_y = rel_y - 1;

        let btn_width = (area.width - 2) / self.cols as u16;
        let btn_height = (area.height - 2) / self.rows as u16;

        if btn_width == 0 || btn_height == 0 {
            return None;
        }

        let col = (inner_x / btn_width) as usize;
        let row = (inner_y / btn_height) as usize;

        if row < self.rows && col < self.cols {
            Some(row * self.cols + col)
        } else {
            None
        }
    }
}

/// Keypad widget for rendering
#[derive(Debug)]
pub struct KeypadWidget<'a> {
    keypad: &'a Keypad,
}

impl<'a> KeypadWidget<'a> {
    /// Creates a new keypad widget
    #[must_use]
    pub fn new(keypad: &'a Keypad) -> Self {
        Self { keypad }
    }

    /// Render the keypad into a TextBuffer
    pub fn render(&self, area: Rect, buf: &mut TextBuffer) {
        // Draw border with title
        if area.width >= 2 && area.height >= 2 {
            buf.write_str(area.x + 1, area.y, " Keypad ");
        }

        // Calculate inner area
        let inner_x = area.x + 1;
        let inner_y = area.y + 1;
        let inner_w = area.width.saturating_sub(2);
        let inner_h = area.height.saturating_sub(2);

        if inner_w < 4 || inner_h < 5 {
            return; // Too small to render
        }

        let btn_width = inner_w / self.keypad.cols as u16;
        let btn_height = inner_h / self.keypad.rows as u16;

        for ((row, col), btn) in self.keypad.buttons_with_positions() {
            let x = inner_x + (col as u16 * btn_width);
            let y = inner_y + (row as u16 * btn_height);

            // Render button label centered
            if btn_width >= 3 {
                let label = format!("[{}]", btn.label);
                let label_x = x + (btn_width.saturating_sub(label.len() as u16)) / 2;
                let label_y = y + btn_height / 2;

                if label_y < inner_y + inner_h && label_x < inner_x + inner_w {
                    buf.write_str(label_x, label_y, &label);
                }
            }
        }
    }
}

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

    // ===== KeypadButton tests =====

    #[test]
    fn test_digit_button_creation() {
        for d in 0..=9 {
            let btn = KeypadButton::digit(d);
            assert_eq!(btn.label, char::from_digit(d as u32, 10).unwrap());
            assert!(!btn.pressed);
            assert_eq!(btn.action, ButtonAction::Digit(d));
        }
    }

    #[test]
    fn test_operator_button_creation() {
        for op in ['+', '-', '*', '/', '^'] {
            let btn = KeypadButton::operator(op);
            assert_eq!(btn.label, op);
            assert!(!btn.pressed);
            assert_eq!(btn.action, ButtonAction::Operator(op));
        }
    }

    #[test]
    fn test_decimal_button() {
        let btn = KeypadButton::decimal();
        assert_eq!(btn.label, '.');
        assert_eq!(btn.action, ButtonAction::Decimal);
    }

    #[test]
    fn test_equals_button() {
        let btn = KeypadButton::equals();
        assert_eq!(btn.label, '=');
        assert_eq!(btn.action, ButtonAction::Equals);
    }

    #[test]
    fn test_clear_button() {
        let btn = KeypadButton::clear();
        assert_eq!(btn.label, 'C');
        assert_eq!(btn.action, ButtonAction::Clear);
    }

    #[test]
    fn test_paren_buttons() {
        let open = KeypadButton::open_paren();
        assert_eq!(open.label, '(');
        assert_eq!(open.action, ButtonAction::OpenParen);

        let close = KeypadButton::close_paren();
        assert_eq!(close.label, ')');
        assert_eq!(close.action, ButtonAction::CloseParen);
    }

    #[test]
    fn test_button_pressed_state() {
        let mut btn = KeypadButton::digit(5);
        assert!(!btn.pressed);
        btn.set_pressed(true);
        assert!(btn.pressed);
        btn.set_pressed(false);
        assert!(!btn.pressed);
    }

    #[test]
    fn test_button_to_char() {
        assert_eq!(KeypadButton::digit(5).to_char(), Some('5'));
        assert_eq!(KeypadButton::decimal().to_char(), Some('.'));
        assert_eq!(KeypadButton::operator('+').to_char(), Some('+'));
        assert_eq!(KeypadButton::open_paren().to_char(), Some('('));
        assert_eq!(KeypadButton::close_paren().to_char(), Some(')'));
        assert_eq!(KeypadButton::equals().to_char(), None);
        assert_eq!(KeypadButton::clear().to_char(), None);
    }

    #[test]
    fn test_button_clone() {
        let btn = KeypadButton::digit(7);
        let cloned = btn.clone();
        assert_eq!(btn, cloned);
    }

    #[test]
    fn test_button_debug() {
        let btn = KeypadButton::digit(9);
        let debug = format!("{:?}", btn);
        assert!(debug.contains("KeypadButton"));
    }

    // ===== ButtonAction tests =====

    #[test]
    fn test_button_action_copy() {
        let action = ButtonAction::Digit(5);
        let copied = action;
        assert_eq!(action, copied);
    }

    #[test]
    fn test_button_action_debug() {
        let action = ButtonAction::Operator('+');
        let debug = format!("{:?}", action);
        assert!(debug.contains("Operator"));
    }

    // ===== Keypad tests =====

    #[test]
    fn test_keypad_new() {
        let keypad = Keypad::new();
        assert_eq!(keypad.button_count(), 20); // 5 rows x 4 cols
    }

    #[test]
    fn test_keypad_default() {
        let keypad = Keypad::default();
        assert_eq!(keypad.button_count(), 20);
    }

    #[test]
    fn test_keypad_dimensions() {
        let keypad = Keypad::new();
        assert_eq!(keypad.dimensions(), (5, 4));
    }

    #[test]
    fn test_keypad_get_button() {
        let keypad = Keypad::new();
        // First button should be 7
        let btn = keypad.get_button(0).unwrap();
        assert_eq!(btn.label, '7');
    }

    #[test]
    fn test_keypad_get_button_out_of_bounds() {
        let keypad = Keypad::new();
        assert!(keypad.get_button(100).is_none());
    }

    #[test]
    fn test_keypad_get_button_at() {
        let keypad = Keypad::new();
        // Row 0, Col 0 = 7
        assert_eq!(keypad.get_button_at(0, 0).unwrap().label, '7');
        // Row 0, Col 3 = /
        assert_eq!(keypad.get_button_at(0, 3).unwrap().label, '/');
        // Row 4, Col 0 = C
        assert_eq!(keypad.get_button_at(4, 0).unwrap().label, 'C');
    }

    #[test]
    fn test_keypad_get_button_at_out_of_bounds() {
        let keypad = Keypad::new();
        assert!(keypad.get_button_at(10, 10).is_none());
    }

    #[test]
    fn test_keypad_find_by_label() {
        let keypad = Keypad::new();
        assert_eq!(keypad.find_button_by_label('7'), Some(0));
        assert_eq!(keypad.find_button_by_label('0'), Some(12));
        assert_eq!(keypad.find_button_by_label('='), Some(14));
        assert_eq!(keypad.find_button_by_label('X'), None);
    }

    #[test]
    fn test_keypad_find_by_char() {
        let keypad = Keypad::new();
        assert_eq!(keypad.find_button_by_char('5'), Some(5));
        assert_eq!(keypad.find_button_by_char('+'), Some(15));
        assert_eq!(keypad.find_button_by_char('.'), Some(13));
    }

    #[test]
    fn test_keypad_press_button() {
        let mut keypad = Keypad::new();
        keypad.press_button(0);
        assert!(keypad.get_button(0).unwrap().pressed);
        assert!(!keypad.get_button(1).unwrap().pressed);
    }

    #[test]
    fn test_keypad_release_all() {
        let mut keypad = Keypad::new();
        keypad.press_button(0);
        keypad.press_button(5);
        keypad.release_all();
        for btn in keypad.buttons() {
            assert!(!btn.pressed);
        }
    }

    #[test]
    fn test_keypad_highlight_char() {
        let mut keypad = Keypad::new();
        keypad.highlight_char('5');
        assert!(keypad.get_button(5).unwrap().pressed);
        // Other buttons should not be pressed
        assert!(!keypad.get_button(0).unwrap().pressed);
    }

    #[test]
    fn test_keypad_buttons_iterator() {
        let keypad = Keypad::new();
        let count = keypad.buttons().count();
        assert_eq!(count, 20);
    }

    #[test]
    fn test_keypad_buttons_with_positions() {
        let keypad = Keypad::new();
        let positions: Vec<_> = keypad.buttons_with_positions().collect();
        assert_eq!(positions.len(), 20);
        assert_eq!(positions[0].0, (0, 0)); // First button at row 0, col 0
        assert_eq!(positions[19].0, (4, 3)); // Last button at row 4, col 3
    }

    #[test]
    fn test_keypad_hit_test_inside() {
        let keypad = Keypad::new();
        let area = Rect::new(0, 0, 22, 12); // Big enough for 4x5 grid

        // Click in center should hit a button
        let result = keypad.hit_test(area, 10, 5);
        assert!(result.is_some());
    }

    #[test]
    fn test_keypad_hit_test_outside() {
        let keypad = Keypad::new();
        let area = Rect::new(10, 10, 22, 12);

        // Click outside area
        assert!(keypad.hit_test(area, 0, 0).is_none());
        assert!(keypad.hit_test(area, 100, 100).is_none());
    }

    #[test]
    fn test_keypad_hit_test_border() {
        let keypad = Keypad::new();
        let area = Rect::new(0, 0, 22, 12);

        // Click on border (first row/col)
        assert!(keypad.hit_test(area, 0, 0).is_none());
    }

    #[test]
    fn test_keypad_get_button_mut() {
        let mut keypad = Keypad::new();
        if let Some(btn) = keypad.get_button_mut(0) {
            btn.set_pressed(true);
        }
        assert!(keypad.get_button(0).unwrap().pressed);
    }

    #[test]
    fn test_keypad_clone() {
        let keypad = Keypad::new();
        let cloned = keypad.clone();
        assert_eq!(keypad.button_count(), cloned.button_count());
    }

    #[test]
    fn test_keypad_debug() {
        let keypad = Keypad::new();
        let debug = format!("{:?}", keypad);
        assert!(debug.contains("Keypad"));
    }

    // ===== Keypad layout verification =====

    #[test]
    fn test_keypad_row_1() {
        let keypad = Keypad::new();
        assert_eq!(keypad.get_button_at(0, 0).unwrap().label, '7');
        assert_eq!(keypad.get_button_at(0, 1).unwrap().label, '8');
        assert_eq!(keypad.get_button_at(0, 2).unwrap().label, '9');
        assert_eq!(keypad.get_button_at(0, 3).unwrap().label, '/');
    }

    #[test]
    fn test_keypad_row_2() {
        let keypad = Keypad::new();
        assert_eq!(keypad.get_button_at(1, 0).unwrap().label, '4');
        assert_eq!(keypad.get_button_at(1, 1).unwrap().label, '5');
        assert_eq!(keypad.get_button_at(1, 2).unwrap().label, '6');
        assert_eq!(keypad.get_button_at(1, 3).unwrap().label, '*');
    }

    #[test]
    fn test_keypad_row_3() {
        let keypad = Keypad::new();
        assert_eq!(keypad.get_button_at(2, 0).unwrap().label, '1');
        assert_eq!(keypad.get_button_at(2, 1).unwrap().label, '2');
        assert_eq!(keypad.get_button_at(2, 2).unwrap().label, '3');
        assert_eq!(keypad.get_button_at(2, 3).unwrap().label, '-');
    }

    #[test]
    fn test_keypad_row_4() {
        let keypad = Keypad::new();
        assert_eq!(keypad.get_button_at(3, 0).unwrap().label, '0');
        assert_eq!(keypad.get_button_at(3, 1).unwrap().label, '.');
        assert_eq!(keypad.get_button_at(3, 2).unwrap().label, '=');
        assert_eq!(keypad.get_button_at(3, 3).unwrap().label, '+');
    }

    #[test]
    fn test_keypad_row_5() {
        let keypad = Keypad::new();
        assert_eq!(keypad.get_button_at(4, 0).unwrap().label, 'C');
        assert_eq!(keypad.get_button_at(4, 1).unwrap().label, '(');
        assert_eq!(keypad.get_button_at(4, 2).unwrap().label, ')');
        assert_eq!(keypad.get_button_at(4, 3).unwrap().label, '^');
    }

    // ===== KeypadWidget tests =====

    #[test]
    fn test_keypad_widget_new() {
        let keypad = Keypad::new();
        let widget = KeypadWidget::new(&keypad);
        // Just verify it creates without panic
        let _ = widget;
    }

    #[test]
    fn test_keypad_widget_render() {
        let keypad = Keypad::new();
        let widget = KeypadWidget::new(&keypad);
        let area = Rect::new(0, 0, 22, 12);
        let mut buf = TextBuffer::empty(area);

        widget.render(area, &mut buf);

        let content = buf.to_string_content();
        assert!(content.contains("Keypad"));
        assert!(content.contains("[7]"));
        assert!(content.contains("[+]"));
    }

    #[test]
    fn test_keypad_widget_render_small() {
        let keypad = Keypad::new();
        let widget = KeypadWidget::new(&keypad);
        let area = Rect::new(0, 0, 5, 5); // Too small
        let mut buf = TextBuffer::empty(area);

        // Should not panic, just render border
        widget.render(area, &mut buf);
    }

    #[test]
    fn test_keypad_widget_render_pressed() {
        let mut keypad = Keypad::new();
        keypad.press_button(0); // Press '7'
        let widget = KeypadWidget::new(&keypad);
        let area = Rect::new(0, 0, 22, 12);
        let mut buf = TextBuffer::empty(area);

        widget.render(area, &mut buf);
        // Pressed button should still render
        let content = buf.to_string_content();
        assert!(content.contains("[7]"));
    }

    // ===== Property-based tests =====

    #[test]
    fn prop_all_digits_have_buttons() {
        let keypad = Keypad::new();
        for d in 0..=9 {
            let ch = char::from_digit(d, 10).unwrap();
            assert!(
                keypad.find_button_by_char(ch).is_some(),
                "Missing button for digit {d}"
            );
        }
    }

    #[test]
    fn prop_all_operators_have_buttons() {
        let keypad = Keypad::new();
        for op in ['+', '-', '*', '/', '^'] {
            assert!(
                keypad.find_button_by_char(op).is_some(),
                "Missing button for operator {op}"
            );
        }
    }

    #[test]
    fn prop_button_char_roundtrip() {
        let keypad = Keypad::new();
        for btn in keypad.buttons() {
            if let Some(ch) = btn.to_char() {
                // Should be able to find it back
                let found = keypad.find_button_by_char(ch);
                assert!(found.is_some(), "Cannot find button for char '{ch}'");
            }
        }
    }

    #[test]
    fn prop_press_release_idempotent() {
        let mut keypad = Keypad::new();
        keypad.press_button(5);
        keypad.press_button(5); // Press again
        assert!(keypad.get_button(5).unwrap().pressed);

        keypad.release_all();
        keypad.release_all(); // Release again
        for btn in keypad.buttons() {
            assert!(!btn.pressed);
        }
    }

    #[test]
    fn prop_highlight_releases_others() {
        let mut keypad = Keypad::new();
        keypad.press_button(0);
        keypad.press_button(5);
        keypad.press_button(10);

        keypad.highlight_char('1'); // Should release all and press only '1'

        let pressed_count = keypad.buttons().filter(|b| b.pressed).count();
        assert_eq!(pressed_count, 1);
    }
}