ebman 0.37.0

k9s-style TUI for AWS Elastic Beanstalk
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
//! Shared drawing vocabulary: blocks, pills, glyphs, colours and the
//! small formatters every panel reuses.
//!
//! Moved verbatim out of `src/ui.rs` (5,046 lines) in the 0.31 split;
//! visibility widened to `pub(crate)` where a sibling needs it, and
//! nothing else changed. `use super::*` picks up the shared vocabulary
//! the way `detail.rs` and `overlays.rs` already do.

use super::*;

pub(crate) const SPINNER_FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];
pub(crate) const ASCII_SPINNER: &[&str] = &["|", "/", "-", "\\"];

pub(crate) fn rounded_block(theme: &Theme, active: bool) -> Block<'static> {
    let color = if active {
        theme.border_active
    } else {
        theme.border_idle
    };
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(color))
}

pub(crate) fn titled_block(
    theme: &Theme,
    raw_title: &str,
    active: bool,
    accent: Color,
) -> Block<'static> {
    let trimmed = raw_title.trim();
    let decorated = match theme.icons {
        IconStyle::Ascii => format!("[ {trimmed} ]"),
        // U+E0B6 / U+E0B4: rounded powerline left/right caps frame the title
        // like a tab on a folder. Renders as boxes when the font isn't
        // installed; documented in the config description.
        IconStyle::Powerline => format!(" {trimmed} "),
        IconStyle::Unicode => format!("[ ◆ {trimmed} ◆ ]"),
    };
    rounded_block(theme, active).title(Span::styled(
        decorated,
        Style::default().fg(accent).add_modifier(Modifier::BOLD),
    ))
}

pub(crate) fn pill(text: &str, fg: Color, bg: Color) -> Span<'static> {
    Span::styled(
        format!(" {text} "),
        Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD),
    )
}

/// Glyph for the pending-actions pill, gated on the active icon style.
/// `⏳` (U+23F3) is unicode-only — operators on `icons = "ascii"`
/// terminals saw box-tofu before this; falls back to a `*` tag now.
pub(crate) fn pending_glyph(theme: &Theme) -> &'static str {
    match theme.icons {
        IconStyle::Ascii => "* ",
        _ => "",
    }
}

/// Pick the ascii fallback for a decorative glyph when the operator's
/// font can't render unicode (`icons = "ascii"` — the mode's contract
/// is "stays readable when the font lacks the glyphs", so raw literals
/// in draw paths are stragglers).
pub(crate) fn glyph<'a>(icons: IconStyle, unicode: &'a str, ascii: &'a str) -> &'a str {
    match icons {
        IconStyle::Ascii => ascii,
        _ => unicode,
    }
}

/// Glyph for the multi-select-active pill.
pub(crate) fn multi_select_glyph(theme: &Theme) -> &'static str {
    match theme.icons {
        IconStyle::Ascii => "+ ",
        _ => "",
    }
}

/// Glyph for the incident banner pill. `🚨` is unicode-only; ascii
/// terminals get a loud `!!` tag instead of tofu.
/// The armed-auto-rollback countdown pill.
///
/// Ascii form is `!` because this watcher *acts* — it redeploys the
/// previous version when the deadline passes. `watching_glyph` is the
/// one that only reports, and the two must stay distinguishable in
/// ascii for the same reason they use different glyphs and colours in
/// unicode.
/// How old a build has to be before the header suggests checking for
/// an update. Three months: long enough not to nag someone who
/// installed last week, short enough that a year-old build never sits
/// there unremarked.
pub(crate) const STALE_BUILD_DAYS: i64 = 90;

