envision 0.17.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
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
//! A triple-value gauge for displaying actual/request/limit measurements.
//!
//! `ResourceGauge` renders a single horizontal bar with three regions showing
//! how actual usage relates to a requested amount and an upper limit. This
//! is useful for CPU/memory monitoring, quota tracking, or any scenario
//! where a value has both a "normal operating range" (request) and a
//! "hard ceiling" (limit).
//!
//! # Visual
//!
//! ```text
//! CPU  [████████▓▓▓▓░░░░░░░░] 350m / 500m / 1000m
//!       actual   ↑request      ↑limit
//! ```
//!
//! - Filled (`█`): actual usage, colored by health (green/yellow/red)
//! - Request zone (`▓`): headroom between actual and request
//! - Empty (`░`): unused capacity up to the limit
//!
//! # Examples
//!
//! ```
//! use envision::component::{ResourceGaugeState, ResourceValues};
//!
//! let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 350.0, request: 500.0, limit: 1000.0 })
//!     .with_label("CPU")
//!     .with_units("m");
//!
//! assert_eq!(state.actual(), 350.0);
//! assert_eq!(state.request(), 500.0);
//! assert_eq!(state.limit(), 1000.0);
//! assert!(!state.is_over_request());
//! assert!(!state.is_near_limit());
//! ```

use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::component::Component;
use crate::component::context::{EventContext, RenderContext};
use crate::input::Event;
use crate::theme::Theme;

mod values;

pub use values::ResourceValues;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Orientation of the gauge bar.
///
/// # Examples
///
/// ```
/// use envision::component::resource_gauge::GaugeOrientation;
///
/// let o = GaugeOrientation::default();
/// assert_eq!(o, GaugeOrientation::Horizontal);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub enum GaugeOrientation {
    /// Bar fills left to right.
    #[default]
    Horizontal,
    /// Bar fills bottom to top.
    Vertical,
}

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

/// State for the ResourceGauge component.
///
/// Holds actual, request, and limit values plus display configuration.
///
/// # Examples
///
/// ```
/// use envision::component::{ResourceGaugeState, ResourceValues};
///
/// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 256.0, request: 384.0, limit: 512.0 })
///     .with_label("Memory")
///     .with_units("Mi");
///
/// assert_eq!(state.label(), Some("Memory"));
/// assert_eq!(state.units(), Some("Mi"));
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct ResourceGaugeState {
    actual: f64,
    request: f64,
    limit: f64,
    label: Option<String>,
    units: Option<String>,
    title: Option<String>,
    show_legend: bool,
    orientation: GaugeOrientation,
    disabled: bool,
}

impl Default for ResourceGaugeState {
    fn default() -> Self {
        Self {
            actual: 0.0,
            request: 0.0,
            limit: 0.0,
            label: None,
            units: None,
            title: None,
            show_legend: true,
            orientation: GaugeOrientation::default(),
            disabled: false,
        }
    }
}

impl ResourceGaugeState {
    // -- Builders --

    /// Sets all three values from a named struct in a single call.
    ///
    /// The struct-literal form (`ResourceValues { actual, request, limit }`)
    /// names each field at construction, matching the intent of the removed
    /// positional `new(a, r, l)` without its transposition hazard.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues {
    ///     actual: 250.0,
    ///     request: 500.0,
    ///     limit: 1000.0,
    /// });
    /// assert_eq!(state.actual(), 250.0);
    /// ```
    pub fn with_values(mut self, values: ResourceValues) -> Self {
        self.actual = values.actual;
        self.request = values.request;
        self.limit = values.limit;
        self
    }

    /// Sets the actual (in-use) value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ResourceGaugeState;
    ///
    /// let state = ResourceGaugeState::default().with_actual(250.0);
    /// assert_eq!(state.actual(), 250.0);
    /// ```
    pub fn with_actual(mut self, actual: f64) -> Self {
        self.actual = actual;
        self
    }

    /// Sets the requested value (e.g., K8s pod resource request).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ResourceGaugeState;
    ///
    /// let state = ResourceGaugeState::default().with_request(500.0);
    /// assert_eq!(state.request(), 500.0);
    /// ```
    pub fn with_request(mut self, request: f64) -> Self {
        self.request = request;
        self
    }

