clauth 0.8.0

Manage multiple Claude Code accounts, monitor 5h/7d usage with configurable auto-switch and delegation with an MCP plugin. CLI + TUI.
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
//! Tokens tab — global Claude Code token usage read from `~/.claude`
//! (`stats-cache.json` + recent transcript top-up; see `crate::tokens`).
//!
//! Two views. The **dashboard** (landing page) is a fixed grid of bordered
//! cards — today, lifetime totals, daily trend, top models, token composition,
//! hour-of-day, and activity — so each metric reads on its own rather than as
//! one long scroll. The **Models** master-detail (reached with `⏎`) drills into
//! a single model. All figures are global across every model/provider Claude
//! Code has run — the on-disk pool is shared across clauth profiles, not
//! per-account.

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use super::super::app::{App, TokenFilter, TokenView};
use super::super::theme;
use super::format::fixed;
use super::panes::{
    draw_selector_list, picker_row, section_box, section_box_verbatim, selector_width,
};
use crate::pricing::PriceTable;
use crate::tokens::{ModelTokens, TokenStats, group_models, is_anthropic, model_display_name};

/// Key column width for label:value rows.
const KEY_W: usize = 8;
/// Wider key column for the spelled-out `cache read`/`cache write` rows
/// (composition card + per-model detail): `cache write` (11) + 1 trailing space,
/// so every label keeps a gap before its bar/value and the columns stay aligned.
const WIDE_KEY_W: usize = 12;
/// Block-glyph ramp for sparklines, low → high.
const SPARK: [char; 8] = ['', '', '', '', '', '', '', ''];
/// Hour-of-day card outer width: 24 hour buckets + 4 (border + 1-col padding
/// each side), so the fixed-width sparkline fills the box exactly.
const HOUR_BOX_W: u16 = 28;

pub(super) fn draw(frame: &mut Frame<'_>, area: Rect, app: &App) {
    match app.token_view {
        TokenView::Dashboard => draw_dashboard(frame, area, app),
        TokenView::Models => draw_models(frame, area, app),
    }
}

// ── shared formatters ──────────────────────────────────────────────────────

/// Compact human count: `2.74B`, `186M`, `33.7M`, `12.3K`, `945`.
fn fmt_count(n: u64) -> String {
    let f = n as f64;
    let (v, suffix) = if f >= 1e12 {
        (f / 1e12, "T")
    } else if f >= 1e9 {
        (f / 1e9, "B")
    } else if f >= 1e6 {
        (f / 1e6, "M")
    } else if f >= 1e3 {
        (f / 1e3, "K")
    } else {
        return n.to_string();
    };
    if v >= 100.0 {
        format!("{v:.0}{suffix}")
    } else if v >= 10.0 {
        format!("{v:.1}{suffix}")
    } else {
        format!("{v:.2}{suffix}")
    }
}

/// Group the integer part of non-negative `n` with `,` thousands separators,
/// keeping `decimals` fractional digits: `(12345.6, 2)` → `12,345.60`.
fn group_thousands(n: f64, decimals: usize) -> String {
    let s = format!("{n:.decimals$}");
    let (int, frac) = s.split_once('.').map_or((s.as_str(), ""), |(i, f)| (i, f));
    let digits = int.len();
    let mut out = String::with_capacity(digits + digits / 3 + 1 + frac.len());
    for (i, ch) in int.chars().enumerate() {
        if i > 0 && (digits - i) % 3 == 0 {
            out.push(',');
        }
        out.push(ch);
    }
    if !frac.is_empty() {
        out.push('.');
        out.push_str(frac);
    }
    out
}

/// Full USD with 2–3 decimal precision and `,`-grouped thousands: `$12,345.67`,
/// `$340.00`, `$12.50`, `$0.340`, `<$0.001`, `$0`. No K/M/B suffix — the whole
/// figure is shown, two decimals from a dollar up and three below.
fn fmt_money(usd: f64) -> String {
    if usd <= 0.0 {
        return "$0".to_string();
    }
    if usd >= 1.0 {
        format!("${}", group_thousands(usd, 2))
    } else {
        // Sub-dollar: 3 decimals. Format first, then floor — any positive value
        // that rounds to $0.000 (incl. 0.0005 under round-half-to-even) shows
        // `<$0.001` rather than a misleading zero.
        let s = format!("${usd:.3}");
        if s == "$0.000" {
            "<$0.001".to_string()
        } else {
            s
        }
    }
}

