envision 0.15.1

A ratatui framework for collaborative TUI development with headless testing 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
//! A month-view calendar component with date selection and event markers.
//!
//! [`Calendar`] provides a navigable month view that displays a grid of days
//! with keyboard navigation, date selection, and colored event markers.
//! State is stored in [`CalendarState`], updated via [`CalendarMessage`],
//! and produces [`CalendarOutput`].
//!
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Calendar, CalendarMessage, CalendarOutput, CalendarState, Component};
//! use ratatui::style::Color;
//!
//! // Create a calendar for March 2026
//! let mut state = CalendarState::new(2026, 3)
//!     .with_selected_day(20)
//!     .with_title("My Calendar");
//!
//! assert_eq!(state.year(), 2026);
//! assert_eq!(state.month(), 3);
//! assert_eq!(state.selected_day(), Some(20));
//! assert_eq!(state.month_name(), "March");
//!
//! // Navigate to next month
//! let output = Calendar::update(&mut state, CalendarMessage::NextMonth);
//! assert_eq!(output, Some(CalendarOutput::MonthChanged(2026, 4)));
//! assert_eq!(state.month(), 4);
//!
//! // Add an event marker
//! Calendar::update(&mut state, CalendarMessage::AddEvent {
//!     year: 2026,
//!     month: 4,
//!     day: 15,
//!     color: Color::Green,
//! });
//! assert!(state.has_event(2026, 4, 15));
//! ```

use std::collections::HashMap;

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph};

use super::{Component, EventContext, RenderContext};
use crate::input::{Event, Key};

// ---------------------------------------------------------------------------
// Date math helpers (private)
// ---------------------------------------------------------------------------

/// Returns whether `year` is a leap year.
fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Returns the number of days in the given month (1-12) of `year`.
///
/// Returns 30 for out-of-range months as a safe fallback.
fn days_in_month(year: i32, month: u32) -> u32 {
    match month {
        1 => 31,
        2 => {
            if is_leap_year(year) {
                29
            } else {
                28
            }
        }
        3 => 31,
        4 => 30,
        5 => 31,
        6 => 30,
        7 => 31,
        8 => 31,
        9 => 30,
        10 => 31,
        11 => 30,
        12 => 31,
        _ => 30, // Safe fallback for out-of-range months
    }
}

/// Returns the day of week for the given date, 0 = Sunday .. 6 = Saturday.
///
/// Uses Tomohiko Sakamoto's algorithm.
fn day_of_week(year: i32, month: u32, day: u32) -> u32 {
    const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    let y = if month < 3 { year - 1 } else { year };
    let result = (y + y / 4 - y / 100 + y / 400 + T[(month - 1) as usize] + day as i32) % 7;
    ((result + 7) % 7) as u32
}

/// Returns the month name for the given month (1-12).
fn month_name_for(month: u32) -> &'static str {
    match month {
        1 => "January",
        2 => "February",
        3 => "March",
        4 => "April",
        5 => "May",
        6 => "June",
        7 => "July",
        8 => "August",
        9 => "September",
        10 => "October",
        11 => "November",
        12 => "December",
        _ => "Unknown",
    }
}

// ---------------------------------------------------------------------------
// CalendarMessage
// ---------------------------------------------------------------------------

/// Messages that can be sent to a Calendar.
#[derive(Clone, Debug, PartialEq)]
pub enum CalendarMessage {
    /// Advance to the next month.
    NextMonth,
    /// Go back to the previous month.
    PrevMonth,
    /// Advance to the next year.
    NextYear,
    /// Go back to the previous year.
    PrevYear,
    /// Select a specific day in the current month.
    SelectDay(u32),
    /// Move selection to the previous day (wraps across months).
    SelectPrevDay,
    /// Move selection to the next day (wraps across months).
    SelectNextDay,
    /// Move selection up one week (wraps across months).
    SelectPrevWeek,
    /// Move selection down one week (wraps across months).
    SelectNextWeek,
    /// Confirm the current selection (emits DateSelected).
    ConfirmSelection,
    /// Navigate to today's month/year (requires explicit date).
    Today {
        /// The current year.
        year: i32,
        /// The current month (1-12).
        month: u32,
        /// The current day.
        day: u32,
    },
    /// Navigate to a specific month.
    SetDate {
        /// Target year.
        year: i32,
        /// Target month (1-12).
        month: u32,
    },
    /// Add an event marker for a specific date.
    AddEvent {
        /// Event year.
        year: i32,
        /// Event month (1-12).
        month: u32,
        /// Event day.
        day: u32,
        /// Marker color.
        color: Color,
    },
    /// Remove all event markers.
    ClearEvents,
}