    /// Sets the hard limit (e.g., K8s pod resource limit).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::ResourceGaugeState;
    ///
    /// let state = ResourceGaugeState::default().with_limit(1000.0);
    /// assert_eq!(state.limit(), 1000.0);
    /// ```
    pub fn with_limit(mut self, limit: f64) -> Self {
        self.limit = limit;
        self
    }

    /// Sets the label displayed before the bar.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 }).with_label("CPU");
    /// assert_eq!(state.label(), Some("CPU"));
    /// ```
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the units suffix for legend text (e.g., "m", "Mi", "GB").
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 }).with_units("Mi");
    /// assert_eq!(state.units(), Some("Mi"));
    /// ```
    pub fn with_units(mut self, units: impl Into<String>) -> Self {
        self.units = Some(units.into());
        self
    }

    /// Sets the title displayed in the border.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 }).with_title("Resource");
    /// assert_eq!(state.title(), Some("Resource"));
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Controls whether the legend text is shown.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 }).with_show_legend(false);
    /// assert!(!state.show_legend());
    /// ```
    pub fn with_show_legend(mut self, show: bool) -> Self {
        self.show_legend = show;
        self
    }

    /// Sets the gauge orientation.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, GaugeOrientation, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 })
    ///     .with_orientation(GaugeOrientation::Vertical);
    /// assert_eq!(state.orientation(), &GaugeOrientation::Vertical);
    /// ```
    pub fn with_orientation(mut self, orientation: GaugeOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Sets the disabled state.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 }).with_disabled(true);
    /// assert!(state.is_disabled());
    /// ```
    pub fn with_disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    // -- Getters --

    /// Returns the actual value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 42.0, request: 100.0, limit: 200.0 });
    /// assert_eq!(state.actual(), 42.0);
    /// ```
    pub fn actual(&self) -> f64 {
        self.actual
    }

    /// Returns the request value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 42.0, request: 100.0, limit: 200.0 });
    /// assert_eq!(state.request(), 100.0);
    /// ```
    pub fn request(&self) -> f64 {
        self.request
    }

    /// Returns the limit value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 42.0, request: 100.0, limit: 200.0 });
    /// assert_eq!(state.limit(), 200.0);
    /// ```
    pub fn limit(&self) -> f64 {
        self.limit
    }

    /// Returns the label, if set.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert_eq!(state.label(), None);
    /// ```
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Returns the units suffix, if set.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert_eq!(state.units(), None);
    /// ```
    pub fn units(&self) -> Option<&str> {
        self.units.as_deref()
    }

    /// Returns the title, if set.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert_eq!(state.title(), None);
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Returns whether the legend is shown.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert!(state.show_legend());
    /// ```
    pub fn show_legend(&self) -> bool {
        self.show_legend
    }

    /// Returns the gauge orientation.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, GaugeOrientation, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert_eq!(state.orientation(), &GaugeOrientation::Horizontal);
    /// ```
    pub fn orientation(&self) -> &GaugeOrientation {
        &self.orientation
    }

    /// Returns whether the gauge is disabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 0.0, request: 0.0, limit: 0.0 });
    /// assert!(!state.is_disabled());
    /// ```
    pub fn is_disabled(&self) -> bool {
        self.disabled
    }

    /// Returns the utilization ratio (actual / limit), clamped to 0.0–1.0.
    ///
    /// Returns 0.0 if limit is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 250.0, request: 500.0, limit: 1000.0 });
    /// assert!((state.utilization() - 0.25).abs() < 0.001);
    /// ```
    pub fn utilization(&self) -> f64 {
        if self.limit <= 0.0 {
            0.0
        } else {
            (self.actual / self.limit).clamp(0.0, 1.0)
        }
    }

    /// Returns the ratio of actual to request.
    ///
    /// Returns 0.0 if request is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default().with_values(ResourceValues { actual: 250.0, request: 500.0, limit: 1000.0 });
    /// assert!((state.request_ratio() - 0.5).abs() < 0.001);
    /// ```
    pub fn request_ratio(&self) -> f64 {
        if self.request <= 0.0 {
            0.0
        } else {
            self.actual / self.request
        }
    }

    /// Returns true if actual exceeds the request.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let under = ResourceGaugeState::default().with_values(ResourceValues { actual: 100.0, request: 500.0, limit: 1000.0 });
    /// assert!(!under.is_over_request());
    ///
    /// let over = ResourceGaugeState::default().with_values(ResourceValues { actual: 600.0, request: 500.0, limit: 1000.0 });
    /// assert!(over.is_over_request());
    /// ```
    pub fn is_over_request(&self) -> bool {
        self.actual >= self.request && self.request > 0.0
    }

    /// Returns true if actual is at or above 90% of the limit.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let safe = ResourceGaugeState::default().with_values(ResourceValues { actual: 500.0, request: 500.0, limit: 1000.0 });
    /// assert!(!safe.is_near_limit());
    ///
    /// let critical = ResourceGaugeState::default().with_values(ResourceValues { actual: 950.0, request: 500.0, limit: 1000.0 });
    /// assert!(critical.is_near_limit());
    /// ```
    pub fn is_near_limit(&self) -> bool {
        self.limit > 0.0 && self.actual >= self.limit * 0.9
    }

    // -- Setters --

    /// Sets the actual value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(100.0).with_limit(200.0);
    /// state.set_actual(75.0);
    /// assert_eq!(state.actual(), 75.0);
    /// ```
    pub fn set_actual(&mut self, actual: f64) {
        self.actual = actual;
    }

    /// Sets the request value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(50.0).with_request(100.0).with_limit(200.0);
    /// state.set_request(150.0);
    /// assert_eq!(state.request(), 150.0);
    /// ```
    pub fn set_request(&mut self, request: f64) {
        self.request = request;
    }

    /// Sets the limit value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(50.0).with_request(100.0).with_limit(200.0);
    /// state.set_limit(500.0);
    /// assert_eq!(state.limit(), 500.0);
    /// ```
    pub fn set_limit(&mut self, limit: f64) {
        self.limit = limit;
    }

    /// Returns all three values as a named struct.
    ///
    /// Complements [`set_values`](Self::set_values); closes the audit
    /// scorecard accessor-symmetry gap flagged at v0.16.0.
    ///
    /// Returning `ResourceValues` (not a bare `(f64, f64, f64)` tuple) keeps
    /// destructuring safe — `let ResourceValues { actual, request, limit } =
    /// state.values()` binds each field by name, so callers can't silently
    /// transpose `request` and `limit`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{ResourceGaugeState, ResourceValues};
    ///
    /// let state = ResourceGaugeState::default()
    ///     .with_actual(250.0)
    ///     .with_request(500.0)
    ///     .with_limit(1000.0);
    /// let ResourceValues { actual, request, limit } = state.values();
    /// assert_eq!(actual, 250.0);
    /// assert_eq!(request, 500.0);
    /// assert_eq!(limit, 1000.0);
    /// ```
    pub fn values(&self) -> ResourceValues {
        ResourceValues {
            actual: self.actual,
            request: self.request,
            limit: self.limit,
        }
    }

    /// Sets all three values at once.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(0.0).with_limit(0.0);
    /// state.set_values(350.0, 500.0, 1000.0);
    /// assert_eq!(state.actual(), 350.0);
    /// assert_eq!(state.request(), 500.0);
    /// assert_eq!(state.limit(), 1000.0);
    /// ```
    pub fn set_values(&mut self, actual: f64, request: f64, limit: f64) {
        self.actual = actual;
        self.request = request;
        self.limit = limit;
    }

    /// Sets the label.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(0.0).with_limit(0.0);
    /// state.set_label(Some("CPU".to_string()));
    /// assert_eq!(state.label(), Some("CPU"));
    /// ```
    pub fn set_label(&mut self, label: Option<String>) {
        self.label = label;
    }

    /// Sets the units.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(0.0).with_limit(0.0);
    /// state.set_units(Some("Mi".to_string()));
    /// assert_eq!(state.units(), Some("Mi"));
    /// ```
    pub fn set_units(&mut self, units: Option<String>) {
        self.units = units;
    }

    /// Sets the title.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::ResourceGaugeState;
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(0.0).with_limit(0.0);
    /// state.set_title(Some("Resource".to_string()));
    /// assert_eq!(state.title(), Some("Resource"));
    /// ```
    pub fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    /// Instance update method.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::component::resource_gauge::{ResourceGaugeState, ResourceGaugeMessage};
    ///
    /// let mut state = ResourceGaugeState::default().with_actual(0.0).with_request(0.0).with_limit(0.0);
    /// state.update(ResourceGaugeMessage::SetValues {
    ///     actual: 100.0,
    ///     request: 200.0,
    ///     limit: 500.0,
    /// });
    /// assert_eq!(state.actual(), 100.0);
    /// ```
    pub fn update(&mut self, msg: ResourceGaugeMessage) -> Option<()> {
        ResourceGauge::update(self, msg)
    }

    /// Returns the health color based on actual vs request vs limit.
    fn health_color(&self) -> Color {
        if self.limit <= 0.0 {
            Color::DarkGray
        } else if self.actual >= self.limit * 0.9 {
            Color::Red
        } else if self.request > 0.0 && self.actual >= self.request {
            Color::Yellow
        } else {
            Color::Green
        }
    }

    /// Formats the legend text.
    fn legend_text(&self) -> String {
        let units = self.units.as_deref().unwrap_or("");
        format!(
            "{}{} / {}{} / {}{}",
            format_value(self.actual),
            units,
            format_value(self.request),
            units,
            format_value(self.limit),
            units,
        )
    }
}