/// Cost value style — gives the API-equivalent figures one identity across the
/// tab, distinct from the accent-bold token headline.
fn money_style() -> Style {
    Style::default().fg(theme::accent_2_color())
}

/// A `label  $cost` row summing API-equivalent cost over `models`. Shows `—` when
/// no price table has loaded yet, and a trailing `+` when some models carry
/// tokens but no matching rate (so the figure is a floor, not a total).
fn cost_line(label: &str, prices: Option<&PriceTable>, models: &[ModelTokens]) -> Line<'static> {
    let value = match prices {
        Some(p) => {
            let (total, unpriced) = p.total_cost(models);
            let mut s = fmt_money(total);
            if unpriced > 0 {
                s.push('+');
            }
            s
        }
        None => "".to_string(),
    };
    Line::from(vec![key(label), Span::styled(value, money_style())])
}

/// `2026-01-18[...]` → `jan 18`. Degrades to the raw string when too short.
fn short_date(ymd: &str) -> String {
    const MONTHS: [&str; 12] = [
        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
    ];
    if ymd.len() < 10 {
        return ymd.to_string();
    }
    let month: usize = ymd[5..7].parse().unwrap_or(1);
    let day: u32 = ymd[8..10].parse().unwrap_or(0);
    let mon = MONTHS.get(month.saturating_sub(1)).copied().unwrap_or("?");
    format!("{mon} {day}")
}

/// Block-glyph sparkline over `vals`, scaled to the slice's own max.
fn sparkline(vals: &[u64]) -> String {
    let max = vals.iter().copied().max().unwrap_or(0);
    if max == 0 {
        return SPARK[0].to_string().repeat(vals.len());
    }
    vals.iter()
        .map(|&v| {
            let idx = ((v as f64 / max as f64) * 7.0).round() as usize;
            SPARK[idx.min(7)]
        })
        .collect()
}

/// `█`×filled + `░`×rest, `value` scaled against `max`, in `fill`.
fn hbar(value: u64, max: u64, width: usize, fill: Style) -> Vec<Span<'static>> {
    let filled = if max == 0 {
        0
    } else {
        (((value as f64 / max as f64) * width as f64).round() as usize).min(width)
    };
    vec![
        Span::styled("".repeat(filled), fill),
        Span::styled(
            "".repeat(width.saturating_sub(filled)),
            theme::line_strong(),
        ),
    ]
}

/// Fixed-width key span in the dim+bold label style — left-justified to `KEY_W`
/// so values/bars in adjacent rows line up regardless of label length.
fn key(label: &str) -> Span<'static> {
    Span::styled(format!("{label:<KEY_W$}"), theme::label())
}

/// Inner content width of a card (`section_box` border + 1-col horizontal padding).
fn inner_w(area: Rect) -> usize {
    (area.width as usize).saturating_sub(4)
}

/// Last `width`-bounded tail of a chronological slice (the recent days).
fn trail<T>(items: &[T], width: usize) -> &[T] {
    let n = items.len().min(width.max(1));
    &items[items.len().saturating_sub(n)..]
}

/// Total display columns of a span run.
fn span_w(spans: &[Span<'static>]) -> usize {
    spans.iter().map(|s| s.content.chars().count()).sum()
}

/// A row with `left` flush to the start and `right` flush to `width`, the gap
/// filled with spaces. cloudy-tui leans on alignment + color to separate facts,
/// not a `·` middot (that's reserved for banner/toast prose).
fn lr(left: Vec<Span<'static>>, right: Vec<Span<'static>>, width: usize) -> Line<'static> {
    let gap = width.saturating_sub(span_w(&left) + span_w(&right)).max(1);
    let mut spans = left;
    spans.push(Span::raw(" ".repeat(gap)));
    spans.extend(right);
    Line::from(spans)
}