/// The build's identity for the header title — `ebman 0.35.0 · 2026-08-27`.
///
/// The date comes from `CHANGELOG.md` via `build.rs`. When it could not
/// be determined (a working tree whose `Cargo.toml` was bumped before
/// the changelog section was cut) the version is shown alone rather
/// than with a placeholder, because a title reading `ebman 0.35.0 ·
/// unknown` invites a bug report about the word "unknown".
pub(crate) fn version_title(theme: &Theme, available: u16) -> String {
    let version = env!("CARGO_PKG_VERSION");
    let short = format!("ebman {version}");
    let full = match release_date() {
        Some(date) => format!("{short} \u{b7} {date}"),
        None => short.clone(),
    };
    // `titled_block` wraps the title, and the block draws two borders.
    // The extra four keeps a few cells of border visible so the title
    // does not butt against the corner and read as clipped.
    let overhead = match theme.icons {
        IconStyle::Ascii => 4,     // `[ x ]`
        IconStyle::Powerline => 2, // ` x `
        IconStyle::Unicode => 8,   // `[ * x * ]`
    } + 2
        + 4;
    let fits = |s: &str| s.chars().count() + overhead <= available as usize;
    // Drop the date before letting it truncate: `ebman 0.35.0 \u{b7} 2026-08-2`
    // is worse than no date at all, and the title never truncated
    // before this carried anything but the word "ebman".
    if fits(&full) {
        full
    } else if fits(&short) {
        short
    } else {
        "ebman".to_string()
    }
}

/// The compiled-in release date, or `None` if `build.rs` could not find
/// one. Empty rather than absent because `cargo:rustc-env` always sets
/// the variable; it is the value that carries "unknown".
pub(crate) fn release_date() -> Option<&'static str> {
    let d = env!("EBMAN_RELEASE_DATE");
    (!d.is_empty()).then_some(d)
}

/// Whole days between this build's release date and `now`.
///
/// `None` when there is no date, or when the date is in the future —
/// which happens to anyone building from a checkout on the day of a
/// release in a timezone ahead of UTC, and is not a thing to warn
/// about.
pub(crate) fn build_age_days(
    release_date: &str,
    now: chrono::DateTime<chrono::Utc>,
) -> Option<i64> {
    let d = chrono::NaiveDate::parse_from_str(release_date, "%Y-%m-%d").ok()?;
    // chrono accepts `2026-8-27` for `%Y-%m-%d`; the build-time
    // validator in `release_meta` does not. Two validators that
    // disagree about what a date is, is the drift this codebase keeps
    // paying for, so require the canonical form by round-tripping
    // rather than by restating the shape rules here and letting the
    // copies diverge.
    if d.format("%Y-%m-%d").to_string() != release_date {
        return None;
    }
    let days = now.date_naive().signed_duration_since(d).num_days();
    (days >= 0).then_some(days)
}

pub(crate) fn rollback_timer_glyph(theme: &Theme) -> &'static str {
    match theme.icons {
        IconStyle::Ascii => "! ",
        _ => "",
    }
}

/// The watching-deploy countdown pill — reports the outcome, never
/// changes the env. See `rollback_timer_glyph` for why they differ.
pub(crate) fn watching_glyph(theme: &Theme) -> &'static str {
    match theme.icons {
        IconStyle::Ascii => "o ",
        _ => "👁 ",
    }
}

pub(crate) fn incident_glyph(theme: &Theme) -> &'static str {
    match theme.icons {
        IconStyle::Ascii => "!! ",
        _ => "🚨 ",
    }
}

pub(crate) fn health_dot(health: &str, theme: &Theme) -> Span<'static> {
    let c = health_color(health, theme);
    let glyph = match theme.icons {
        IconStyle::Ascii => "*",
        // U+F111 Nerd-Font solid circle reads identically to U+25CF in
        // Powerline-patched fonts but is part of the Nerd Font set, which
        // gives a tiny consistency win when the rest of the chrome uses
        // private-use glyphs.
        IconStyle::Powerline => "\u{f111}",
        IconStyle::Unicode => "",
    };
    Span::styled(glyph, Style::default().fg(c).add_modifier(Modifier::BOLD))
}

pub(crate) fn spinner(elapsed_ms: u128, icons: IconStyle) -> &'static str {
    match icons {
        // Powerline-targeted fonts include the braille range, so the same
        // animation reads well without needing a separate frame set.
        IconStyle::Unicode | IconStyle::Powerline => {
            SPINNER_FRAMES[(elapsed_ms / 100) as usize % SPINNER_FRAMES.len()]
        }
        IconStyle::Ascii => ASCII_SPINNER[(elapsed_ms / 100) as usize % ASCII_SPINNER.len()],
    }
}

