sugarrush 2026.7.1

A terminal UI for viewing Nightscout CGM (blood glucose sensor) data
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
//! Rendering. v1: a single dashboard screen.

use chrono::{Local, TimeZone};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    symbols,
    text::{Line, Span},
    widgets::{Axis, Block, Borders, Chart, Dataset, GraphType, Paragraph},
    Frame,
};

use crate::app::{App, Field, Screen};
use crate::bigfont;
use crate::config::GraphStyle;
use crate::stats;

pub fn draw(f: &mut Frame, app: &App) {
    if app.screen == Screen::Settings {
        draw_settings(f, app);
        return;
    }
    // A one-line alert banner appears above the header only while alerting.
    let banner = app.alert.is_alerting();
    let minimap = app.minimap_enabled;
    // On wide terminals, current + stats share one row (side-by-side),
    // reclaiming ~5 rows for the graph. Otherwise they stack.
    let wide = f.area().width >= 90;

    let mut constraints = Vec::new();
    if banner {
        constraints.push(Constraint::Length(1)); // banner
    }
    constraints.push(Constraint::Length(3)); // header
    if wide {
        constraints.push(Constraint::Length(7)); // current + stats
    } else {
        constraints.push(Constraint::Length(7)); // current
        constraints.push(Constraint::Length(5)); // stats
    }
    constraints.push(Constraint::Min(8)); // graph
    if minimap {
        constraints.push(Constraint::Length(4)); // minimap
    }
    constraints.push(Constraint::Length(1)); // footer

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(f.area());

    let mut i = 0;
    if banner {
        draw_banner(f, chunks[i], app);
        i += 1;
    }
    draw_header(f, chunks[i], app);
    i += 1;
    if wide {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
            .split(chunks[i]);
        draw_current(f, cols[0], app);
        draw_stats(f, cols[1], app);
        i += 1;
    } else {
        draw_current(f, chunks[i], app);
        draw_stats(f, chunks[i + 1], app);
        i += 2;
    }
    draw_graph(f, chunks[i], app);
    i += 1;
    if minimap {
        draw_minimap(f, chunks[i], app);
        i += 1;
    }
    draw_footer(f, chunks[i], app);
}

fn draw_minimap(f: &mut Frame, area: Rect, app: &App) {
    let hours = app.minimap_span_ms / 3_600_000;
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {hours}h overview "));
    let inner = block.inner(area);
    f.render_widget(block, area);
    // Record the inner rect so mouse events can map columns back to time.
    app.minimap_rect.set(Some(inner));

    let now = chrono::Utc::now().timestamp_millis();
    let start = now - app.minimap_span_ms;

    if app.minimap_entries.is_empty() {
        return;
    }

    let points: Vec<(f64, f64)> = app
        .minimap_entries
        .iter()
        .rev()
        .map(|e| (e.date as f64, app.units.from_mgdl(e.sgv)))
        .collect();
    let (min_y, max_y) = points
        .iter()
        .fold((f64::MAX, f64::MIN), |(lo, hi), (_, y)| {
            (lo.min(*y), hi.max(*y))
        });
    let bounds_y = [min_y, max_y.max(min_y + 1.0)];

    // Bracket the currently-visible window with two vertical rules.
    let vs = (app.view_start.max(start)) as f64;
    let ve = (app.view_end.min(now)) as f64;
    let start_rule = [(vs, bounds_y[0]), (vs, bounds_y[1])];
    let end_rule = [(ve, bounds_y[0]), (ve, bounds_y[1])];

    let datasets = vec![
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(Color::DarkGray))
            .data(&points),
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(app.theme.graph))
            .data(&start_rule),
        Dataset::default()
            .marker(symbols::Marker::Braille)
            .graph_type(GraphType::Line)
            .style(Style::default().fg(app.theme.graph))
            .data(&end_rule),
    ];

    let chart = Chart::new(datasets)
        .x_axis(Axis::default().bounds([start as f64, now as f64]))
        .y_axis(Axis::default().bounds(bounds_y));
    f.render_widget(chart, inner);
}