/// A row with `spans` centered within `width`.
fn center(spans: Vec<Span<'static>>, width: usize) -> Line<'static> {
    let pad = width.saturating_sub(span_w(&spans)) / 2;
    let mut out = vec![Span::raw(" ".repeat(pad))];
    out.extend(spans);
    Line::from(out)
}

fn busiest_hour(hours: &[u64; 24]) -> Option<usize> {
    let (hour, &count) = hours.iter().enumerate().max_by_key(|&(_, c)| *c)?;
    (count > 0).then_some(hour)
}

/// A model's token count on the active basis: in+out, or +cache when `count_cache`.
fn model_metric(m: &ModelTokens, count_cache: bool) -> u64 {
    if count_cache { m.total() } else { m.in_out() }
}

/// Grouped models after the display filter, ranked DESC by the active basis
/// (so the bars descend by the value actually shown).
fn ranked_models(stats: &TokenStats, count_cache: bool, filter: TokenFilter) -> Vec<ModelTokens> {
    let mut g = group_models(&stats.models);
    g.retain(|m| filter.matches(&m.model));
    g.sort_unstable_by_key(|m| std::cmp::Reverse(model_metric(m, count_cache)));
    g
}

// ── dashboard view ─────────────────────────────────────────────────────────

fn draw_dashboard(frame: &mut Frame<'_>, area: Rect, app: &App) {
    let Some(stats) = app.token_stats.as_ref() else {
        let block = section_box("tokens", false, true);
        let inner = block.inner(area);
        frame.render_widget(block, area);
        let (msg, style) = if app.tokens_failed {
            ("~/.claude/stats-cache.json unreadable", theme::danger())
        } else {
            ("reading ~/.claude", theme::faint())
        };
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(msg, style))).style(theme::base()),
            inner,
        );
        return;
    };

    let count_cache = app.config().state.count_cache;
    let prices = app.price_table.as_ref();

    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(6), // today · total (incl. cost row)
            Constraint::Length(4), // daily
            Constraint::Length(7), // top models · composition
            Constraint::Min(4),    // hour · activity
        ])
        .split(area);

    let top = halves(rows[0], 42);
    // Today's date → the today card's title-right meta badge.
    let today_meta = stats.today.as_ref().map(|t| short_date(&t.date));
    card(
        frame,
        top[0],
        "today",
        today_meta.as_deref(),
        true,
        today_lines(stats, inner_w(top[0]), count_cache, prices),
    );
    card(
        frame,
        top[1],
        "total",
        None,
        false,
        total_lines(stats, inner_w(top[1]), count_cache, prices),
    );

    // Freshness badge → the daily card's title-right meta slot.
    let fresh = stats
        .topped_up_through
        .as_deref()
        .map(|d| format!("live thru {}", short_date(d)));
    card(
        frame,
        rows[1],
        "daily",
        fresh.as_deref(),
        false,
        daily_lines(stats, inner_w(rows[1])),
    );

    let mid = halves(rows[2], 55);
    // The active model filter shows as the card's title-right meta badge.
    card(
        frame,
        mid[0],
        "top models",
        app.token_filter.badge(),
        false,
        model_lines(
            stats,
            inner_w(mid[0]),
            5,
            count_cache,
            prices,
            app.token_filter,
        ),
    );
    card(
        frame,
        mid[1],
        "composition",
        None,
        false,
        comp_lines(stats, inner_w(mid[1])),
    );

    // Hour graph is a fixed 24-bucket sparkline (one cell/hour). Pin its box to
    // 24 + 4 (border + 1-col padding each side) so the graph fills it with no
    // gap; activity takes the rest and shows more history on wide terminals.
    let bot = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Length(HOUR_BOX_W), Constraint::Min(0)])
        .split(rows[3]);
    card(
        frame,
        bot[0],
        "hour of day",
        None,
        false,
        hour_lines(stats, inner_w(bot[0])),
    );
    card(
        frame,
        bot[1],
        "activity",
        None,
        false,
        activity_lines(stats, inner_w(bot[1])),
    );
}