pub(crate) fn tab_icon(t: DetailTab, icons: IconStyle) -> &'static str {
    match (icons, t) {
        (IconStyle::Unicode, DetailTab::Health) => "",
        (IconStyle::Unicode, DetailTab::Events) => "",
        (IconStyle::Unicode, DetailTab::Instances) => "",
        (IconStyle::Unicode, DetailTab::Metrics) => "",
        (IconStyle::Unicode, DetailTab::Queue) => "",
        (IconStyle::Unicode, DetailTab::Logs) => "",
        (IconStyle::Unicode, DetailTab::Config) => "",
        // Powerline / Nerd Font Material Design glyphs. Each is distinct so
        // the tab strip remains readable even when icons collapse onto a
        // single line in the boot splash / detail header.
        (IconStyle::Powerline, DetailTab::Health) => "\u{f02d1}", // heart-pulse
        (IconStyle::Powerline, DetailTab::Events) => "\u{f0e7}",  // flash
        (IconStyle::Powerline, DetailTab::Instances) => "\u{f048b}", // server
        (IconStyle::Powerline, DetailTab::Metrics) => "\u{f0680}", // chart-line
        (IconStyle::Powerline, DetailTab::Queue) => "\u{f01ee}",  // email-outline
        (IconStyle::Powerline, DetailTab::Logs) => "\u{f021a}",   // text-box
        (IconStyle::Powerline, DetailTab::Config) => "\u{f0493}", // cog
        // ASCII fallbacks: one letter per tab so each is distinguishable.
        (IconStyle::Ascii, DetailTab::Health) => "H",
        (IconStyle::Ascii, DetailTab::Events) => "E",
        (IconStyle::Ascii, DetailTab::Instances) => "I",
        (IconStyle::Ascii, DetailTab::Metrics) => "M",
        (IconStyle::Ascii, DetailTab::Queue) => "Q",
        (IconStyle::Ascii, DetailTab::Logs) => "L",
        (IconStyle::Ascii, DetailTab::Config) => "C",
    }
}

pub(crate) fn micro_bar(value: i64, max: i64, width: usize) -> String {
    // `value < 0` and the `full.min(width)` below are both redundant
    // given the `clamp(0.0, 1.0)`: a negative value clamps to 0.0 and
    // yields no glyphs, and `frac <= 1.0` bounds `full` by `width`. The
    // 2026-08-26 sweep reports both as survivable and is right.
    //
    // Kept anyway, and not as an oversight: they are belt-and-braces on
    // float arithmetic feeding a `usize` loop count, and deleting them
    // to move a mutation score would trade a real safety margin for a
    // number. `max <= 0` is NOT redundant — it guards the divide.
    if max <= 0 || width == 0 || value < 0 {
        return String::new();
    }
    let frac = (value as f64 / max as f64).clamp(0.0, 1.0);
    let total_eighths = (frac * (width as f64) * 8.0).round() as usize;
    let full = total_eighths / 8;
    let rem = total_eighths % 8;
    let mut out = String::new();
    for _ in 0..full.min(width) {
        out.push('');
    }
    if full < width && rem > 0 {
        out.push(match rem {
            1 => '',
            2 => '',
            3 => '',
            4 => '',
            5 => '',
            6 => '',
            7 => '',
            _ => ' ',
        });
    }
    out
}

pub(crate) const SPARKLINE_WIDTH: usize = 10;
/// How wide each divider fill string is. Ratatui truncates per-column, so any
/// value ≥ max column width works.
pub(crate) const DIVIDER_FILL_WIDTH: usize = 200;

/// Pure helper: pick a (start, end) window of indices to render such that
/// `cursor` is inside `[start, end)` and `end - start <= budget`. Window
/// stays as low as possible (anchor to top when items fit, slide down only
/// when the cursor passes the visible area). Used by the saved-configs
/// overlay's scroll logic and tested directly.
pub(crate) fn visible_window(cursor: usize, total: usize, budget: usize) -> (usize, usize) {
    if total == 0 {
        return (0, 0);
    }
    let budget = budget.max(1).min(total);
    if total <= budget {
        return (0, total);
    }
    // Slide so the cursor stays inside. If cursor is in the upper portion,
    // anchor to 0; if in the lower portion, end at total; otherwise centre.
    let half = budget / 2;
    let start = cursor.saturating_sub(half);
    let start = start.min(total - budget);
    (start, start + budget)
}