/// Formats a float value for display (no trailing zeros).
fn format_value(v: f64) -> String {
    if v == v.floor() {
        format!("{}", v as i64)
    } else {
        format!("{:.1}", v)
    }
}

// ---------------------------------------------------------------------------
// Message
// ---------------------------------------------------------------------------

/// Messages for the ResourceGauge component.
///
/// # Examples
///
/// ```
/// use envision::component::resource_gauge::ResourceGaugeMessage;
///
/// let msg = ResourceGaugeMessage::SetActual(42.0);
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum ResourceGaugeMessage {
    /// Set the actual value.
    SetActual(f64),
    /// Set the request value.
    SetRequest(f64),
    /// Set the limit value.
    SetLimit(f64),
    /// Set all three values.
    SetValues {
        /// Actual value.
        actual: f64,
        /// Request value.
        request: f64,
        /// Limit value.
        limit: f64,
    },
    /// Set the label.
    SetLabel(Option<String>),
    /// Set the units.
    SetUnits(Option<String>),
}

/// Output type (display-only, no output).
pub type ResourceGaugeOutput = ();

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

/// A triple-value gauge displaying actual/request/limit.
pub struct ResourceGauge;

impl Component for ResourceGauge {
    type State = ResourceGaugeState;
    type Message = ResourceGaugeMessage;
    type Output = ResourceGaugeOutput;

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