/// Split a row into two columns, the left taking `left_pct` percent.
fn halves(area: Rect, left_pct: u16) -> std::rc::Rc<[Rect]> {
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(left_pct),
            Constraint::Percentage(100 - left_pct),
        ])
        .split(area)
}

/// Draw one bordered card with its lines. `meta` (if any) renders as a
/// right-aligned title badge (the cloudy-tui title-right meta slot).
fn card(
    frame: &mut Frame<'_>,
    area: Rect,
    title: &str,
    meta: Option<&str>,
    first: bool,
    lines: Vec<Line<'static>>,
) {
    let mut block = section_box(title, false, first);
    if let Some(m) = meta {
        block = block.title(
            Line::from(Span::styled(format!(" {m} "), theme::dim())).alignment(Alignment::Right),
        );
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    frame.render_widget(Paragraph::new(lines).style(theme::base()), inner);
}

fn today_lines(
    stats: &TokenStats,
    w: usize,
    count_cache: bool,
    prices: Option<&PriceTable>,
) -> Vec<Line<'static>> {
    let Some(t) = stats.today.as_ref() else {
        return vec![Line::from(Span::styled(
            "idle so far today",
            theme::faint(),
        ))];
    };
    let tokens = if count_cache { t.total() } else { t.in_out() };
    vec![
        kv_accent("tokens", fmt_count(tokens)),
        cost_line("cost", prices, &t.models),
        Line::from(vec![
            key("msgs"),
            Span::styled(t.messages.to_string(), theme::body()),
        ]),
        lr(
            vec![Span::styled(
                format!("{} in", fmt_count(t.input)),
                theme::dim(),
            )],
            vec![Span::styled(
                format!("{} out", fmt_count(t.output)),
                theme::dim(),
            )],
            w,
        ),
    ]
}

fn total_lines(
    stats: &TokenStats,
    w: usize,
    count_cache: bool,
    prices: Option<&PriceTable>,
) -> Vec<Line<'static>> {
    let last = stats
        .topped_up_through
        .as_deref()
        .or(stats.daily.last().map(|d| d.date.as_str()))
        .or(stats.last_computed_date.as_deref());
    let total = if count_cache {
        stats.total_tokens()
    } else {
        stats.total_in_out()
    };
    let mut lines = vec![
        lr(
            vec![
                key("tokens"),
                Span::styled(
                    fmt_count(total),
                    theme::accent().add_modifier(Modifier::BOLD),
                ),
            ],
            vec![Span::styled(
                format!("{:.0}% cached", stats.cache_hit_ratio() * 100.0),
                Style::default().fg(theme::info_color()),
            )],
            w,
        ),
        cost_line("cost", prices, &stats.models),
        lr(
            vec![Span::styled(
                format!("{} sess", stats.total_sessions),
                theme::body(),
            )],
            vec![Span::styled(
                format!("{} msgs", fmt_count(stats.total_messages)),
                theme::body(),
            )],
            w,
        ),
    ];
    if let (Some(first), Some(latest)) = (stats.first_session_date.as_deref(), last) {
        lines.push(lr(
            vec![Span::styled(short_date(first), theme::dim())],
            vec![Span::styled(short_date(latest), theme::dim())],
            w,
        ));
    }
    lines
}

fn daily_lines(stats: &TokenStats, w: usize) -> Vec<Line<'static>> {
    let vals: Vec<u64> = trail(&stats.daily, w).iter().map(|d| d.tokens).collect();
    if vals.is_empty() {
        return vec![Line::from(Span::styled("no daily data", theme::faint()))];
    }
    let (peak_v, peak_d) = stats
        .daily
        .iter()
        .max_by_key(|d| d.tokens)
        .map(|d| (d.tokens, d.date.clone()))
        .unwrap_or((0, String::new()));
    vec![
        center(vec![Span::styled(sparkline(&vals), theme::accent())], w),
        center(
            vec![Span::styled(
                format!("peak {} {}", fmt_count(peak_v), short_date(&peak_d)),
                theme::faint(),
            )],
            w,
        ),
    ]
}

