presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! `NetworkPanel` widget for network interface monitoring.
//!
//! Displays network interfaces with upload/download sparklines.
//! Reference: ttop/btop network displays.

use presentar_core::{
    Brick, BrickAssertion, BrickBudget, BrickVerification, Canvas, Color, Constraints, Event,
    LayoutResult, Point, Rect, Size, TextStyle, TypeId, Widget,
};
use std::any::Any;
use std::time::Duration;

/// Block characters for sparkline rendering (8 levels).
const SPARK_CHARS: [char; 8] = ['', '', '', '', '', '', '', ''];

/// A network interface entry.
#[derive(Debug, Clone)]
pub struct NetworkInterface {
    /// Interface name (e.g., "eth0", "wlan0").
    pub name: String,
    /// Download bytes per second history.
    pub rx_history: Vec<f64>,
    /// Upload bytes per second history.
    pub tx_history: Vec<f64>,
    /// Current download bytes per second.
    pub rx_bps: f64,
    /// Current upload bytes per second.
    pub tx_bps: f64,
    /// Total bytes received.
    pub rx_total: u64,
    /// Total bytes transmitted.
    pub tx_total: u64,
    /// Receive errors (cumulative).
    pub rx_errors: u64,
    /// Transmit errors (cumulative).
    pub tx_errors: u64,
    /// Receive dropped packets (cumulative).
    pub rx_dropped: u64,
    /// Transmit dropped packets (cumulative).
    pub tx_dropped: u64,
    /// Error rate (errors per second).
    pub errors_per_sec: f64,
    /// Drop rate (drops per second).
    pub drops_per_sec: f64,
    /// Bandwidth utilization percentage (CB-NET-006).
    /// None if link speed unknown.
    pub utilization_percent: Option<f64>,
}

impl NetworkInterface {
    /// Create a new network interface entry.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            rx_history: Vec::new(),
            tx_history: Vec::new(),
            rx_bps: 0.0,
            tx_bps: 0.0,
            rx_total: 0,
            tx_total: 0,
            rx_errors: 0,
            tx_errors: 0,
            rx_dropped: 0,
            tx_dropped: 0,
            errors_per_sec: 0.0,
            drops_per_sec: 0.0,
            utilization_percent: None,
        }
    }

    /// Set error and drop stats.
    pub fn set_stats(&mut self, rx_errors: u64, tx_errors: u64, rx_dropped: u64, tx_dropped: u64) {
        self.rx_errors = rx_errors;
        self.tx_errors = tx_errors;
        self.rx_dropped = rx_dropped;
        self.tx_dropped = tx_dropped;
    }

    /// Set error and drop rates.
    pub fn set_rates(&mut self, errors_per_sec: f64, drops_per_sec: f64) {
        self.errors_per_sec = errors_per_sec;
        self.drops_per_sec = drops_per_sec;
    }

    /// Set bandwidth utilization percentage (CB-NET-006).
    pub fn set_utilization(&mut self, utilization_percent: Option<f64>) {
        self.utilization_percent = utilization_percent;
    }

    /// Total errors (RX + TX).
    #[must_use]
    pub fn total_errors(&self) -> u64 {
        self.rx_errors + self.tx_errors
    }

    /// Total dropped packets (RX + TX).
    #[must_use]
    pub fn total_dropped(&self) -> u64 {
        self.rx_dropped + self.tx_dropped
    }

    /// Update with current bandwidth readings.
    pub fn update(&mut self, rx_bps: f64, tx_bps: f64) {
        self.rx_bps = rx_bps;
        self.tx_bps = tx_bps;
        self.rx_history.push(rx_bps);
        self.tx_history.push(tx_bps);
        // Keep last 60 samples
        if self.rx_history.len() > 60 {
            self.rx_history.remove(0);
        }
        if self.tx_history.len() > 60 {
            self.tx_history.remove(0);
        }
    }

    /// Set totals.
    pub fn set_totals(&mut self, rx: u64, tx: u64) {
        self.rx_total = rx;
        self.tx_total = tx;
    }
}