// ---------------------------------------------------------------------------
// CalendarOutput
// ---------------------------------------------------------------------------

/// Output messages from a Calendar.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CalendarOutput {
    /// A date was confirmed (Enter/Space pressed on selected day).
    DateSelected(i32, u32, u32),
    /// The displayed month changed via navigation.
    MonthChanged(i32, u32),
}

// ---------------------------------------------------------------------------
// CalendarState
// ---------------------------------------------------------------------------

/// State for a Calendar component.
///
/// # Example
///
/// ```rust
/// use envision::component::CalendarState;
///
/// let state = CalendarState::new(2026, 3)
///     .with_selected_day(15)
///     .with_title("Events");
/// assert_eq!(state.year(), 2026);
/// assert_eq!(state.month(), 3);
/// assert_eq!(state.selected_day(), Some(15));
/// assert_eq!(state.month_name(), "March");
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct CalendarState {
    year: i32,
    month: u32,
    selected_day: Option<u32>,
    events: HashMap<(i32, u32, u32), Color>,
    title: Option<String>,
}

impl Default for CalendarState {
    /// Returns a calendar for January 1970 with no selected day, no events,
    /// and no title.
    ///
    /// This mirrors the conventional Unix epoch default used by date libraries
    /// like `chrono`'s `NaiveDate::default()`. For meaningful UI, construct
    /// state with [`CalendarState::new`] for the desired year and month.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::default();
    /// assert_eq!(state.year(), 1970);
    /// assert_eq!(state.month(), 1);
    /// assert_eq!(state.selected_day(), None);
    /// ```
    fn default() -> Self {
        Self::new(1970, 1)
    }
}

impl CalendarState {
    /// Creates a new calendar for the given year and month.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3);
    /// assert_eq!(state.year(), 2026);
    /// assert_eq!(state.month(), 3);
    /// assert_eq!(state.selected_day(), None);
    /// ```
    pub fn new(year: i32, month: u32) -> Self {
        Self {
            year,
            month,
            selected_day: None,
            events: HashMap::new(),
            title: None,
        }
    }

    /// Sets the initially selected day (builder method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3).with_selected_day(15);
    /// assert_eq!(state.selected_day(), Some(15));
    /// ```
    pub fn with_selected_day(mut self, day: u32) -> Self {
        self.selected_day = Some(day);
        self
    }

    /// Sets the title (builder method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3).with_title("My Calendar");
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Adds an event marker (builder method).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    /// use ratatui::style::Color;
    ///
    /// let state = CalendarState::new(2026, 3)
    ///     .with_event(2026, 3, 15, Color::Green);
    /// assert!(state.has_event(2026, 3, 15));
    /// ```
    pub fn with_event(mut self, year: i32, month: u32, day: u32, color: Color) -> Self {
        self.events.insert((year, month, day), color);
        self
    }

    /// Returns the current year.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3);
    /// assert_eq!(state.year(), 2026);
    /// ```
    pub fn year(&self) -> i32 {
        self.year
    }

    /// Returns the current month (1-12).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3);
    /// assert_eq!(state.month(), 3);
    /// ```
    pub fn month(&self) -> u32 {
        self.month
    }

    /// Returns the currently selected day, if any.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3).with_selected_day(20);
    /// assert_eq!(state.selected_day(), Some(20));
    /// ```
    pub fn selected_day(&self) -> Option<u32> {
        self.selected_day
    }