fn model_lines(
    stats: &TokenStats,
    w: usize,
    n: usize,
    count_cache: bool,
    prices: Option<&PriceTable>,
    filter: TokenFilter,
) -> Vec<Line<'static>> {
    let grouped = ranked_models(stats, count_cache, filter);
    if grouped.is_empty() {
        return vec![Line::from(Span::styled(
            "no models match the filter",
            theme::faint(),
        ))];
    }
    let max = grouped
        .first()
        .map(|m| model_metric(m, count_cache))
        .unwrap_or(0);
    let names: Vec<String> = grouped
        .iter()
        .take(n)
        .map(|m| model_display_name(&m.model))
        .collect();
    // Token-count strings, right-aligned to a shared column so the counts (and
    // the cost suffix after them) form clean vertical columns across rows.
    let counts: Vec<String> = grouped
        .iter()
        .take(n)
        .map(|m| fmt_count(model_metric(m, count_cache)))
        .collect();
    let count_w = counts.iter().map(|s| s.chars().count()).max().unwrap_or(3);
    // Per-model API-equivalent cost suffix (empty when unpriced / not loaded),
    // right-aligned to its own shared column.
    let costs: Vec<String> = grouped
        .iter()
        .take(n)
        .map(|m| {
            prices
                .and_then(|p| p.cost(m))
                .map(fmt_money)
                .unwrap_or_default()
        })
        .collect();
    let cost_w = costs.iter().map(|s| s.chars().count()).max().unwrap_or(0);
    // Only carry the cost column when the card is wide enough for label + a
    // minimum bar + the count + cost; otherwise drop it (token bars stay legible
    // on narrow terminals rather than clipping). `cost_col` includes its gap.
    let cost_col = if cost_w > 0 { cost_w + 1 } else { 0 };
    let show_cost = cost_col > 0 && w >= 6 + 2 + 8 + count_w + cost_col;
    let cost_col = if show_cost { cost_col } else { 0 };

    // Expand the label column to the longest name when there's room; only
    // truncate (via `fixed`) when the card is too narrow. Reserve the count
    // column + two 1-cell gaps + a minimum 8-cell bar + the cost column.
    let longest = names.iter().map(|s| s.chars().count()).max().unwrap_or(6);
    let max_label = w.saturating_sub(count_w + 2 + 8 + cost_col);
    let label_w = longest.clamp(6, max_label.max(6));
    let bar_w = w
        .saturating_sub(label_w)
        .saturating_sub(count_w + 2 + cost_col)
        .clamp(4, 30);
    grouped
        .iter()
        .take(n)
        .zip(names.iter())
        .zip(counts.iter())
        .zip(costs.iter())
        .map(|(((m, name), count), cost)| {
            let fill = if is_anthropic(&m.model) {
                theme::accent()
            } else {
                theme::dim()
            };
            let val = model_metric(m, count_cache);
            let mut spans = vec![
                Span::styled(fixed(name, label_w), theme::body()),
                Span::raw(" "),
            ];
            spans.extend(hbar(val, max, bar_w, fill));
            spans.push(Span::styled(format!(" {count:>count_w$}"), theme::dim()));
            if show_cost {
                spans.push(Span::styled(format!(" {cost:>cost_w$}"), money_style()));
            }
            Line::from(spans)
        })
        .collect()
}

fn comp_lines(stats: &TokenStats, w: usize) -> Vec<Line<'static>> {
    let grand = stats.total_tokens();
    let bar_w = w.saturating_sub(WIDE_KEY_W).saturating_sub(6).clamp(4, 28);
    [
        ("input", stats.total_input, theme::accent()),
        ("output", stats.total_output, theme::success()),
        ("cache write", stats.total_cache_create, theme::warning()),
        ("cache read", stats.total_cache_read, theme::info()),
    ]
    .into_iter()
    .map(|(label, value, fill)| {
        let pct = if grand == 0 {
            0.0
        } else {
            value as f64 / grand as f64 * 100.0
        };
        let mut spans = vec![Span::styled(
            format!("{label:<WIDE_KEY_W$}"),
            theme::label(),
        )];
        spans.extend(hbar(value, grand, bar_w, fill));
        spans.push(Span::styled(format!(" {pct:>3.0}%"), theme::dim()));
        Line::from(spans)
    })
    .collect()
}