    fn handle_event(
        _state: &Self::State,
        _event: &Event,
        _ctx: &EventContext,
    ) -> Option<Self::Message> {
        None // Display-only component
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            ResourceGaugeMessage::SetActual(v) => state.actual = v,
            ResourceGaugeMessage::SetRequest(v) => state.request = v,
            ResourceGaugeMessage::SetLimit(v) => state.limit = v,
            ResourceGaugeMessage::SetValues {
                actual,
                request,
                limit,
            } => {
                state.actual = actual;
                state.request = request;
                state.limit = limit;
            }
            ResourceGaugeMessage::SetLabel(l) => state.label = l,
            ResourceGaugeMessage::SetUnits(u) => state.units = u,
        }
        None
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        let disabled = ctx.disabled || state.disabled;

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

        let mut block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style);

        if let Some(title) = &state.title {
            block = block.title(format!(" {} ", title));
        }

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

        if inner.width < 3 || inner.height < 1 {
            return;
        }

        // Layout: [label] [bar] [legend]
        let label_width = state
            .label
            .as_ref()
            .map(|l| l.len() as u16 + 1)
            .unwrap_or(0);

        let legend = if state.show_legend {
            state.legend_text()
        } else {
            String::new()
        };
        let legend_width = if legend.is_empty() {
            0
        } else {
            legend.len() as u16 + 1
        };

        let bar_width = inner
            .width
            .saturating_sub(label_width)
            .saturating_sub(legend_width);

        if bar_width < 2 {
            // Too narrow for a bar — just show legend
            let text = if let Some(label) = &state.label {
                format!("{} {}", label, legend)
            } else {
                legend
            };
            let style = if disabled {
                ctx.theme.disabled_style()
            } else {
                Style::default().fg(state.health_color())
            };
            ctx.frame
                .render_widget(Paragraph::new(text).style(style), inner);
            return;
        }

        let bar_y = inner.y;
        let buf = ctx.frame.buffer_mut();
        let buf_area = buf.area;

        // Render label
        if let Some(label) = &state.label {
            let label_style = if disabled {
                ctx.theme.disabled_style()
            } else {
                Style::default().add_modifier(Modifier::BOLD)
            };
            for (i, ch) in label.chars().enumerate() {
                let x = inner.x + i as u16;
                if x < inner.x + label_width {
                    set_cell(buf, x, bar_y, &ch.to_string(), label_style, buf_area);
                }
            }
        }

        // Render bar
        let bar_x = inner.x + label_width;
        let bar_params = BarParams {
            state,
            disabled,
            theme: ctx.theme,
        };
        render_bar(buf, bar_x, bar_y, bar_width, &bar_params);

        // Render legend
        if !legend.is_empty() {
            let legend_x = bar_x + bar_width + 1;
            let legend_style = if disabled {
                ctx.theme.disabled_style()
            } else {
                Style::default().fg(state.health_color())
            };
            for (i, ch) in legend.chars().enumerate() {
                let x = legend_x + i as u16;
                if x < inner.x + inner.width {
                    set_cell(buf, x, bar_y, &ch.to_string(), legend_style, buf_area);
                }
            }
        }
    }
}