fn draw_stats(f: &mut Frame, area: Rect, app: &App) {
    let block = Block::default().borders(Borders::ALL).title(" stats ");
    let inner = block.inner(area);
    f.render_widget(block, area);

    let u = app.units;
    // Time-in-range over the loaded window.
    let tir_line = match stats::tir(&app.entries, app.alerts.low, app.alerts.high) {
        Some(t) => Line::from(vec![
            Span::raw("  TIR  "),
            Span::styled(
                format!("low {:.0}%", t.low),
                Style::default().fg(Color::Red),
            ),
            Span::raw("  "),
            Span::styled(
                format!("in-range {:.0}%", t.in_range),
                Style::default().fg(Color::Green),
            ),
            Span::raw("  "),
            Span::styled(
                format!("high {:.0}%", t.high),
                Style::default().fg(Color::Yellow),
            ),
        ]),
        None => Line::from("  TIR  —"),
    };

    // Mean + estimated A1c, plus IOB/COB when the uploader provides them.
    let mut iobcob = String::new();
    if let Some(iob) = app.device.iob {
        iobcob.push_str(&format!("   ·   IOB {iob:.1}U"));
    }
    if let Some(cob) = app.device.cob {
        iobcob.push_str(&format!("   ·   COB {cob:.0}g"));
    }
    let avg_line = match stats::mean_mgdl(&app.entries) {
        Some(mean) => Line::from(format!(
            "  avg  {} {}   ·   GMI {:.1}%{iobcob}",
            u.format(mean),
            u.label(),
            stats::gmi(mean),
        )),
        None if !iobcob.is_empty() => Line::from(format!("  avg  —{iobcob}")),
        None => Line::from("  avg  —"),
    };

    // Device / uploader status.
    let now = chrono::Utc::now().timestamp_millis();
    let mut parts = Vec::new();
    if let Some(name) = &app.device.device {
        parts.push(name.clone());
    }
    if let Some(b) = app.device.battery {
        parts.push(format!("battery {b}%"));
    }
    if let Some(start) = app.sensor_start_ms {
        parts.push(format!("sensor {}", fmt_age(now - start)));
    }
    if let Some(last) = app.device.last_ms {
        parts.push(format!("uploader {} ago", fmt_age(now - last)));
    }
    let dev_line = if parts.is_empty() {
        Line::from(Span::styled(
            "  device  —",
            Style::default().fg(Color::DarkGray),
        ))
    } else {
        Line::from(Span::styled(
            format!("  {}", parts.join("   ·   ")),
            Style::default().fg(Color::DarkGray),
        ))
    };

    f.render_widget(Paragraph::new(vec![tir_line, avg_line, dev_line]), inner);
}

/// Format a positive duration in ms as a compact age like `6d 4h` or `12m`.
fn fmt_age(ms: i64) -> String {
    let mins = ms.max(0) / 60_000;
    let days = mins / 1440;
    let hours = (mins % 1440) / 60;
    let m = mins % 60;
    if days > 0 {
        format!("{days}d {hours}h")
    } else if hours > 0 {
        format!("{hours}h {m}m")
    } else {
        format!("{m}m")
    }
}

fn draw_settings(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // header
            Constraint::Min(5),    // fields
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    let header = Paragraph::new(Line::from(Span::styled(
        " settings ",
        Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD),
    )))
    .block(Block::default().borders(Borders::ALL));
    f.render_widget(header, chunks[0]);

    let block = Block::default().borders(Borders::ALL);
    let inner = block.inner(chunks[1]);
    f.render_widget(block, chunks[1]);

    // Build display rows: a dim section header whenever the group changes,
    // then each field. Headers aren't selectable — navigation stays over
    // Field::ALL, so `settings_sel` still indexes fields directly.
    enum Row {
        Header(&'static str),
        Field(usize, Field),
    }
    let mut display: Vec<Row> = Vec::new();
    let mut last_group = "";
    for (i, &field) in Field::ALL.iter().enumerate() {
        let g = field.group();
        if g != last_group {
            display.push(Row::Header(g));
            last_group = g;
        }
        display.push(Row::Field(i, field));
    }

    // Scroll so the selected field (and ideally its header) stays visible.
    let height = inner.height.max(1) as usize;
    let sel_display = display
        .iter()
        .position(|r| matches!(r, Row::Field(i, _) if *i == app.settings_sel))
        .unwrap_or(0);
    let offset = if sel_display < height {
        0
    } else {
        (sel_display + 1 - height).min(display.len().saturating_sub(height))
    };

    let lines: Vec<Line> = display
        .iter()
        .skip(offset)
        .take(height)
        .map(|row| match row {
            Row::Header(name) => Line::from(Span::styled(
                format!(" {name}"),
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )),
            Row::Field(i, field) => {
                let selected = *i == app.settings_sel;
                let marker = if selected { "" } else { "   " };
                let style = if selected {
                    Style::default()
                        .fg(Color::Black)
                        .bg(Color::Cyan)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                };
                Line::from(Span::styled(
                    format!("{marker}{:<26}{}", field.label(), app.field_value(*field)),
                    style,
                ))
            }
        })
        .collect();
    f.render_widget(Paragraph::new(lines), inner);

    let footer = match &app.status {
        Some(msg) => Span::styled(format!(" {msg} "), Style::default().fg(Color::Green)),
        None => Span::raw(" ↑/↓ select · ←/→ change · w save · s/esc back · q quit "),
    };
    f.render_widget(Paragraph::new(Line::from(footer)), chunks[2]);
}