    /// Returns the title, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 3).with_title("My Calendar");
    /// assert_eq!(state.title(), Some("My Calendar"));
    ///
    /// let state2 = CalendarState::new(2026, 3);
    /// assert_eq!(state2.title(), None);
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let mut state = CalendarState::new(2026, 3);
    /// state.set_title("Events");
    /// assert_eq!(state.title(), Some("Events"));
    /// ```
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = Some(title.into());
    }

    /// Sets the selected day.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let mut state = CalendarState::new(2026, 3);
    /// state.set_selected_day(Some(15));
    /// assert_eq!(state.selected_day(), Some(15));
    /// state.set_selected_day(None);
    /// assert_eq!(state.selected_day(), None);
    /// ```
    pub fn set_selected_day(&mut self, day: Option<u32>) {
        self.selected_day = day;
    }

    /// Returns the name of the current month.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    ///
    /// let state = CalendarState::new(2026, 1);
    /// assert_eq!(state.month_name(), "January");
    /// ```
    pub fn month_name(&self) -> &str {
        month_name_for(self.month)
    }

    /// Adds an event marker for the given date with the given color.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    /// use ratatui::style::Color;
    ///
    /// let mut state = CalendarState::new(2026, 3);
    /// state.add_event(2026, 3, 15, Color::Red);
    /// assert!(state.has_event(2026, 3, 15));
    /// ```
    pub fn add_event(&mut self, year: i32, month: u32, day: u32, color: Color) {
        self.events.insert((year, month, day), color);
    }

    /// Removes all event markers.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    /// use ratatui::style::Color;
    ///
    /// let mut state = CalendarState::new(2026, 3);
    /// state.add_event(2026, 3, 15, Color::Red);
    /// state.clear_events();
    /// assert!(!state.has_event(2026, 3, 15));
    /// ```
    pub fn clear_events(&mut self) {
        self.events.clear();
    }

    /// Returns whether there is an event marker for the given date.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::CalendarState;
    /// use ratatui::style::Color;
    ///
    /// let state = CalendarState::new(2026, 3)
    ///     .with_event(2026, 3, 15, Color::Green);
    /// assert!(state.has_event(2026, 3, 15));
    /// assert!(!state.has_event(2026, 3, 16));
    /// ```
    pub fn has_event(&self, year: i32, month: u32, day: u32) -> bool {
        self.events.contains_key(&(year, month, day))
    }

    /// Updates the calendar state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CalendarMessage, CalendarOutput, CalendarState};
    ///
    /// let mut state = CalendarState::new(2026, 3);
    /// let output = state.update(CalendarMessage::NextMonth);
    /// assert_eq!(output, Some(CalendarOutput::MonthChanged(2026, 4)));
    /// ```
    pub fn update(&mut self, msg: CalendarMessage) -> Option<CalendarOutput> {
        Calendar::update(self, msg)
    }
}

// ---------------------------------------------------------------------------
// Calendar component
// ---------------------------------------------------------------------------

/// A month-view calendar component with date selection and event markers.
///
/// The calendar renders a standard month grid with day-of-week headers,
/// supports keyboard navigation between days and months, and can display
/// colored event markers on specific dates.
///
/// # Keyboard Navigation
///
/// When focused:
/// - Left / h: previous day (wraps to previous month)
/// - Right / l: next day (wraps to next month)
/// - Up / k: same day minus 7 (previous week)
/// - Down / j: same day plus 7 (next week)
/// - PageUp: previous month
/// - PageDown: next month
/// - Enter / Space: confirm selection (emits `DateSelected`)
///
/// # Visual Layout
///
/// ```text
/// ┌─ March 2026 ─────────────────┐
/// │ Su  Mo  Tu  We  Th  Fr  Sa   │
/// │  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                   │
/// │ ◀ PgUp          PgDn ▶      │
/// └──────────────────────────────┘
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{Calendar, CalendarMessage, CalendarState, Component};
///
/// let mut state = CalendarState::new(2026, 3).with_selected_day(1);
///
/// // Navigate forward
/// let output = Calendar::update(&mut state, CalendarMessage::NextMonth);
/// assert_eq!(state.month(), 4);
/// ```
pub struct Calendar;

impl Calendar {
    /// Navigates to the previous month, adjusting year if needed.
    fn go_prev_month(state: &mut CalendarState) {
        if state.month == 1 {
            state.month = 12;
            state.year -= 1;
        } else {
            state.month -= 1;
        }
        // Clamp selected day to new month
        if let Some(day) = state.selected_day {
            let max_day = days_in_month(state.year, state.month);
            if day > max_day {
                state.selected_day = Some(max_day);
            }
        }
    }