/// Network panel showing multiple interfaces with sparklines.
#[derive(Debug, Clone)]
pub struct NetworkPanel {
    /// Network interfaces.
    interfaces: Vec<NetworkInterface>,
    /// Download color.
    rx_color: Color,
    /// Upload color.
    tx_color: Color,
    /// Sparkline width.
    spark_width: usize,
    /// Show totals.
    show_totals: bool,
    /// Compact mode.
    compact: bool,
    /// Cached bounds.
    bounds: Rect,
}

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

impl NetworkPanel {
    /// Create a new network panel.
    #[must_use]
    pub fn new() -> Self {
        Self {
            interfaces: Vec::new(),
            rx_color: Color::new(0.3, 0.8, 0.3, 1.0), // Green for download
            tx_color: Color::new(0.8, 0.3, 0.3, 1.0), // Red for upload
            spark_width: 20,
            show_totals: true,
            compact: false,
            bounds: Rect::default(),
        }
    }

    /// Set interfaces.
    pub fn set_interfaces(&mut self, interfaces: Vec<NetworkInterface>) {
        self.interfaces = interfaces;
    }

    /// Add an interface.
    pub fn add_interface(&mut self, iface: NetworkInterface) {
        self.interfaces.push(iface);
    }

    /// Get interface by name.
    pub fn interface_mut(&mut self, name: &str) -> Option<&mut NetworkInterface> {
        self.interfaces.iter_mut().find(|i| i.name == name)
    }

    /// Clear all interfaces.
    pub fn clear(&mut self) {
        self.interfaces.clear();
    }

    /// Set download color.
    #[must_use]
    pub fn with_rx_color(mut self, color: Color) -> Self {
        self.rx_color = color;
        self
    }

    /// Set upload color.
    #[must_use]
    pub fn with_tx_color(mut self, color: Color) -> Self {
        self.tx_color = color;
        self
    }

    /// Set sparkline width.
    #[must_use]
    pub fn with_spark_width(mut self, width: usize) -> Self {
        self.spark_width = width;
        self
    }

    /// Hide totals.
    #[must_use]
    pub fn without_totals(mut self) -> Self {
        self.show_totals = false;
        self
    }

    /// Enable compact mode.
    #[must_use]
    pub fn compact(mut self) -> Self {
        self.compact = true;
        self
    }

    /// Get interface count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.interfaces.len()
    }

    /// Check if empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.interfaces.is_empty()
    }

    /// Format bytes per second as human-readable string.
    fn format_bps(bps: f64) -> String {
        const KB: f64 = 1024.0;
        const MB: f64 = KB * 1024.0;
        const GB: f64 = MB * 1024.0;

        if bps >= GB {
            format!("{:.1}G/s", bps / GB)
        } else if bps >= MB {
            format!("{:.1}M/s", bps / MB)
        } else if bps >= KB {
            format!("{:.1}K/s", bps / KB)
        } else {
            format!("{bps:.0}B/s")
        }
    }

    /// Format total bytes as human-readable string.
    fn format_bytes(bytes: u64) -> String {
        const KB: u64 = 1024;
        const MB: u64 = KB * 1024;
        const GB: u64 = MB * 1024;
        const TB: u64 = GB * 1024;

        if bytes >= TB {
            format!("{:.1}T", bytes as f64 / TB as f64)
        } else if bytes >= GB {
            format!("{:.1}G", bytes as f64 / GB as f64)
        } else if bytes >= MB {
            format!("{:.1}M", bytes as f64 / MB as f64)
        } else if bytes >= KB {
            format!("{:.1}K", bytes as f64 / KB as f64)
        } else {
            format!("{bytes}B")
        }
    }

    /// Render sparkline from data.
    fn render_sparkline(data: &[f64], width: usize) -> String {
        if data.is_empty() {
            return " ".repeat(width);
        }

        let max_val = data
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
            .max(1.0);
        let start = data.len().saturating_sub(width);
        let visible = &data[start..];

        let mut result = String::with_capacity(width * 3); // Unicode chars are up to 3 bytes
        for &val in visible {
            let normalized = (val / max_val).clamp(0.0, 1.0);
            let idx = ((normalized * 7.0).round() as usize).min(7);
            result.push(SPARK_CHARS[idx]);
        }

        // Pad if needed (use char count, not byte count)
        let char_count = result.chars().count();
        if char_count < width {
            let padding = " ".repeat(width - char_count);
            result.insert_str(0, &padding);
        }

        result
    }
}