fn draw_banner(f: &mut Frame, area: Rect, app: &App) {
    let color = app.alert.color();
    let line = Line::from(Span::styled(
        format!("{} ", app.alert.label()),
        Style::default()
            .fg(Color::Black)
            .bg(color)
            .add_modifier(Modifier::BOLD),
    ));
    f.render_widget(
        Paragraph::new(line)
            .style(Style::default().bg(color))
            .alignment(Alignment::Center),
        area,
    );
}

fn draw_header(f: &mut Frame, area: Rect, app: &App) {
    let mode = if app.view.is_live() {
        Span::styled(" ● live ", Style::default().fg(Color::Green))
    } else {
        Span::styled(" ◷ history ", Style::default().fg(Color::Yellow))
    };
    let mut spans = vec![
        Span::styled(
            " sugarrush ",
            Style::default()
                .fg(Color::Magenta)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(format!(
            "· {} · {} ",
            app.units.label(),
            app.view.span.label()
        )),
        mode,
    ];
    if app.sites.len() > 1 {
        spans.push(Span::styled(
            format!(" [{}] ", app.active_site().name),
            Style::default().fg(Color::Blue),
        ));
    }
    if !app.online {
        let age = app
            .last_ok_ms
            .map(|t| {
                format!(
                    " (last {} ago)",
                    fmt_age(chrono::Utc::now().timestamp_millis() - t)
                )
            })
            .unwrap_or_default();
        spans.push(Span::styled(
            format!(" ⚠ offline — can't reach Nightscout{age} "),
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ));
    }
    let title = Line::from(spans);
    let p = Paragraph::new(title).block(Block::default().borders(Borders::ALL));
    f.render_widget(p, area);
}

fn draw_current(f: &mut Frame, area: Rect, app: &App) {
    let block = Block::default().borders(Borders::ALL).title(" current ");
    let inner = block.inner(area);
    f.render_widget(block, area);

    let Some(e) = app.latest() else {
        f.render_widget(Paragraph::new("  no data in this window…"), inner);
        return;
    };
    let value = app.units.format(e.sgv);
    let color = color_for(e.sgv, app);
    let info = current_info(app, e);
    let big_w = bigfont::width(&value);

    // Big number when there's room; compact single line otherwise.
    if inner.height as usize >= bigfont::ROWS && inner.width >= big_w + 24 {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(big_w + 3), Constraint::Min(0)])
            .split(inner);
        let big: Vec<Line> = bigfont::render(&value)
            .into_iter()
            .map(|l| {
                Line::from(Span::styled(
                    format!(" {l}"),
                    Style::default().fg(color).add_modifier(Modifier::BOLD),
                ))
            })
            .collect();
        f.render_widget(Paragraph::new(big), cols[0]);
        f.render_widget(Paragraph::new(info), cols[1]);
    } else {
        let mut lines = vec![Line::from(Span::styled(
            format!("  {}  {}", value, e.arrow()),
            Style::default().fg(color).add_modifier(Modifier::BOLD),
        ))];
        lines.extend(info.into_iter().skip(1)); // drop the unit/arrow line (already shown)
        f.render_widget(Paragraph::new(lines), inner);
    }
}