    /// Navigates to the next month, adjusting year if needed.
    fn go_next_month(state: &mut CalendarState) {
        if state.month == 12 {
            state.month = 1;
            state.year += 1;
        } else {
            state.month += 1;
        }
        // Clamp selected day to new month
        if let Some(day) = state.selected_day {
            let max_day = days_in_month(state.year, state.month);
            if day > max_day {
                state.selected_day = Some(max_day);
            }
        }
    }
}

impl Component for Calendar {
    type State = CalendarState;
    type Message = CalendarMessage;
    type Output = CalendarOutput;

    fn init() -> Self::State {
        CalendarState::new(2026, 1)
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            CalendarMessage::NextMonth => {
                Self::go_next_month(state);
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::PrevMonth => {
                Self::go_prev_month(state);
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::NextYear => {
                state.year += 1;
                // Clamp selected day (e.g. Feb 29 -> Feb 28 on non-leap year)
                if let Some(day) = state.selected_day {
                    let max_day = days_in_month(state.year, state.month);
                    if day > max_day {
                        state.selected_day = Some(max_day);
                    }
                }
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::PrevYear => {
                state.year -= 1;
                if let Some(day) = state.selected_day {
                    let max_day = days_in_month(state.year, state.month);
                    if day > max_day {
                        state.selected_day = Some(max_day);
                    }
                }
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::SelectDay(day) => {
                let max_day = days_in_month(state.year, state.month);
                let clamped = day.min(max_day).max(1);
                state.selected_day = Some(clamped);
                None
            }
            CalendarMessage::SelectPrevDay => {
                let current_day = state.selected_day.unwrap_or(1);
                if current_day <= 1 {
                    Self::go_prev_month(state);
                    let last_day = days_in_month(state.year, state.month);
                    state.selected_day = Some(last_day);
                    Some(CalendarOutput::MonthChanged(state.year, state.month))
                } else {
                    state.selected_day = Some(current_day - 1);
                    None
                }
            }
            CalendarMessage::SelectNextDay => {
                let current_day = state.selected_day.unwrap_or(1);
                let max_day = days_in_month(state.year, state.month);
                if current_day >= max_day {
                    Self::go_next_month(state);
                    state.selected_day = Some(1);
                    Some(CalendarOutput::MonthChanged(state.year, state.month))
                } else {
                    state.selected_day = Some(current_day + 1);
                    None
                }
            }
            CalendarMessage::SelectPrevWeek => {
                let current_day = state.selected_day.unwrap_or(1);
                if current_day <= 7 {
                    let days_back = 7 - current_day;
                    Self::go_prev_month(state);
                    let prev_max = days_in_month(state.year, state.month);
                    state.selected_day = Some(prev_max - days_back);
                    Some(CalendarOutput::MonthChanged(state.year, state.month))
                } else {
                    state.selected_day = Some(current_day - 7);
                    None
                }
            }
            CalendarMessage::SelectNextWeek => {
                let current_day = state.selected_day.unwrap_or(1);
                let max_day = days_in_month(state.year, state.month);
                if current_day + 7 > max_day {
                    let overflow = current_day + 7 - max_day;
                    Self::go_next_month(state);
                    state.selected_day = Some(overflow);
                    Some(CalendarOutput::MonthChanged(state.year, state.month))
                } else {
                    state.selected_day = Some(current_day + 7);
                    None
                }
            }
            CalendarMessage::ConfirmSelection => {
                if let Some(day) = state.selected_day {
                    Some(CalendarOutput::DateSelected(state.year, state.month, day))
                } else {
                    None
                }
            }
            CalendarMessage::Today { year, month, day } => {
                state.year = year;
                state.month = month;
                let max_day = days_in_month(year, month);
                state.selected_day = Some(day.min(max_day).max(1));
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::SetDate { year, month } => {
                state.year = year;
                state.month = month;
                if let Some(day) = state.selected_day {
                    let max_day = days_in_month(year, month);
                    if day > max_day {
                        state.selected_day = Some(max_day);
                    }
                }
                Some(CalendarOutput::MonthChanged(state.year, state.month))
            }
            CalendarMessage::AddEvent {
                year,
                month,
                day,
                color,
            } => {
                state.events.insert((year, month, day), color);
                None
            }
            CalendarMessage::ClearEvents => {
                state.events.clear();
                None
            }
        }
    }

    fn handle_event(
        _state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        if !ctx.focused || ctx.disabled {
            return None;
        }

        if let Some(key) = event.as_key() {
            match key.code {
                Key::Left | Key::Char('h') => Some(CalendarMessage::SelectPrevDay),
                Key::Right | Key::Char('l') => Some(CalendarMessage::SelectNextDay),
                Key::Up | Key::Char('k') => Some(CalendarMessage::SelectPrevWeek),
                Key::Down | Key::Char('j') => Some(CalendarMessage::SelectNextWeek),
                Key::PageUp => Some(CalendarMessage::PrevMonth),
                Key::PageDown => Some(CalendarMessage::NextMonth),
                Key::Enter | Key::Char(' ') => Some(CalendarMessage::ConfirmSelection),
                _ => None,
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if ctx.area.height == 0 || ctx.area.width == 0 {
            return;
        }

        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
                    "Calendar".to_string(),
                ))
                .with_id("calendar")
                .with_focus(ctx.focused)
                .with_disabled(ctx.disabled),
            );
        });

        // Determine styles
        let border_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if ctx.focused {
            ctx.theme.focused_border_style()
        } else {
            ctx.theme.border_style()
        };

        let normal_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else {
            ctx.theme.normal_style()
        };

        let header_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if ctx.focused {
            ctx.theme.focused_bold_style()
        } else {
            Style::default()
                .fg(ctx.theme.foreground)
                .add_modifier(Modifier::BOLD)
        };

        let day_header_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else {
            Style::default()
                .fg(ctx.theme.primary)
                .add_modifier(Modifier::BOLD)
        };

        // Build the title
        let title_text = if let Some(ref title) = state.title {
            format!("{} - {} {}", title, state.month_name(), state.year)
        } else {
            format!("{} {}", state.month_name(), state.year)
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style)
            .title(Span::styled(format!(" {title_text} "), header_style));

        let inner = block.inner(ctx.area);
        ctx.frame.render_widget(block, ctx.area);

        if inner.height == 0 || inner.width == 0 {
            return;
        }

        // Day-of-week headers
        let dow_line = Line::from(vec![Span::styled(
            " Su  Mo  Tu  We  Th  Fr  Sa",
            day_header_style,
        )]);

        let mut lines: Vec<Line<'_>> = Vec::new();
        lines.push(dow_line);

        // Compute the calendar grid
        let first_dow = day_of_week(state.year, state.month, 1);
        let total_days = days_in_month(state.year, state.month);

        let selected_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else {
            ctx.theme.selected_highlight_style(ctx.focused)
        };

        // Build week rows
        let mut day = 1u32;

        for week in 0..6 {
            if day > total_days {
                break;
            }

            let mut spans: Vec<Span<'_>> = Vec::new();

            for dow in 0..7u32 {
                if week == 0 && dow < first_dow {
                    // Empty cell before month starts
                    spans.push(Span::styled("    ", normal_style));
                } else if day > total_days {
                    // Empty cell after month ends
                    spans.push(Span::styled("    ", normal_style));
                } else {
                    let is_selected = state.selected_day == Some(day);
                    let has_event = state.events.contains_key(&(state.year, state.month, day));
                    let event_color = state.events.get(&(state.year, state.month, day));

                    let day_str = if has_event {
                        format!("{day:>3}\u{2022}")
                    } else {
                        format!("{day:>3} ")
                    };

                    let style = if is_selected {
                        selected_style
                    } else if let Some(&color) = event_color {
                        Style::default().fg(color)
                    } else {
                        normal_style
                    };

                    spans.push(Span::styled(day_str, style));
                    day += 1;
                }
            }

            lines.push(Line::from(spans));
        }

        // Navigation hint footer
        let footer_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else {
            ctx.theme.placeholder_style()
        };
        lines.push(Line::from(vec![Span::styled(
            " \u{25c0} PgUp          PgDn \u{25b6}",
            footer_style,
        )]));

        let paragraph = Paragraph::new(lines).style(normal_style);
        ctx.frame.render_widget(paragraph, inner);
    }
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod view_tests;