impl Brick for NetworkPanel {
    fn brick_name(&self) -> &'static str {
        "network_panel"
    }

    fn assertions(&self) -> &[BrickAssertion] {
        static ASSERTIONS: &[BrickAssertion] = &[BrickAssertion::max_latency_ms(8)];
        ASSERTIONS
    }

    fn budget(&self) -> BrickBudget {
        BrickBudget::uniform(8)
    }

    fn verify(&self) -> BrickVerification {
        BrickVerification {
            passed: vec![BrickAssertion::max_latency_ms(8)],
            failed: vec![],
            verification_time: Duration::from_micros(5),
        }
    }

    fn to_html(&self) -> String {
        String::new()
    }

    fn to_css(&self) -> String {
        String::new()
    }
}

impl Widget for NetworkPanel {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn measure(&self, constraints: Constraints) -> Size {
        let rows_per_iface = if self.compact { 1 } else { 2 };
        let height = (self.interfaces.len() * rows_per_iface + 1) as f32;
        let min_width = if self.compact { 40.0 } else { 60.0 };
        let width = constraints.max_width.max(min_width);
        constraints.constrain(Size::new(width, height.max(2.0)))
    }

    fn layout(&mut self, bounds: Rect) -> LayoutResult {
        self.bounds = bounds;
        LayoutResult {
            size: Size::new(bounds.width, bounds.height),
        }
    }