fn hour_lines(stats: &TokenStats, w: usize) -> Vec<Line<'static>> {
    // Centered 24-bucket sparkline with the busiest hour centered below it.
    let peak = busiest_hour(&stats.hour_counts)
        .map(|h| format!("peak {h:02}:00"))
        .unwrap_or_default();
    vec![
        center(
            vec![Span::styled(sparkline(&stats.hour_counts), theme::accent())],
            w,
        ),
        center(vec![Span::styled(peak, theme::faint())], w),
    ]
}

fn activity_lines(stats: &TokenStats, w: usize) -> Vec<Line<'static>> {
    let msgs: Vec<u64> = trail(&stats.activity, w)
        .iter()
        .map(|a| a.messages)
        .collect();
    if msgs.is_empty() {
        return vec![Line::from(Span::styled("no activity data", theme::faint()))];
    }
    let peak_msgs = stats.activity.iter().map(|a| a.messages).max().unwrap_or(0);
    let peak_sess = stats.activity.iter().map(|a| a.sessions).max().unwrap_or(0);
    let tools: u64 = stats.activity.iter().map(|a| a.tool_calls).sum();
    vec![
        center(vec![Span::styled(sparkline(&msgs), theme::accent())], w),
        center(
            vec![Span::styled(
                format!(
                    "peak {} msgs   {peak_sess} sess   {} tools",
                    fmt_count(peak_msgs),
                    fmt_count(tools),
                ),
                theme::faint(),
            )],
            w,
        ),
    ]
}

/// `key:value` line whose value is the accent-bold headline number.
fn kv_accent(label: &str, value: String) -> Line<'static> {
    Line::from(vec![
        key(label),
        Span::styled(value, theme::accent().add_modifier(Modifier::BOLD)),
    ])
}

// ── models master-detail view ──────────────────────────────────────────────

fn draw_models(frame: &mut Frame<'_>, area: Rect, app: &App) {
    let cols = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length(selector_width(area.width)),
            Constraint::Min(20),
        ])
        .split(area);

    let count_cache = app.config().state.count_cache;
    let grouped = app
        .token_stats
        .as_ref()
        .map(|s| ranked_models(s, count_cache, app.token_filter))
        .unwrap_or_default();
    let sel = app.token_model_cursor.min(grouped.len().saturating_sub(1));

    // The selector title carries the filter so the narrowed list reads as such.
    let title = match app.token_filter.badge() {
        Some(badge) => format!("models  {badge}"),
        None => "models".to_string(),
    };
    // A filter can empty the list mid-view (menu on the Models view) —
    // `draw_selector_list`'s shared empty state talks about accounts, so
    // render the filter-specific message instead.
    if grouped.is_empty() {
        let block = section_box(&title, true, true);
        let inner = block.inner(cols[0]);
        frame.render_widget(block, cols[0]);
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled(
                "no models match the filter",
                theme::faint(),
            )))
            .style(theme::base()),
            inner,
        );
        draw_model_detail(frame, cols[1], None, 0, app.price_table.as_ref());
        return;
    }
    draw_selector_list(frame, cols[0], &title, true, sel, |w| {
        grouped
            .iter()
            .enumerate()
            .map(|(i, m)| {
                let style = if is_anthropic(&m.model) {
                    Style::default().fg(theme::text_color())
                } else {
                    theme::dim()
                };
                picker_row(i == sel, true, model_display_name(&m.model), style, w)
            })
            .collect()
    });

    let grand = app
        .token_stats
        .as_ref()
        .map(TokenStats::total_tokens)
        .unwrap_or(0);
    draw_model_detail(
        frame,
        cols[1],
        grouped.get(sel),
        grand,
        app.price_table.as_ref(),
    );
}