pub(crate) fn truncate_for_display(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let prefix: String = s.chars().take(max.saturating_sub(1)).collect();
    format!("{prefix}")
}

/// Pad a string to at least `width` chars with spaces. Uses
/// char-count rather than byte-count because Region / env names
/// can contain non-ASCII (rare but legal).
pub(crate) fn pad_right(s: &str, width: usize) -> String {
    let n = s.chars().count();
    if n >= width {
        s.to_string()
    } else {
        let mut out = String::with_capacity(width);
        out.push_str(s);
        for _ in 0..(width - n) {
            out.push(' ');
        }
        out
    }
}

pub(crate) fn humanize_duration(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m", secs / 60)
    } else if secs < 86_400 {
        format!("{}h{}m", secs / 3600, (secs % 3600) / 60)
    } else {
        format!("{}d{}h", secs / 86_400, (secs % 86_400) / 3600)
    }
}

pub(crate) fn kv<'a>(key: &'a str, value: &'a str, theme: &Theme) -> Vec<Span<'a>> {
    vec![
        Span::styled(format!("{key}: "), Style::default().fg(theme.muted)),
        Span::styled(
            value.to_string(),
            Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
        ),
    ]
}

/// The narrowest an overlay should be before it starts wrapping prose
/// into nonsense — unless the terminal itself is narrower.
///
/// 72 is the conventional comfortable reading measure, and it is what
/// the help keymap needs to keep a key and its description on one line.
pub(crate) const COMFORTABLE_OVERLAY_WIDTH: u16 = 72;

/// A centred overlay rect that does not waste a narrow terminal.
///
/// The shared `tui_common::centered_overlay` sizes by PERCENTAGE, which
/// is right on a wide screen and wrong on a small one: `OverlaySize::Text`
/// is 70%, so an 80-column terminal got a 56-cell overlay, left 24 cells
/// unused, and then wrapped the help keymap mid-description — the
/// continuation losing its indent, so no line said which key it belonged
/// to. The percentage exists to stop an overlay dominating a big screen;
/// that reasoning simply does not apply when the screen is small.
///
/// So: never narrower than [`COMFORTABLE_OVERLAY_WIDTH`], never wider
/// than the terminal less a small margin, and otherwise exactly what the
/// shared size table says. On a wide terminal this is a no-op, which is
/// why it wraps the shared helper rather than replacing it — pgman uses
/// the same table and this is an ebman-side judgement about narrow
/// terminals, not a change to the shared visual language.
pub(crate) fn overlay_rect(size: OverlaySize, area: Rect) -> Rect {
    let base = centered_overlay(size, area);
    let margin = 4;
    let floor = COMFORTABLE_OVERLAY_WIDTH.min(area.width.saturating_sub(margin));
    let want_w = base.width.max(floor);
    // Same argument vertically: a short overlay on a short terminal is
    // all scrollback and no content.
    let h_floor = 20u16.min(area.height.saturating_sub(margin));
    let want_h = base.height.max(h_floor);
    // Unreachable given the line above: `floor` is capped at
    // `area.width - margin` and `base` at 100% of the area, so `want_w`
    // is always already inside. Kept so the returned `Rect` is truthful
    // about where it will draw — a caller doing its own arithmetic from
    // it (as the help wrapping does) would otherwise be handed a width
    // that does not exist.
    //
    // NOT panic protection, which was the assumption worth checking:
    // removing BOTH this and the floor's own `.min()` renders fine at
    // 2x2, because ratatui clips an out-of-area Rect itself. Verified
    // rather than assumed.
    let w = want_w.min(area.width);
    let h = want_h.min(area.height);
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

/// How many `key: value` fields fit in `available` columns.
///
/// Fields are laid out in order with a separator between each, and the
/// answer is a count so the caller can render exactly the prefix that
/// fits. Always at least one — a header row showing nothing is worse
/// than one showing a clipped first field.
///
/// The point is to drop WHOLE fields. ratatui clips the right edge, so
/// an over-long row rendered `Account: 1234  \u{b7}  Region: eu-west-1
/// \u{b7}  Profile: ` — a label with its value cut off entirely, which
/// reads as "the profile is empty" rather than "this did not fit". Same
/// defect as a truncated release date in the title, and the same fix.
pub(crate) fn fields_that_fit(field_widths: &[usize], sep_width: usize, available: usize) -> usize {
    if field_widths.is_empty() {
        return 0;
    }
    let mut used = 0usize;
    let mut fitted = 0usize;
    for (i, w) in field_widths.iter().enumerate() {
        let extra = if i == 0 { *w } else { sep_width + *w };
        if used + extra > available {
            break;
        }
        used += extra;
        fitted += 1;
    }
    fitted.max(1)
}

/// Join field groups with separators, dropping whole groups that do not
/// fit `available` columns.
///
/// A group is one logical field — `kv("Region", …)`, or a label plus a
/// coloured pill, or anything else — and its width is measured from the
/// spans themselves, so a caller does not have to keep a parallel list
/// of widths in step with the spans. That matters here: the Detail
/// header rows mix `kv` pairs with status pills and health dots, and a
/// hand-maintained width table would be one more thing to get wrong.
///
/// Whole groups, never part of one. ratatui clips the right edge, which
/// is how the Detail header came to render `CNAME: api-pr` — a label
/// promising a value it then cut in half.
pub(crate) fn join_fields_to_fit<'a>(
    groups: Vec<Vec<Span<'a>>>,
    theme: &Theme,
    available: u16,
) -> Vec<Span<'a>> {
    let widths: Vec<usize> = groups
        .iter()
        .map(|g| g.iter().map(|s| s.content.chars().count()).sum())
        .collect();
    let keep = fields_that_fit(&widths, SEP_WIDTH, available as usize);
    let mut out: Vec<Span<'a>> = Vec::new();
    for (i, g) in groups.into_iter().take(keep).enumerate() {
        if i > 0 {
            out.push(sep(theme));
        }
        out.extend(g);
    }
    out
}