    #[allow(clippy::too_many_lines)]
    fn paint(&self, canvas: &mut dyn Canvas) {
        let width = self.bounds.width as usize;
        let height = self.bounds.height as usize;
        if width == 0 || height == 0 {
            return;
        }

        // Header
        let header_style = TextStyle {
            color: Color::new(0.0, 1.0, 1.0, 1.0),
            weight: presentar_core::FontWeight::Bold,
            ..Default::default()
        };
        canvas.draw_text(
            "Network",
            Point::new(self.bounds.x, self.bounds.y),
            &header_style,
        );

        let _rows_per_iface = if self.compact { 1 } else { 2 };
        let mut y = self.bounds.y + 1.0;

        for iface in &self.interfaces {
            if y >= self.bounds.y + self.bounds.height {
                break;
            }

            if self.compact {
                // Compact: single line per interface
                // eth0: ▁▂▃▄▅ 125K/s ↓ ▅▄▃▂▁ 50K/s ↑
                let name_w = 8;
                let spark_w = self.spark_width.min(width.saturating_sub(30) / 2);

                let mut x = self.bounds.x;

                // Interface name
                let name = format!("{:name_w$}", iface.name);
                canvas.draw_text(
                    &name,
                    Point::new(x, y),
                    &TextStyle {
                        color: Color::new(0.8, 0.8, 0.8, 1.0),
                        ..Default::default()
                    },
                );
                x += name_w as f32 + 1.0;

                // Download sparkline
                let rx_spark = Self::render_sparkline(&iface.rx_history, spark_w);
                canvas.draw_text(
                    &rx_spark,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += spark_w as f32 + 1.0;

                // Download rate
                let rx_rate = format!("{:>8}", Self::format_bps(iface.rx_bps));
                canvas.draw_text(
                    &rx_rate,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += 9.0;

                // Arrow
                canvas.draw_text(
                    "",
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += 2.0;

                // Upload sparkline
                let tx_spark = Self::render_sparkline(&iface.tx_history, spark_w);
                canvas.draw_text(
                    &tx_spark,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += spark_w as f32 + 1.0;

                // Upload rate
                let tx_rate = format!("{:>8}", Self::format_bps(iface.tx_bps));
                canvas.draw_text(
                    &tx_rate,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += 9.0;

                // Arrow
                canvas.draw_text(
                    "",
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += 2.0;

                // Error/Drop rate highlighting (CB-NET-003/004)
                // Show warning indicators if error or drop rates are non-zero
                if iface.errors_per_sec > 0.0 || iface.drops_per_sec > 0.0 {
                    // Choose color based on severity
                    let (indicator, color) =
                        if iface.errors_per_sec > 10.0 || iface.drops_per_sec > 10.0 {
                            (
                                "",
                                Color {
                                    r: 1.0,
                                    g: 0.3,
                                    b: 0.3,
                                    a: 1.0,
                                },
                            ) // Red - critical
                        } else if iface.errors_per_sec > 1.0 || iface.drops_per_sec > 1.0 {
                            (
                                "",
                                Color {
                                    r: 1.0,
                                    g: 0.8,
                                    b: 0.2,
                                    a: 1.0,
                                },
                            ) // Yellow - warning
                        } else {
                            (
                                "",
                                Color {
                                    r: 0.8,
                                    g: 0.8,
                                    b: 0.3,
                                    a: 1.0,
                                },
                            ) // Dim yellow - minor
                        };

                    // Format: ●E:5/D:2
                    let err_drop_text = format!(
                        "{indicator}E:{:.0}/D:{:.0}",
                        iface.errors_per_sec, iface.drops_per_sec
                    );
                    canvas.draw_text(
                        &err_drop_text,
                        Point::new(x, y),
                        &TextStyle {
                            color,
                            ..Default::default()
                        },
                    );
                    x += err_drop_text.len() as f32 + 1.0;
                }

                // Bandwidth utilization display (CB-NET-006)
                if let Some(util_pct) = iface.utilization_percent {
                    let capped = util_pct.min(100.0);
                    let (util_text, util_color) = if util_pct > 80.0 {
                        (
                            format!("{capped:.0}%"),
                            Color {
                                r: 1.0,
                                g: 0.3,
                                b: 0.3,
                                a: 1.0,
                            }, // Red - saturated
                        )
                    } else if util_pct > 50.0 {
                        (
                            format!("{util_pct:.0}%"),
                            Color {
                                r: 1.0,
                                g: 0.8,
                                b: 0.2,
                                a: 1.0,
                            }, // Yellow - high
                        )
                    } else {
                        (
                            format!("{util_pct:.0}%"),
                            Color {
                                r: 0.5,
                                g: 0.8,
                                b: 0.5,
                                a: 1.0,
                            }, // Green - normal
                        )
                    };
                    canvas.draw_text(
                        &util_text,
                        Point::new(x, y),
                        &TextStyle {
                            color: util_color,
                            ..Default::default()
                        },
                    );
                }
            } else {
                // Full: two lines per interface
                // eth0
                //   ↓ ▁▂▃▄▅▆▇█ 125.3M/s (Total: 1.2G)  ↑ ▅▄▃▂▁▂▃▄ 50.2K/s (Total: 500M)

                // Interface name
                canvas.draw_text(
                    &iface.name,
                    Point::new(self.bounds.x, y),
                    &TextStyle {
                        color: Color::new(0.8, 0.8, 1.0, 1.0),
                        weight: presentar_core::FontWeight::Bold,
                        ..Default::default()
                    },
                );
                y += 1.0;

                let spark_w = self.spark_width.min(width.saturating_sub(40) / 2);
                let mut x = self.bounds.x + 2.0;

                // Download
                canvas.draw_text(
                    "",
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += 2.0;

                let rx_spark = Self::render_sparkline(&iface.rx_history, spark_w);
                canvas.draw_text(
                    &rx_spark,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += spark_w as f32 + 1.0;

                let rx_rate = Self::format_bps(iface.rx_bps);
                canvas.draw_text(
                    &rx_rate,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.rx_color,
                        ..Default::default()
                    },
                );
                x += 10.0;

                if self.show_totals {
                    let rx_total = format!("({})", Self::format_bytes(iface.rx_total));
                    canvas.draw_text(
                        &rx_total,
                        Point::new(x, y),
                        &TextStyle {
                            color: Color::new(0.5, 0.5, 0.5, 1.0),
                            ..Default::default()
                        },
                    );
                    x += 10.0;
                }

                x += 2.0;

                // Upload
                canvas.draw_text(
                    "",
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += 2.0;

                let tx_spark = Self::render_sparkline(&iface.tx_history, spark_w);
                canvas.draw_text(
                    &tx_spark,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += spark_w as f32 + 1.0;

                let tx_rate = Self::format_bps(iface.tx_bps);
                canvas.draw_text(
                    &tx_rate,
                    Point::new(x, y),
                    &TextStyle {
                        color: self.tx_color,
                        ..Default::default()
                    },
                );
                x += 10.0;

                if self.show_totals {
                    let tx_total = format!("({})", Self::format_bytes(iface.tx_total));
                    canvas.draw_text(
                        &tx_total,
                        Point::new(x, y),
                        &TextStyle {
                            color: Color::new(0.5, 0.5, 0.5, 1.0),
                            ..Default::default()
                        },
                    );
                }
            }

            y += 1.0;
        }

        // Empty state
        if self.interfaces.is_empty() && height > 1 {
            canvas.draw_text(
                "No interfaces",
                Point::new(self.bounds.x + 1.0, self.bounds.y + 1.0),
                &TextStyle {
                    color: Color::new(0.5, 0.5, 0.5, 1.0),
                    ..Default::default()
                },
            );
        }
    }

    fn event(&mut self, _event: &Event) -> Option<Box<dyn Any + Send>> {
        None
    }

    fn children(&self) -> &[Box<dyn Widget>] {
        &[]
    }

    fn children_mut(&mut self) -> &mut [Box<dyn Widget>] {
        &mut []
    }
}

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

    fn sample_interface() -> NetworkInterface {
        let mut iface = NetworkInterface::new("eth0");
        for i in 0..30 {
            iface.update(i as f64 * 1000.0, i as f64 * 500.0);
        }
        iface.set_totals(1024 * 1024 * 1024, 512 * 1024 * 1024);
        iface
    }

    #[test]
    fn test_network_panel_new() {
        let panel = NetworkPanel::new();
        assert!(panel.is_empty());
    }

    #[test]
    fn test_network_panel_add_interface() {
        let mut panel = NetworkPanel::new();
        panel.add_interface(NetworkInterface::new("eth0"));
        assert_eq!(panel.len(), 1);
    }

    #[test]
    fn test_network_panel_set_interfaces() {
        let mut panel = NetworkPanel::new();
        panel.set_interfaces(vec![
            NetworkInterface::new("eth0"),
            NetworkInterface::new("wlan0"),
        ]);
        assert_eq!(panel.len(), 2);
    }

    #[test]
    fn test_network_panel_interface_mut() {
        let mut panel = NetworkPanel::new();
        panel.add_interface(NetworkInterface::new("eth0"));
        let iface = panel.interface_mut("eth0").unwrap();
        iface.update(1000.0, 500.0);
        assert_eq!(iface.rx_bps, 1000.0);
    }

    #[test]
    fn test_network_panel_clear() {
        let mut panel = NetworkPanel::new();
        panel.add_interface(NetworkInterface::new("eth0"));
        panel.clear();
        assert!(panel.is_empty());
    }

    #[test]
    fn test_network_interface_update() {
        let mut iface = NetworkInterface::new("eth0");
        iface.update(1000.0, 500.0);
        assert_eq!(iface.rx_bps, 1000.0);
        assert_eq!(iface.tx_bps, 500.0);
        assert_eq!(iface.rx_history.len(), 1);
        assert_eq!(iface.tx_history.len(), 1);
    }

    #[test]
    fn test_network_interface_history_limit() {
        let mut iface = NetworkInterface::new("eth0");
        for i in 0..100 {
            iface.update(i as f64, i as f64);
        }
        assert_eq!(iface.rx_history.len(), 60);
        assert_eq!(iface.tx_history.len(), 60);
    }

    #[test]
    fn test_network_panel_with_colors() {
        let panel = NetworkPanel::new()
            .with_rx_color(Color::BLUE)
            .with_tx_color(Color::RED);
        assert_eq!(panel.rx_color, Color::BLUE);
        assert_eq!(panel.tx_color, Color::RED);
    }

    #[test]
    fn test_network_panel_with_spark_width() {
        let panel = NetworkPanel::new().with_spark_width(30);
        assert_eq!(panel.spark_width, 30);
    }

    #[test]
    fn test_network_panel_without_totals() {
        let panel = NetworkPanel::new().without_totals();
        assert!(!panel.show_totals);
    }

    #[test]
    fn test_network_panel_compact() {
        let panel = NetworkPanel::new().compact();
        assert!(panel.compact);
    }

    #[test]
    fn test_format_bps() {
        assert_eq!(NetworkPanel::format_bps(500.0), "500B/s");
        assert_eq!(NetworkPanel::format_bps(1024.0), "1.0K/s");
        assert_eq!(NetworkPanel::format_bps(1024.0 * 1024.0), "1.0M/s");
        assert_eq!(NetworkPanel::format_bps(1024.0 * 1024.0 * 1024.0), "1.0G/s");
    }

    #[test]
    fn test_format_bytes() {
        assert_eq!(NetworkPanel::format_bytes(500), "500B");
        assert_eq!(NetworkPanel::format_bytes(1024), "1.0K");
        assert_eq!(NetworkPanel::format_bytes(1024 * 1024), "1.0M");
        assert_eq!(NetworkPanel::format_bytes(1024 * 1024 * 1024), "1.0G");
        assert_eq!(
            NetworkPanel::format_bytes(1024u64 * 1024 * 1024 * 1024),
            "1.0T"
        );
    }

    #[test]
    fn test_render_sparkline() {
        let data = vec![0.0, 0.5, 1.0];
        let spark = NetworkPanel::render_sparkline(&data, 5);
        assert_eq!(spark.chars().count(), 5);
    }

    #[test]
    fn test_render_sparkline_empty() {
        let spark = NetworkPanel::render_sparkline(&[], 5);
        assert_eq!(spark, "     ");
    }

    #[test]
    fn test_network_panel_measure() {
        let mut panel = NetworkPanel::new();
        panel.add_interface(NetworkInterface::new("eth0"));
        let size = panel.measure(Constraints::new(0.0, 100.0, 0.0, 50.0));
        assert!(size.width >= 60.0);
        assert!(size.height >= 2.0);
    }

    #[test]
    fn test_network_panel_layout() {
        let mut panel = NetworkPanel::new();
        let result = panel.layout(Rect::new(0.0, 0.0, 80.0, 20.0));
        assert_eq!(result.size.width, 80.0);
    }

    #[test]
    fn test_network_panel_verify() {
        let panel = NetworkPanel::new();
        assert!(panel.verify().is_valid());
    }

    #[test]
    fn test_network_panel_brick_name() {
        let panel = NetworkPanel::new();
        assert_eq!(panel.brick_name(), "network_panel");
    }

    #[test]
    fn test_network_panel_default() {
        let panel = NetworkPanel::default();
        assert!(panel.is_empty());
    }

    #[test]
    fn test_network_panel_children() {
        let panel = NetworkPanel::new();
        assert!(panel.children().is_empty());
    }

    #[test]
    fn test_network_panel_children_mut() {
        let mut panel = NetworkPanel::new();
        assert!(panel.children_mut().is_empty());
    }

    #[test]
    fn test_network_panel_type_id() {
        let panel = NetworkPanel::new();
        assert_eq!(Widget::type_id(&panel), TypeId::of::<NetworkPanel>());
    }

    #[test]
    fn test_network_panel_to_html() {
        let panel = NetworkPanel::new();
        assert!(panel.to_html().is_empty());
    }

    #[test]
    fn test_network_panel_to_css() {
        let panel = NetworkPanel::new();
        assert!(panel.to_css().is_empty());
    }

    #[test]
    fn test_network_interface_set_totals() {
        let mut iface = NetworkInterface::new("eth0");
        iface.set_totals(1000, 500);
        assert_eq!(iface.rx_total, 1000);
        assert_eq!(iface.tx_total, 500);
    }

    #[test]
    fn test_network_panel_paint_with_data() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new();
        let mut iface = NetworkInterface::new("eth0");
        for i in 0..30 {
            iface.update(i as f64 * 1000.0, i as f64 * 500.0);
        }
        iface.set_totals(1024 * 1024 * 1024, 512 * 1024 * 1024);
        panel.add_interface(iface);

        panel.layout(Rect::new(0.0, 0.0, 80.0, 10.0));

        let mut buffer = CellBuffer::new(80, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_paint_empty() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new();
        panel.layout(Rect::new(0.0, 0.0, 60.0, 10.0));

        let mut buffer = CellBuffer::new(60, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_paint_small_bounds() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new();
        panel.add_interface(NetworkInterface::new("eth0"));
        panel.layout(Rect::new(0.0, 0.0, 5.0, 0.5)); // Too small

        let mut buffer = CellBuffer::new(5, 1);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas); // Should early return
    }

    #[test]
    fn test_network_panel_paint_compact() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new().compact();
        let mut iface = NetworkInterface::new("wlan0");
        iface.update(5000.0, 2500.0);
        panel.add_interface(iface);

        panel.layout(Rect::new(0.0, 0.0, 60.0, 10.0));

        let mut buffer = CellBuffer::new(60, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_paint_with_totals() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new(); // show_totals is true by default
        let mut iface = NetworkInterface::new("eth0");
        iface.update(1024.0 * 1024.0, 512.0 * 1024.0);
        iface.set_totals(10 * 1024 * 1024 * 1024, 5 * 1024 * 1024 * 1024);
        panel.add_interface(iface);

        panel.layout(Rect::new(0.0, 0.0, 80.0, 10.0));

        let mut buffer = CellBuffer::new(80, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_paint_without_totals() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new().without_totals();
        let mut iface = NetworkInterface::new("eth0");
        iface.update(1024.0, 512.0);
        panel.add_interface(iface);

        panel.layout(Rect::new(0.0, 0.0, 60.0, 10.0));

        let mut buffer = CellBuffer::new(60, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_multiple_interfaces() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new();

        let mut eth0 = NetworkInterface::new("eth0");
        eth0.update(10000.0, 5000.0);
        panel.add_interface(eth0);

        let mut wlan0 = NetworkInterface::new("wlan0");
        wlan0.update(2000.0, 1000.0);
        panel.add_interface(wlan0);

        let mut lo = NetworkInterface::new("lo");
        lo.update(100.0, 100.0);
        panel.add_interface(lo);

        panel.layout(Rect::new(0.0, 0.0, 80.0, 10.0));

        let mut buffer = CellBuffer::new(80, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_network_panel_event() {
        let mut panel = NetworkPanel::new();
        let result = panel.event(&Event::KeyDown {
            key: presentar_core::Key::Enter,
        });
        assert!(result.is_none());
    }

    #[test]
    fn test_network_panel_assertions() {
        let panel = NetworkPanel::new();
        assert!(!panel.assertions().is_empty());
    }

    #[test]
    fn test_network_panel_budget() {
        let panel = NetworkPanel::new();
        assert!(panel.budget().paint_ms > 0);
    }

    #[test]
    fn test_network_interface_long_name() {
        use crate::direct::{CellBuffer, DirectTerminalCanvas};

        let mut panel = NetworkPanel::new();
        let mut iface = NetworkInterface::new("verylonginterfacename0");
        iface.update(1024.0, 512.0);
        panel.add_interface(iface);

        panel.layout(Rect::new(0.0, 0.0, 80.0, 10.0));

        let mut buffer = CellBuffer::new(80, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        panel.paint(&mut canvas);
    }

    #[test]
    fn test_format_bps_edge_cases() {
        // Test very large values (displayed as G/s since no T/s support)
        assert!(NetworkPanel::format_bps(1024.0 * 1024.0 * 1024.0 * 1024.0).contains("G/s"));
        // Test very small values
        assert_eq!(NetworkPanel::format_bps(0.5), "0B/s");
    }

    #[test]
    fn test_render_sparkline_single_value() {
        let data = vec![0.5];
        let spark = NetworkPanel::render_sparkline(&data, 3);
        assert_eq!(spark.chars().count(), 3);
    }
}