fn draw_model_detail(
    frame: &mut Frame<'_>,
    area: Rect,
    model: Option<&ModelTokens>,
    grand: u64,
    prices: Option<&PriceTable>,
) {
    let title = model
        .map(|m| model_display_name(&m.model))
        .unwrap_or_else(|| "model".to_string());
    let block = section_box_verbatim(&title, false, false);
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let Some(m) = model else {
        frame.render_widget(
            Paragraph::new(Line::from(Span::styled("no model data", theme::faint())))
                .style(theme::base()),
            inner,
        );
        return;
    };

    // This block carries the spelled-out `cache read`/`cache write` rows, so it
    // pads to WIDE_KEY_W (not the shared KEY_W) to keep the value column aligned.
    let kv = |label: &str, value: String| {
        Line::from(vec![
            Span::styled(format!("{label:<WIDE_KEY_W$}"), theme::label()),
            Span::styled(value, theme::body()),
        ])
    };
    let mut lines = vec![
        kv("input", fmt_count(m.input)),
        kv("output", fmt_count(m.output)),
        kv("cache read", fmt_count(m.cache_read)),
        kv("cache write", fmt_count(m.cache_create)),
        Line::from(""),
        Line::from(vec![
            Span::styled(format!("{:<WIDE_KEY_W$}", "total"), theme::label()),
            Span::styled(
                fmt_count(m.total()),
                theme::accent().add_modifier(Modifier::BOLD),
            ),
        ]),
        kv("io", fmt_count(m.in_out())),
    ];

    // API-equivalent cost, split by token bucket (rates differ per bucket).
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "COST · API-EQUIVALENT",
        theme::label(),
    )));
    match prices {
        None => lines.push(Line::from(Span::styled("rates loading", theme::faint()))),
        Some(p) => match p.rate(&m.model) {
            None => lines.push(Line::from(Span::styled(
                "no rate for this model",
                theme::faint(),
            ))),
            Some(r) => {
                let c_in = m.input as f64 * r.input;
                let c_out = m.output as f64 * r.output;
                let c_cache =
                    m.cache_read as f64 * r.cache_read + m.cache_create as f64 * r.cache_write;
                // Cost values share the `money_style` identity (vs the body-styled
                // token counts above).
                let cost_kv = |label: &str, value: String| {
                    Line::from(vec![key(label), Span::styled(value, money_style())])
                };
                lines.push(cost_kv("input", fmt_money(c_in)));
                lines.push(cost_kv("output", fmt_money(c_out)));
                lines.push(cost_kv("cache", fmt_money(c_cache)));
                lines.push(Line::from(vec![
                    key("total"),
                    Span::styled(
                        fmt_money(c_in + c_out + c_cache),
                        money_style().add_modifier(Modifier::BOLD),
                    ),
                ]));
            }
        },
    }

    let bar_w = (inner.width as usize).saturating_sub(14).clamp(6, 36);

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "SHARE OF ALL TOKENS",
        theme::label(),
    )));
    let share = if grand == 0 {
        0.0
    } else {
        m.total() as f64 / grand as f64 * 100.0
    };
    let mut share_line = hbar(m.total(), grand, bar_w, theme::accent());
    share_line.push(Span::styled(format!(" {share:>4.1}%"), theme::dim()));
    lines.push(Line::from(share_line));

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled("CACHE HIT", theme::label())));
    let denom = m.cache_read + m.cache_create + m.input;
    let hit = if denom == 0 {
        0.0
    } else {
        m.cache_read as f64 / denom as f64
    };
    let mut hit_line = hbar(
        (hit * 100.0) as u64,
        100,
        bar_w,
        Style::default().fg(theme::info_color()),
    );
    hit_line.push(Span::styled(
        format!(" {:>3.0}%", hit * 100.0),
        theme::dim(),
    ));
    lines.push(Line::from(hit_line));

    frame.render_widget(Paragraph::new(lines).style(theme::base()), inner);
}