/// Trim a footer key-strip to whole hints.
///
/// Hints are separated by two spaces, and ratatui clips the right edge —
/// which left a bare key with its action gone, `r region  p`, reading as
/// a hint for a key called "p" that does nothing. A hint you cannot act
/// on is worse than one you cannot see, because it costs a keystroke to
/// find out.
///
/// Always keeps at least the first hint: a key strip is the only
/// discoverability surface in the TUI, and an empty one on a very narrow
/// terminal helps nobody.
pub(crate) fn hints_to_fit(line: &str, available: u16) -> String {
    let available = available as usize;
    if line.chars().count() <= available {
        return line.to_string();
    }
    // Split the TRIMMED line: the first hint carries the strip's own
    // leading space, and re-adding one below doubled the indent on
    // exactly the narrow terminals this exists to help.
    let hints: Vec<&str> = line
        .trim_start()
        .split("  ")
        .filter(|h| !h.is_empty())
        .collect();
    let mut out = String::new();
    for hint in &hints {
        // Only the non-first case can break — the first hint is always
        // kept — so there is no candidate length to compute for it. It
        // used to be computed anyway and thrown away, which meant the
        // arithmetic could be mutated freely with nothing to notice:
        // two permanently-surviving mutants standing for dead code
        // rather than a missing test.
        if !out.is_empty() && out.chars().count() + 2 + hint.chars().count() > available {
            break;
        }
        if out.is_empty() {
            out.push(' ');
        } else {
            out.push_str("  ");
        }
        out.push_str(hint);
    }
    // A single hint longer than the whole terminal is the one case where
    // clipping is unavoidable — there is no smaller whole unit to fall
    // back to. Do it here rather than leaving ratatui to, so the return
    // value always honours the width it was given and a caller can rely
    // on that.
    // `>` and `>=` are indistinguishable here — at exactly `available`,
    // `take(available)` is a no-op — so that mutant is equivalent and
    // will survive every sweep. Noted so the next triage does not spend
    // time on it.
    if out.chars().count() > available {
        out = out.chars().take(available).collect();
    }
    out
}

/// `sep` renders as five cells in every icon style.
pub(crate) const SEP_WIDTH: usize = 5;