/// The secondary info lines beside/below the current value: unit + arrow,
/// delta, forecast ETA, and the timestamp.
fn current_info<'a>(app: &App, e: &crate::nightscout::Entry) -> Vec<Line<'a>> {
    let delta = app
        .delta_mgdl()
        .map(|d| {
            let sign = if d >= 0.0 { "+" } else { "-" };
            format!("{}{}", sign, app.units.format(d.abs()))
        })
        .unwrap_or_else(|| "--".into());
    let stamp = fmt_time(e.date);
    let when = if app.view.is_live() {
        format!("as of {stamp}")
    } else {
        format!("window end · {stamp}")
    };

    // Textual range label — legible without relying on color.
    let range = crate::alert::from_value(e.sgv, &app.alerts).label();
    let mut lines = vec![
        Line::from(Span::styled(
            format!(" {}  {}", app.units.label(), e.arrow()),
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::styled(
            format!(" {range}"),
            Style::default().fg(color_for(e.sgv, app)),
        )),
        Line::from(format!(" Δ {} {}", delta, app.units.label())),
    ];
    if let Some((rising, mins)) = app.prediction_eta(chrono::Utc::now().timestamp_millis()) {
        let (arrow, word, c) = if rising {
            ("", "high", app.theme.high)
        } else {
            ("", "low", app.theme.low)
        };
        lines.push(Line::from(Span::styled(
            format!(" {arrow} {word} in ~{mins} min"),
            Style::default().fg(c),
        )));
    }
    lines.push(Line::from(Span::styled(
        format!(" {when}"),
        Style::default().fg(Color::DarkGray),
    )));
    lines
}

fn draw_graph(f: &mut Frame, area: Rect, app: &App) {
    let title = format!(
        " {}{} ",
        fmt_time(app.view_start),
        fmt_time(app.view_end)
    );
    let block = Block::default().borders(Borders::ALL).title(title);

    if app.entries.is_empty() {
        f.render_widget(
            Paragraph::new("  no readings in this window…")
                .block(block)
                .alignment(Alignment::Left),
            area,
        );
        return;
    }

    // x = real timestamp (ms), y = value in current units.
    let points: Vec<(f64, f64)> = app
        .entries
        .iter()
        .rev()
        .map(|e| (e.date as f64, app.units.from_mgdl(e.sgv)))
        .collect();

    // Forecast series, anchored to the latest actual reading for continuity.
    let pred: Vec<(f64, f64)> = if app.predictions.is_empty() {
        Vec::new()
    } else {
        let anchor = app
            .latest()
            .map(|e| (e.date as f64, app.units.from_mgdl(e.sgv)));
        anchor
            .into_iter()
            .chain(
                app.predictions
                    .iter()
                    .map(|(t, mgdl)| (*t as f64, app.units.from_mgdl(*mgdl))),
            )
            .collect()
    };

    let (min_y, max_y) = points
        .iter()
        .chain(pred.iter())
        .fold((f64::MAX, f64::MIN), |(lo, hi), (_, y)| {
            (lo.min(*y), hi.max(*y))
        });
    let pad = ((max_y - min_y) * 0.1).max(app.units.from_mgdl(10.0));
    let bounds_y = [min_y - pad, max_y + pad];
    // Anchor x to the requested window; extend right to cover any forecast.
    let right = pred
        .last()
        .map(|(x, _)| *x as i64)
        .unwrap_or(app.view_end)
        .max(app.view_end);
    let bounds_x = [app.view_start as f64, right as f64];
    let mid_x = (app.view_start + right) / 2;

    // A dim vertical rule at the latest reading marks the boundary between
    // actual readings and the forecast — only when it's within the window.
    let now_line = app
        .latest()
        .map(|e| e.date as f64)
        .filter(|x| *x >= app.view_start as f64 && *x <= right as f64)
        .map(|x| [(x, bounds_y[0]), (x, bounds_y[1])]);

    // Treatment markers along the bottom: carbs and boluses on separate rows.
    let span_y = (bounds_y[1] - bounds_y[0]).max(1.0);
    let carb_pts: Vec<(f64, f64)> = app
        .treatments
        .iter()
        .filter(|t| t.carbs.is_some())
        .map(|t| (t.at_ms as f64, bounds_y[0] + span_y * 0.02))
        .collect();
    let bolus_pts: Vec<(f64, f64)> = app
        .treatments
        .iter()
        .filter(|t| t.insulin.is_some())
        .map(|t| (t.at_ms as f64, bounds_y[0] + span_y * 0.08))
        .collect();

    let (marker, gtype) = match app.graph_style {
        GraphStyle::Line => (symbols::Marker::Braille, GraphType::Line),
        GraphStyle::Dots => (symbols::Marker::Dot, GraphType::Scatter),
        GraphStyle::Blocks => (symbols::Marker::Block, GraphType::Scatter),
    };
    let mut datasets = vec![Dataset::default()
        .marker(marker)
        .graph_type(gtype)
        .style(Style::default().fg(app.theme.graph))
        .data(&points)];
    if let Some(nl) = &now_line {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(Color::DarkGray))
                .data(nl),
        );
    }
    if !carb_pts.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .graph_type(GraphType::Scatter)
                .style(Style::default().fg(Color::Yellow))
                .data(&carb_pts),
        );
    }
    if !bolus_pts.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Dot)
                .graph_type(GraphType::Scatter)
                .style(Style::default().fg(Color::Blue))
                .data(&bolus_pts),
        );
    }
    if !pred.is_empty() {
        datasets.push(
            Dataset::default()
                .marker(symbols::Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(app.theme.prediction))
                .data(&pred),
        );
    }

    let chart = Chart::new(datasets)
        .block(block)
        .x_axis(Axis::default().bounds(bounds_x).labels(vec![
            Span::raw(fmt_time(app.view_start)),
            Span::raw(fmt_time(mid_x)),
            Span::raw(fmt_time(right)),
        ]))
        .y_axis(Axis::default().bounds(bounds_y).labels(vec![
            Span::raw(format!("{:.1}", bounds_y[0])),
            Span::raw(format!("{:.1}", bounds_y[1])),
        ]));
    f.render_widget(chart, area);
}

