envision 0.16.0

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
//! A threshold-based alert panel for metric monitoring.
//!
//! [`AlertPanel`] displays a grid of metrics, each with configurable
//! thresholds that determine alert states (OK, Warning, Critical, Unknown).
//! Each metric card shows a state indicator, current value with units, and
//! an optional sparkline history. The title bar summarizes aggregate counts.
//!
//! State is stored in [`AlertPanelState`], updated via [`AlertPanelMessage`],
//! and produces [`AlertPanelOutput`].
//!
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     AlertPanel, AlertPanelState, AlertMetric, AlertThreshold, AlertState,
//!     Component,
//! };
//!
//! let metrics = vec![
//!     AlertMetric::new("cpu", "CPU Usage", AlertThreshold::new(70.0, 90.0))
//!         .with_units("%")
//!         .with_value(45.0),
//!     AlertMetric::new("mem", "Memory", AlertThreshold::new(80.0, 95.0))
//!         .with_units("%")
//!         .with_value(82.0),
//! ];
//!
//! let state = AlertPanelState::new()
//!     .with_metrics(metrics)
//!     .with_columns(2);
//!
//! assert_eq!(state.metrics().len(), 2);
//! assert_eq!(state.ok_count(), 1);
//! assert_eq!(state.warning_count(), 1);
//! ```

mod metric;
mod render;

pub use metric::{AlertMetric, AlertState, AlertThreshold};

use std::marker::PhantomData;

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

/// Messages that can be sent to an AlertPanel.
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     AlertPanel, AlertPanelState, AlertPanelMessage, AlertMetric, AlertThreshold,
///     Component,
/// };
///
/// let mut state = AlertPanelState::new().with_metrics(vec![
///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)).with_value(50.0),
/// ]);
/// let output = state.update(AlertPanelMessage::UpdateMetric {
///     id: "cpu".into(),
///     value: 80.0,
/// });
/// assert!(output.is_some());
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum AlertPanelMessage {
    /// Update a metric's value by id.
    UpdateMetric {
        /// The metric identifier.
        id: String,
        /// The new value.
        value: f64,
    },
    /// Add a new metric.
    AddMetric(AlertMetric),
    /// Remove a metric by id.
    RemoveMetric(String),
    /// Replace all metrics.
    SetMetrics(Vec<AlertMetric>),
    /// Select the next metric.
    SelectNext,
    /// Select the previous metric.
    SelectPrev,
    /// Navigate up in the grid.
    SelectUp,
    /// Navigate down in the grid.
    SelectDown,
    /// Set the number of grid columns.
    SetColumns(usize),
    /// Confirm selection of the current metric.
    Select,
}

/// Output messages from an AlertPanel.
///
/// # Example
///
/// ```rust
/// use envision::component::{AlertPanelOutput, AlertState};
///
/// let output = AlertPanelOutput::StateChanged {
///     id: "cpu".into(),
///     old: AlertState::Ok,
///     new_state: AlertState::Warning,
/// };
/// assert!(matches!(output, AlertPanelOutput::StateChanged { .. }));
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum AlertPanelOutput {
    /// A metric changed alert state.
    StateChanged {
        /// The metric identifier.
        id: String,
        /// The previous alert state.
        old: AlertState,
        /// The new alert state.
        new_state: AlertState,
    },
    /// A metric was selected (Enter pressed).
    MetricSelected(String),
}

/// State for the AlertPanel component.
///
/// Contains the metrics, layout configuration, and navigation state.
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     AlertPanelState, AlertMetric, AlertThreshold,
/// };
///
/// let state = AlertPanelState::new()
///     .with_metrics(vec![
///         AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
///             .with_value(45.0),
///     ])
///     .with_columns(2)
///     .with_title("Alerts");
///
/// assert_eq!(state.metrics().len(), 1);
/// assert_eq!(state.ok_count(), 1);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct AlertPanelState {
    /// The alert metrics.
    metrics: Vec<AlertMetric>,
    /// Number of columns in the grid layout.
    columns: usize,
    /// Currently selected metric index.
    selected: Option<usize>,
    /// Optional title.
    title: Option<String>,
    /// Whether to show sparkline history.
    show_sparklines: bool,
    /// Whether to show threshold values.
    show_thresholds: bool,
}

impl Default for AlertPanelState {
    fn default() -> Self {
        Self {
            metrics: Vec::new(),
            columns: 2,
            selected: None,
            title: None,
            show_sparklines: true,
            show_thresholds: false,
        }
    }
}