pub(crate) fn sep(theme: &Theme) -> Span<'static> {
    // U+E0B1 — thin powerline separator — reads as a real divider in
    // Powerline-patched fonts and falls back to a tofu box otherwise.
    let glyph = if theme.icons == IconStyle::Powerline {
        "  \u{e0b1}  "
    } else {
        ""
    };
    Span::styled(glyph, Style::default().fg(theme.muted))
}

/// Pure: ASCII-case-insensitive "is `s` any of these?" predicate. Cheap
/// alternative to `s.to_lowercase().as_str()` matching against a fixed
/// option list — saves a per-call `String` allocation in the table-row
/// render hot path, where `health` / `status` strings come from AWS in
/// known-case form anyway.
pub(crate) fn ieq_any(s: &str, options: &[&str]) -> bool {
    options.iter().any(|o| s.eq_ignore_ascii_case(o))
}

/// Cursor / row-selection marker prepended to highlighted rows in lists +
/// tables. Powerline-mode users get the filled U+E0B0 right-triangle so
/// the marker matches the rest of the ribbon aesthetic; everyone else gets
/// the half-block ▌ that doesn't need a patched font.
pub(crate) fn cursor_marker(theme: &Theme) -> &'static str {
    if theme.icons == IconStyle::Powerline {
        "\u{e0b0} "
    } else {
        ""
    }
}

/// Insertion-point caret glyph used as the blinking cursor in the command
/// bar / filter bar / quick-jump bar / picker / typed-name confirm. ASCII
/// stays on `_` (no Unicode needed in low-feature terminals); everything
/// else uses U+258E (a thin vertical block) which actually reads as a
/// terminal cursor rather than an underscore character.
pub(crate) fn caret_glyph(theme: &Theme) -> &'static str {
    if theme.icons == IconStyle::Ascii {
        "_"
    } else {
        "\u{258e}"
    }
}

/// Render a single-line text input as `before-caret` + caret glyph +
/// `after-caret`, so the blinking caret sits at `cursor_col` (a char
/// offset) instead of always at the end. Shared by the `TextInput`-backed
/// input renderers (quickjump / palette / …) now that those inputs
/// support mid-string cursor movement. `cursor_col` past the end clamps
/// to the end (caret after all text).
pub(crate) fn input_caret_spans(
    text: &str,
    cursor_col: usize,
    text_style: Style,
    caret_style: Style,
    theme: &Theme,
) -> Vec<Span<'static>> {
    let byte = text
        .char_indices()
        .nth(cursor_col)
        .map(|(i, _)| i)
        .unwrap_or(text.len());
    let (before, after) = text.split_at(byte);
    vec![
        Span::styled(before.to_string(), text_style),
        Span::styled(caret_glyph(theme), caret_style),
        Span::styled(after.to_string(), text_style),
    ]
}

/// Pure: chevron used in the non-Powerline group-banner row to mark the
/// start of an app section (`── ▶ app-name ──`). Powerline mode renders
/// its own ribbon and never calls this — but we return a sensible glyph
/// anyway so the helper is total.
pub(crate) fn separator_glyph(icons: IconStyle) -> &'static str {
    match icons {
        IconStyle::Ascii => ">",
        // U+25B6 BLACK RIGHT-POINTING TRIANGLE — BMP, single-cell in every
        // standard monospace font. Mirrors the Powerline E0B0 wedge in
        // intent (forward direction, calls attention to the section break).
        _ => "",
    }
}

/// Warning glyph — `⚠ ` in unicode/powerline modes, `! ` in ascii so
/// `icons = "ascii"` operators don't get box-tofu instead. Caller
/// includes the trailing space.
pub(crate) fn warn_glyph(icons: IconStyle) -> &'static str {
    match icons {
        IconStyle::Ascii => "! ",
        _ => "",
    }
}

/// Hint / suggestion glyph — `💡 ` (lightbulb) in unicode/powerline,
/// `? ` in ascii. Used by context-aware footer hints (`:why` / `:alarms`
/// suggestions when the status slot is empty).
pub(crate) fn hint_glyph(icons: IconStyle) -> &'static str {
    match icons {
        IconStyle::Ascii => "? ",
        _ => "💡 ",
    }
}

/// "Newer platform version available" glyph — `↑` in unicode/powerline,
/// `^` in ascii. Flags stale platforms in the envs-table PLATFORM column.
pub(crate) fn stale_glyph(icons: IconStyle) -> &'static str {
    match icons {
        IconStyle::Ascii => "^",
        _ => "",
    }
}