fn draw_footer(f: &mut Frame, area: Rect, app: &App) {
    if let Some(buf) = &app.date_input {
        let line = Line::from(vec![
            Span::styled(
                " jump to date (YYYY-MM-DD): ",
                Style::default().fg(Color::Cyan),
            ),
            Span::styled(buf.clone(), Style::default().add_modifier(Modifier::BOLD)),
            Span::styled("_", Style::default().add_modifier(Modifier::SLOW_BLINK)),
            Span::raw("  · enter confirm · esc cancel"),
        ]);
        f.render_widget(Paragraph::new(line), area);
        return;
    }

    let text = match &app.last_error {
        Some(err) => Span::styled(format!(" error: {err} "), Style::default().fg(Color::Red)),
        None if app.perm_warning => Span::styled(
            " ⚠ config.toml is readable by others — run: chmod 600 ~/.config/sugarrush/config.toml ",
            Style::default().fg(Color::Yellow),
        ),
        None => {
            let mut s = String::from(
                " q quit · r refresh · u units · h/l pan · +/- zoom · g date · f live · s settings",
            );
            if app.sites.len() > 1 {
                s.push_str(" · n site");
            }
            if app.minimap_enabled {
                s.push_str(" · drag overview");
            }
            if app.alarm_active(chrono::Utc::now().timestamp_millis()) {
                s.push_str(" · a snooze");
            }
            s.push(' ');
            Span::raw(s)
        }
    };
    f.render_widget(Paragraph::new(Line::from(text)), area);
}

/// Format an epoch-ms timestamp as local `MM-DD HH:MM`.
fn fmt_time(ms: i64) -> String {
    match Local.timestamp_millis_opt(ms).single() {
        Some(dt) => dt.format("%m-%d %H:%M").to_string(),
        None => "--".into(),
    }
}

/// Colour a reading by configured thresholds and theme.
fn color_for(sgv: f64, app: &App) -> Color {
    let a = &app.alerts;
    let t = &app.theme;
    if sgv <= a.urgent_low || sgv >= a.urgent_high {
        t.urgent
    } else if sgv < a.low {
        t.low
    } else if sgv > a.high {
        t.high
    } else {
        t.in_range
    }
}