impl AlertPanelState {
    /// Creates a new empty alert panel state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new();
    /// assert!(state.metrics().is_empty());
    /// assert_eq!(state.columns(), 2);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the initial metrics (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// assert_eq!(state.metrics().len(), 1);
    /// ```
    pub fn with_metrics(mut self, metrics: Vec<AlertMetric>) -> Self {
        self.selected = if metrics.is_empty() { None } else { Some(0) };
        self.metrics = metrics;
        self
    }

    /// Sets the number of grid columns (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_columns(3);
    /// assert_eq!(state.columns(), 3);
    /// ```
    pub fn with_columns(mut self, columns: usize) -> Self {
        self.columns = columns.max(1);
        self
    }

    /// Sets the title (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_title("System Alerts");
    /// assert_eq!(state.title(), Some("System Alerts"));
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets whether to show sparklines (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_show_sparklines(false);
    /// assert!(!state.show_sparklines());
    /// ```
    pub fn with_show_sparklines(mut self, show: bool) -> Self {
        self.show_sparklines = show;
        self
    }

    /// Sets whether to show threshold values (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_show_thresholds(true);
    /// assert!(state.show_thresholds());
    /// ```
    pub fn with_show_thresholds(mut self, show: bool) -> Self {
        self.show_thresholds = show;
        self
    }

    // ---- Accessors ----

    /// Returns the metrics.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// assert_eq!(state.metrics().len(), 1);
    /// ```
    pub fn metrics(&self) -> &[AlertMetric] {
        &self.metrics
    }

    /// Returns a mutable reference to the alert metrics.
    ///
    /// This is safe because metrics are simple data containers.
    /// Selection state is index-based and unaffected by value mutation.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let mut state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    ///         .with_value(50.0),
    /// ]);
    /// state.metrics_mut()[0].update_value(85.0);
    /// assert_eq!(state.metrics()[0].value(), 85.0);
    /// ```
    pub fn metrics_mut(&mut self) -> &mut Vec<AlertMetric> {
        &mut self.metrics
    }

    /// Returns the number of grid columns.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_columns(4);
    /// assert_eq!(state.columns(), 4);
    /// ```
    pub fn columns(&self) -> usize {
        self.columns
    }

    /// Returns the selected metric index.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// assert_eq!(state.selected(), Some(0));
    /// ```
    pub fn selected(&self) -> Option<usize> {
        self.selected
    }

    /// Returns the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new().with_title("Alerts");
    /// assert_eq!(state.title(), Some("Alerts"));
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

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

    /// Returns whether sparklines are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new();
    /// assert!(state.show_sparklines());
    /// ```
    pub fn show_sparklines(&self) -> bool {
        self.show_sparklines
    }

    /// Returns whether threshold values are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new();
    /// assert!(!state.show_thresholds());
    /// ```
    pub fn show_thresholds(&self) -> bool {
        self.show_thresholds
    }

    /// Sets whether sparklines are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let mut state = AlertPanelState::new();
    /// state.set_show_sparklines(false);
    /// assert!(!state.show_sparklines());
    /// ```
    pub fn set_show_sparklines(&mut self, show: bool) {
        self.show_sparklines = show;
    }

    /// Sets whether threshold values are shown.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let mut state = AlertPanelState::new();
    /// state.set_show_thresholds(true);
    /// assert!(state.show_thresholds());
    /// ```
    pub fn set_show_thresholds(&mut self, show: bool) {
        self.show_thresholds = show;
    }

    /// Adds a metric to the panel.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let mut state = AlertPanelState::new();
    /// state.add_metric(
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    /// );
    /// assert_eq!(state.metrics().len(), 1);
    /// assert_eq!(state.selected(), Some(0));
    /// ```
    pub fn add_metric(&mut self, metric: AlertMetric) {
        self.metrics.push(metric);
        if self.selected.is_none() {
            self.selected = Some(0);
        }
    }

    /// Updates a metric's value by id.
    ///
    /// Returns `Some((old_state, new_state))` if the alert state changed,
    /// or `None` if the state did not change or the metric was not found.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold, AlertState};
    ///
    /// let mut state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    ///         .with_value(50.0),
    /// ]);
    /// let result = state.update_metric("cpu", 80.0);
    /// assert_eq!(result, Some((AlertState::Ok, AlertState::Warning)));
    /// ```
    pub fn update_metric(&mut self, id: &str, value: f64) -> Option<(AlertState, AlertState)> {
        if let Some(metric) = self.metrics.iter_mut().find(|m| m.id == id) {
            let old_state = metric.state.clone();
            metric.update_value(value);
            let new_state = metric.state.clone();
            if old_state != new_state {
                Some((old_state, new_state))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Returns a reference to a metric by id.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// assert!(state.metric_by_id("cpu").is_some());
    /// assert!(state.metric_by_id("unknown").is_none());
    /// ```
    pub fn metric_by_id(&self, id: &str) -> Option<&AlertMetric> {
        self.metrics.iter().find(|m| m.id == id)
    }

    /// Returns the count of metrics in OK state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    ///         .with_value(50.0),
    ///     AlertMetric::new("mem", "Memory", AlertThreshold::new(80.0, 95.0))
    ///         .with_value(30.0),
    /// ]);
    /// assert_eq!(state.ok_count(), 2);
    /// ```
    pub fn ok_count(&self) -> usize {
        self.metrics
            .iter()
            .filter(|m| m.state == AlertState::Ok)
            .count()
    }

    /// Returns the count of metrics in Warning state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    ///         .with_value(80.0),
    /// ]);
    /// assert_eq!(state.warning_count(), 1);
    /// ```
    pub fn warning_count(&self) -> usize {
        self.metrics
            .iter()
            .filter(|m| m.state == AlertState::Warning)
            .count()
    }

    /// Returns the count of metrics in Critical state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0))
    ///         .with_value(95.0),
    /// ]);
    /// assert_eq!(state.critical_count(), 1);
    /// ```
    pub fn critical_count(&self) -> usize {
        self.metrics
            .iter()
            .filter(|m| m.state == AlertState::Critical)
            .count()
    }

    /// Returns the count of metrics in Unknown state.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::AlertPanelState;
    ///
    /// let state = AlertPanelState::new();
    /// assert_eq!(state.unknown_count(), 0);
    /// ```
    pub fn unknown_count(&self) -> usize {
        self.metrics
            .iter()
            .filter(|m| m.state == AlertState::Unknown)
            .count()
    }

    /// Returns a reference to the currently selected metric.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{AlertPanelState, AlertMetric, AlertThreshold};
    ///
    /// let state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// assert_eq!(state.selected_metric().unwrap().id(), "cpu");
    /// ```
    pub fn selected_metric(&self) -> Option<&AlertMetric> {
        self.metrics.get(self.selected?)
    }

    /// Returns the number of rows in the grid.
    ///
    /// The row count is derived from the number of metrics and the configured
    /// column count (rounded up so partial rows still count).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use envision::component::{AlertMetric, AlertPanelState, AlertThreshold};
    ///
    /// let state = AlertPanelState::new()
    ///     .with_metrics(vec![
    ///         AlertMetric::new("a", "A", AlertThreshold::new(70.0, 90.0)),
    ///         AlertMetric::new("b", "B", AlertThreshold::new(70.0, 90.0)),
    ///         AlertMetric::new("c", "C", AlertThreshold::new(70.0, 90.0)),
    ///     ])
    ///     .with_columns(2);
    /// assert_eq!(state.rows(), 2);
    /// ```
    pub fn rows(&self) -> usize {
        if self.metrics.is_empty() {
            0
        } else {
            self.metrics.len().div_ceil(self.columns)
        }
    }

    /// Builds the title string with aggregate state counts.
    pub(crate) fn title_with_counts(&self) -> String {
        let base = self.title.as_deref().unwrap_or("Alerts");
        let ok = self.ok_count();
        let warn = self.warning_count();
        let crit = self.critical_count();
        let unknown = self.unknown_count();

        let mut parts = Vec::new();
        if ok > 0 {
            parts.push(format!("{} OK", ok));
        }
        if warn > 0 {
            parts.push(format!("{} WARN", warn));
        }
        if crit > 0 {
            parts.push(format!("{} CRIT", crit));
        }
        if unknown > 0 {
            parts.push(format!("{} UNKNOWN", unknown));
        }

        if parts.is_empty() {
            base.to_string()
        } else {
            format!("{} ({})", base, parts.join(", "))
        }
    }

    // ---- Instance methods ----

    /// Updates the state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{
    ///     AlertPanelState, AlertPanelMessage, AlertPanelOutput,
    ///     AlertMetric, AlertThreshold,
    /// };
    ///
    /// let mut state = AlertPanelState::new().with_metrics(vec![
    ///     AlertMetric::new("cpu", "CPU", AlertThreshold::new(70.0, 90.0)),
    /// ]);
    /// let output = state.update(AlertPanelMessage::Select);
    /// assert_eq!(output, Some(AlertPanelOutput::MetricSelected("cpu".into())));
    /// ```
    pub fn update(&mut self, msg: AlertPanelMessage) -> Option<AlertPanelOutput> {
        AlertPanel::update(self, msg)
    }
}

/// A threshold-based alert panel component.
///
/// Displays metrics in a grid layout with visual state indicators,
/// sparkline history, and keyboard navigation.
///
/// # Key Bindings
///
/// - `Left` / `h` -- Move selection left
/// - `Right` / `l` -- Move selection right
/// - `Up` / `k` -- Move selection up
/// - `Down` / `j` -- Move selection down
/// - `Enter` -- Confirm selection
pub struct AlertPanel(PhantomData<()>);

impl Component for AlertPanel {
    type State = AlertPanelState;
    type Message = AlertPanelMessage;
    type Output = AlertPanelOutput;

    fn init() -> Self::State {
        AlertPanelState::default()
    }

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

        let key = event.as_key()?;

        match key.code {
            Key::Left | Key::Char('h') => Some(AlertPanelMessage::SelectPrev),
            Key::Right | Key::Char('l') => Some(AlertPanelMessage::SelectNext),
            Key::Up | Key::Char('k') => Some(AlertPanelMessage::SelectUp),
            Key::Down | Key::Char('j') => Some(AlertPanelMessage::SelectDown),
            Key::Enter => Some(AlertPanelMessage::Select),
            _ => None,
        }
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            AlertPanelMessage::UpdateMetric { id, value } => {
                if let Some(metric) = state.metrics.iter_mut().find(|m| m.id == id) {
                    let old_state = metric.state.clone();
                    metric.update_value(value);
                    let new_state = metric.state.clone();
                    if old_state != new_state {
                        return Some(AlertPanelOutput::StateChanged {
                            id,
                            old: old_state,
                            new_state,
                        });
                    }
                }
                None
            }
            AlertPanelMessage::AddMetric(metric) => {
                state.add_metric(metric);
                None
            }
            AlertPanelMessage::RemoveMetric(id) => {
                state.metrics.retain(|m| m.id != id);
                if state.metrics.is_empty() {
                    state.selected = None;
                } else if let Some(sel) = state.selected {
                    if sel >= state.metrics.len() {
                        state.selected = Some(state.metrics.len() - 1);
                    }
                }
                None
            }
            AlertPanelMessage::SetMetrics(metrics) => {
                state.selected = if metrics.is_empty() { None } else { Some(0) };
                state.metrics = metrics;
                None
            }
            AlertPanelMessage::SelectNext => {
                if state.metrics.is_empty() {
                    return None;
                }
                let current = state.selected.unwrap_or(0);
                let cols = state.columns;
                let current_col = current % cols;
                if current_col < cols - 1 && current + 1 < state.metrics.len() {
                    let new_index = current + 1;
                    state.selected = Some(new_index);
                    Some(AlertPanelOutput::MetricSelected(
                        state.metrics[new_index].id.clone(),
                    ))
                } else {
                    None
                }
            }
            AlertPanelMessage::SelectPrev => {
                if state.metrics.is_empty() {
                    return None;
                }
                let current = state.selected.unwrap_or(0);
                let current_col = current % state.columns;
                if current_col > 0 {
                    let new_index = current - 1;
                    state.selected = Some(new_index);
                    Some(AlertPanelOutput::MetricSelected(
                        state.metrics[new_index].id.clone(),
                    ))
                } else {
                    None
                }
            }
            AlertPanelMessage::SelectUp => {
                if state.metrics.is_empty() {
                    return None;
                }
                let current = state.selected.unwrap_or(0);
                let cols = state.columns;
                let current_row = current / cols;
                if current_row > 0 {
                    let new_index = (current_row - 1) * cols + (current % cols);
                    if new_index < state.metrics.len() {
                        state.selected = Some(new_index);
                        return Some(AlertPanelOutput::MetricSelected(
                            state.metrics[new_index].id.clone(),
                        ));
                    }
                }
                None
            }
            AlertPanelMessage::SelectDown => {
                if state.metrics.is_empty() {
                    return None;
                }
                let current = state.selected.unwrap_or(0);
                let cols = state.columns;
                let new_index = (current / cols + 1) * cols + (current % cols);
                if new_index < state.metrics.len() {
                    state.selected = Some(new_index);
                    Some(AlertPanelOutput::MetricSelected(
                        state.metrics[new_index].id.clone(),
                    ))
                } else {
                    None
                }
            }
            AlertPanelMessage::SetColumns(columns) => {
                state.columns = columns.max(1);
                None
            }
            AlertPanelMessage::Select => state
                .selected_metric()
                .map(|metric| AlertPanelOutput::MetricSelected(metric.id.clone())),
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        render::render_alert_panel(
            state,
            ctx.frame,
            ctx.area,
            ctx.theme,
            ctx.focused,
            ctx.disabled,
        );
    }
}

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