struct BarParams<'a> {
    state: &'a ResourceGaugeState,
    disabled: bool,
    theme: &'a Theme,
}

/// Renders the triple-value bar.
fn render_bar(buf: &mut Buffer, x: u16, y: u16, width: u16, params: &BarParams<'_>) {
    let state = params.state;
    let disabled = params.disabled;
    let buf_area = buf.area;
    if state.limit <= 0.0 || width == 0 {
        // Empty bar
        for i in 0..width {
            set_cell(
                buf,
                x + i,
                y,
                "\u{2591}",
                Style::default().fg(Color::DarkGray),
                buf_area,
            );
        }
        return;
    }

    let actual_ratio = (state.actual / state.limit).clamp(0.0, 1.0);
    let request_ratio = if state.request > 0.0 {
        (state.request / state.limit).clamp(0.0, 1.0)
    } else {
        0.0
    };

    let actual_pos = ((actual_ratio * width as f64) as u16).min(width);
    let request_pos = ((request_ratio * width as f64) as u16).min(width);

    let fill_color = if disabled {
        params.theme.disabled_style().fg.unwrap_or(Color::DarkGray)
    } else {
        state.health_color()
    };

    let fill_style = Style::default().fg(fill_color);
    let request_zone_style = Style::default().fg(Color::DarkGray);
    let empty_style = Style::default().fg(Color::DarkGray);

    for i in 0..width {
        let cx = x + i;
        if i < actual_pos {
            // Filled — actual usage
            set_cell(buf, cx, y, "\u{2588}", fill_style, buf_area);
        } else if i < request_pos {
            // Request headroom zone
            set_cell(buf, cx, y, "\u{2593}", request_zone_style, buf_area);
        } else {
            // Empty — unused capacity
            set_cell(buf, cx, y, "\u{2591}", empty_style, buf_area);
        }
    }

    // Request marker (if request is between 0 and limit)
    if request_pos > 0 && request_pos < width && state.request > 0.0 {
        let marker_style = if disabled {
            Style::default().fg(Color::DarkGray)
        } else {
            Style::default()
                .fg(Color::White)
                .add_modifier(Modifier::BOLD)
        };
        set_cell(buf, x + request_pos, y, "\u{2502}", marker_style, buf_area);
    }
}

/// Writes a character to the buffer at (x, y) if within bounds.
fn set_cell(buf: &mut Buffer, x: u16, y: u16, ch: &str, style: Style, area: Rect) {
    if x >= area.x && x < area.right() && y >= area.y && y < area.bottom() {
        if let Some(cell) = buf.cell_mut(Position::new(x, y)) {
            cell.set_symbol(ch);
            cell.set_style(style);
        }
    }
}

#[cfg(test)]
mod tests;