/// Severity-stripe glyph for toast notification bodies. Half-block
/// `▎` in unicode/powerline, `|` in ascii.
pub(crate) fn stripe_glyph(icons: IconStyle) -> &'static str {
    match icons {
        IconStyle::Ascii => "|",
        _ => "",
    }
}

pub(crate) fn sparkline_for(
    samples: Option<&std::collections::VecDeque<String>>,
    theme: &Theme,
    pulse_last: bool,
) -> Line<'static> {
    let Some(samples) = samples else {
        return Line::from(Span::raw(" ".repeat(SPARKLINE_WIDTH)));
    };
    let pad = SPARKLINE_WIDTH.saturating_sub(samples.len());
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(SPARKLINE_WIDTH);
    if pad > 0 {
        spans.push(Span::raw(" ".repeat(pad)));
    }
    let start = samples.len().saturating_sub(SPARKLINE_WIDTH);
    let visible: Vec<&String> = samples.iter().skip(start).collect();
    let visible_len = visible.len();
    for (i, h) in visible.iter().enumerate() {
        let color = health_color(h, theme);
        // Two-tone styling so the cell reads as a coloured bar under
        // the row-highlight's `Modifier::REVERSED`. fg=full bright,
        // bg=darker shade — the swap flips to (darker fg, bright bg)
        // on the selected row, painting the bar in the darker shade.
        // Bar shape: `▇` is the lower 7/8 block, so the top 1/8 sliver
        // shows the bg colour as a darker cap (or a brighter cap on
        // the inverted highlighted row). Uniform across the bar — the
        // earlier dim-leading-third gradient added confusion without
        // operational signal (everything inside a 5-min window is
        // "recent" enough).
        let darker = scale_rgb(color, 0.6);
        let style = Style::default().fg(color).bg(darker);
        // Pulse the rightmost cell when the caller flagged a fresh
        // health transition — swap the block to a full-height `█` and
        // bold it so the change visually pops on the refresh that
        // landed it.
        let (glyph, style) = if pulse_last && i + 1 == visible_len {
            (
                "",
                style.add_modifier(Modifier::BOLD | Modifier::SLOW_BLINK),
            )
        } else {
            ("", style)
        };
        spans.push(Span::styled(glyph, style));
    }
    Line::from(spans)
}

/// Pure: scale an `Rgb` colour towards black by `factor` (clamped 0..=1).
/// Non-RGB inputs (e.g. terminal-named `Color::Red`) pass through unchanged
/// because there's no portable "darken by N%" for those. Used by the
/// sparkline two-tone styling so fg+bg pairs read as distinct shades on
/// both highlighted and unhighlighted rows.
pub(crate) fn scale_rgb(color: Color, factor: f32) -> Color {
    let factor = factor.clamp(0.0, 1.0);
    if let Color::Rgb(r, g, b) = color {
        Color::Rgb(
            (r as f32 * factor) as u8,
            (g as f32 * factor) as u8,
            (b as f32 * factor) as u8,
        )
    } else {
        color
    }
}

pub(crate) fn health_style(health: &str, theme: &Theme) -> Style {
    Style::default()
        .fg(health_color(health, theme))
        .add_modifier(Modifier::BOLD)
}

/// Pure: map an EB health bucket name (any case) to the theme's
/// corresponding palette colour. Allocation-free — extracted so the
/// per-row hot path doesn't pay a `to_lowercase` per cell.
pub(crate) fn health_color(health: &str, theme: &Theme) -> Color {
    if ieq_any(health, &["green", "ok"]) {
        theme.health_green
    } else if ieq_any(health, &["yellow", "warning"]) {
        theme.health_yellow
    } else if ieq_any(health, &["red", "severe", "degraded"]) {
        theme.health_red
    } else if ieq_any(health, &["grey", "gray", "info", "no data", "pending"]) {
        theme.health_grey
    } else {
        theme.text
    }
}

pub(crate) fn redact(value: &str, on: bool) -> String {
    if !on || value.is_empty() || value == "" {
        return value.to_string();
    }
    // Preserve length using full-block shaded characters.
    "".repeat(value.chars().count())
}