quotas 0.5.0

CLI that auto-detects AI provider credentials (Claude, Codex, MiniMax, Kimi, Z.ai) and shows your usage quotas in a TUI or JSON.
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
use super::detail::DetailView;
use super::provider_card::ProviderCard;
use crate::providers::{ProviderKind, ProviderResult, ProviderStatus, QuotaWindow};
use chrono::Utc;
use ratatui::layout::Rect;
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use std::cell::Cell;

#[derive(Clone, Copy)]
pub enum Direction {
    Left,
    Right,
    Up,
    Down,
}

#[derive(Clone)]
pub enum ProviderEntry {
    Loading,
    Done(ProviderResult),
}

const SPINNER: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];

const MIN_CARD_W: u16 = 28;
const MIN_CARD_H: u16 = 7;

#[derive(Clone, Copy, Default)]
struct GridLayout {
    cols: usize,
    per_page: usize,
}

pub struct Dashboard {
    pub kinds: Vec<ProviderKind>,
    pub entries: Vec<ProviderEntry>,
    pub selected_index: usize,
    pub show_detail: bool,
    pub spinner_frame: usize,
    last_layout: Cell<GridLayout>,
}

impl Dashboard {
    pub fn new_loading(kinds: Vec<ProviderKind>) -> Self {
        let entries = kinds.iter().map(|_| ProviderEntry::Loading).collect();
        Self {
            kinds,
            entries,
            selected_index: 0,
            show_detail: false,
            spinner_frame: 0,
            last_layout: Cell::new(GridLayout::default()),
        }
    }

    pub fn update(&mut self, idx: usize, result: ProviderResult) {
        if idx < self.entries.len() {
            self.entries[idx] = ProviderEntry::Done(result);
        }
    }

    pub fn reset_loading(&mut self) {
        for e in &mut self.entries {
            *e = ProviderEntry::Loading;
        }
    }

    pub fn tick_spinner(&mut self) {
        self.spinner_frame = (self.spinner_frame + 1) % SPINNER.len();
    }

    pub fn all_loaded(&self) -> bool {
        self.entries
            .iter()
            .all(|e| matches!(e, ProviderEntry::Done(_)))
    }

    pub fn selected_provider(&self) -> Option<&ProviderResult> {
        match self.entries.get(self.selected_index)? {
            ProviderEntry::Done(r) => Some(r),
            ProviderEntry::Loading => None,
        }
    }

    fn current_page(&self) -> usize {
        let layout = self.last_layout.get();
        if layout.per_page == 0 {
            0
        } else {
            self.selected_index / layout.per_page
        }
    }

    pub fn navigate(&mut self, dir: Direction) {
        if self.entries.is_empty() {
            return;
        }
        let layout = self.last_layout.get();
        if layout.cols == 0 || layout.per_page == 0 {
            return;
        }
        let total = self.entries.len();
        let page = self.current_page();
        let page_start = page * layout.per_page;
        let page_end = (page_start + layout.per_page).min(total);
        let page_count = page_end - page_start;
        let in_page_idx = self.selected_index - page_start;
        let cols = layout.cols.min(page_count.max(1));
        let rows_in_page = page_count.div_ceil(cols);
        let col = in_page_idx % cols;
        let row = in_page_idx / cols;

        match dir {
            Direction::Left => {
                if col > 0 {
                    self.selected_index -= 1;
                } else if page > 0 {
                    let prev_end = page * layout.per_page;
                    self.selected_index = prev_end - 1;
                }
            }
            Direction::Right => {
                if in_page_idx + 1 < page_count && col + 1 < cols {
                    self.selected_index += 1;
                } else if page_end < total {
                    self.selected_index = page_end;
                }
            }
            Direction::Up => {
                if row > 0 {
                    self.selected_index -= cols;
                }
            }
            Direction::Down => {
                if row + 1 < rows_in_page {
                    let candidate = self.selected_index + cols;
                    if candidate < page_end {
                        self.selected_index = candidate;
                    } else {
                        self.selected_index = page_end - 1;
                    }
                }
            }
        }
    }

    pub fn render(&self, f: &mut Frame) {
        if self.show_detail {
            self.render_detail(f);
        } else {
            self.render_grid(f);
        }
    }

    fn compute_layout(&self, grid_area: Rect) -> GridLayout {
        let n = self.entries.len().max(1);
        let max_cols = (grid_area.width / MIN_CARD_W).max(1) as usize;
        let max_rows = (grid_area.height / MIN_CARD_H).max(1) as usize;
        let per_page = (max_cols * max_rows).max(1);

        if n <= per_page {
            // Choose cols balancing terminal aspect
            // Aim for roughly square cells visually: chars are ~2:1 tall:wide,
            // so pick cols so that cols/rows ≈ grid_w / (grid_h * 2).
            let aspect = (grid_area.width as f64) / (grid_area.height as f64 * 2.0).max(1.0);
            let mut best_cols = 1usize.max(n.min(max_cols));
            let mut best_score = f64::MAX;
            for c in 1..=n.min(max_cols) {
                let r = n.div_ceil(c);
                if r > max_rows {
                    continue;
                }
                let ratio = (c as f64) / (r as f64);
                let score = (ratio - aspect).abs();
                if score < best_score {
                    best_score = score;
                    best_cols = c;
                }
            }
            let cols = best_cols;
            GridLayout { cols, per_page: n }
        } else {
            // Paginate: use max_cols × max_rows
            GridLayout {
                cols: max_cols,
                per_page,
            }
        }
    }

    fn render_grid(&self, f: &mut Frame) {
        let area = f.area();

        if self.entries.is_empty() {
            let paragraph = Paragraph::new(
                "No providers configured. Set API keys via environment variables or config files.",
            )
            .block(Block::new().borders(Borders::ALL).title("quotas"));
            f.render_widget(paragraph, area);
            return;
        }

        let title_h = 2;
        let footer_h = 1;
        let title_area = Rect::new(area.x, area.y, area.width, title_h);
        let grid_area = Rect::new(
            area.x,
            area.y + title_h,
            area.width,
            area.height.saturating_sub(title_h + footer_h),
        );
        let footer_area = Rect::new(
            area.x,
            area.y + area.height.saturating_sub(footer_h),
            area.width,
            footer_h,
        );

        let layout = self.compute_layout(grid_area);
        self.last_layout.set(layout);

        let total = self.entries.len();
        let page = self.current_page();
        let pages = total.div_ceil(layout.per_page.max(1));
        let page_start = page * layout.per_page;
        let page_end = (page_start + layout.per_page).min(total);

        let loading_count = self
            .entries
            .iter()
            .filter(|e| matches!(e, ProviderEntry::Loading))
            .count();

        let mut header_line = vec![Span::raw(" quotas ").bold().white()];
        if loading_count > 0 {
            header_line.push(Span::raw("  "));
            header_line.push(
                Span::raw(format!(
                    "{} fetching {} provider{}…",
                    SPINNER[self.spinner_frame],
                    loading_count,
                    if loading_count == 1 { "" } else { "s" }
                ))
                .cyan(),
            );
        }
        if pages > 1 {
            header_line.push(Span::raw("   "));
            header_line.push(Span::raw(format!("page {}/{}", page + 1, pages)).dim());
        }
        let title = Paragraph::new(vec![
            Line::from(header_line),
            Line::from(vec![
                Span::raw(" ←↑↓→ Nav  Enter Detail  R Refresh  C Copy  PgUp/PgDn Page  Q Quit  · ")
                    .dim(),
                Span::raw("┃").white().bold(),
                Span::raw(" = time elapsed ").dim(),
            ]),
        ])
        .block(Block::new().borders(Borders::NONE));
        f.render_widget(title, title_area);

        let footer = Paragraph::new(format!(
            "{} of {} providers loaded",
            total - loading_count,
            total
        ))
        .style(Style::new().dim());
        f.render_widget(footer, footer_area);

        let page_count = page_end - page_start;
        let cols = layout.cols.min(page_count.max(1));
        let rows = page_count.div_ceil(cols);

        // Row heights are weighted by the max content weight of any card in
        // that row, so a row containing a minimax card with 10 windows gets
        // more vertical space than a row of single-window zai/claude cards.
        let mut row_weights: Vec<u32> = vec![1; rows];
        for (i, entry_idx) in (page_start..page_end).enumerate() {
            let row_i = i / cols;
            let w = Self::card_weight(&self.entries[entry_idx]);
            if w > row_weights[row_i] {
                row_weights[row_i] = w;
            }
        }
        let total_weight: u32 = row_weights.iter().sum::<u32>().max(1);
        let row_constraints: Vec<Constraint> = row_weights
            .iter()
            .map(|w| Constraint::Ratio(*w, total_weight))
            .collect();
        let row_rects = Layout::vertical(row_constraints).split(grid_area);

        for (i, entry_idx) in (page_start..page_end).enumerate() {
            let col_i = i % cols;
            let row_i = i / cols;
            let row_area = row_rects[row_i];
            let col_w = row_area.width / cols as u16;
            let x = row_area.x + col_i as u16 * col_w;
            let card_area = Rect::new(x, row_area.y, col_w.saturating_sub(1), row_area.height);
            let selected = entry_idx == self.selected_index;
            self.render_entry(f, entry_idx, selected, card_area);
        }
    }

    fn card_weight(entry: &ProviderEntry) -> u32 {
        match entry {
            ProviderEntry::Loading => 4,
            ProviderEntry::Done(r) => match &r.status {
                ProviderStatus::Available { quota } => {
                    let visible = quota
                        .windows
                        .iter()
                        .filter(|w| w.limit > 0 || w.window_type == "payg_balance")
                        .count()
                        .max(1) as u32;
                    // Score grows with content but is capped so a card
                    // with 30 windows can't monopolize an entire row at
                    // the expense of the others. Anything over ~6 windows
                    // switches to compact rendering anyway.
                    let raw = 4 + visible;
                    raw.clamp(5, 12)
                }
                _ => 5,
            },
        }
    }

    fn render_entry(&self, f: &mut Frame, idx: usize, selected: bool, area: Rect) {
        let border_style = if selected {
            Style::new().green()
        } else {
            Style::new().dim()
        };
        let block = Block::new()
            .borders(Borders::ALL)
            .border_style(border_style);
        let inner = block.inner(area);
        f.render_widget(block, area);

        match &self.entries[idx] {
            ProviderEntry::Loading => {
                let name = self.kinds[idx].display_name();
                let spinner_char = SPINNER[self.spinner_frame];
                let text = Text::from(vec![
                    Line::from(vec![Span::raw(format!(
                        "{} {}",
                        if selected { "▶" } else { " " },
                        name
                    ))
                    .bold()]),
                    Line::from(""),
                    Line::from(vec![
                        Span::raw(spinner_char).cyan(),
                        Span::raw(" loading…").dim(),
                    ]),
                ]);
                let p = Paragraph::new(text).wrap(Wrap { trim: true });
                f.render_widget(p, inner);
            }
            ProviderEntry::Done(result) => {
                self.render_done_card(f, result, selected, inner);
            }
        }
    }

    fn render_done_card(
        &self,
        f: &mut Frame,
        result: &ProviderResult,
        selected: bool,
        inner: Rect,
    ) {
        let card = ProviderCard::new(result.clone(), selected);
        let freshness = card.freshness_label();
        let freshness_style = match freshness.staleness {
            crate::tui::freshness::Staleness::Fresh => Style::new().cyan(),
            crate::tui::freshness::Staleness::Warning => Style::new().yellow(),
            crate::tui::freshness::Staleness::Stale => Style::new().red(),
        };

        let mut lines: Vec<Line> = Vec::new();

        // Header line: name + freshness
        lines.push(Line::from(vec![
            Span::raw(format!(
                "{} {}",
                if selected { "▶" } else { " " },
                card.display_name()
            ))
            .bold(),
            Span::raw("  "),
            Span::styled(freshness.label.clone(), freshness_style),
        ]));

        // Plan / status line
        match &result.status {
            ProviderStatus::Available { quota } => {
                lines.push(Line::from(
                    Span::raw(quota.plan_name.clone()).italic().dim(),
                ));

                let visible: Vec<&QuotaWindow> = quota
                    .windows
                    .iter()
                    .filter(|w| w.limit > 0 || w.window_type == "payg_balance")
                    .collect();
                let total = visible.len();

                // Available space inside the card after header + plan line,
                // minus one row reserved for a possible "+ N more" footer.
                let header_lines = lines.len() as u16;
                let body_height = inner.height.saturating_sub(header_lines);
                let footer_reserve: u16 = if total > 0 { 1 } else { 0 };
                let usable = body_height.saturating_sub(footer_reserve) as usize;

                // Pick the densest layout that fits all windows. Falls
                // through to the most compact form if even that overflows,
                // with overflow handled by an explicit "+ N more" footer.
                let (mode, shown_count) = pick_layout(total, usable);

                // Compact bar widths leave more room for labels.
                let label_w = match mode {
                    RenderMode::TwoLine => 12,
                    RenderMode::OneLine => 11,
                };
                let bar_width = inner.width.saturating_sub(label_w as u16 + 11).clamp(6, 32);

                for w in visible.iter().take(shown_count) {
                    if w.window_type == "payg_balance" {
                        lines.push(Line::from(vec![Span::raw(format!(
                            "{:<width$} ${:.2}",
                            w.window_type,
                            w.remaining as f64 / 100.0,
                            width = label_w
                        ))]));
                        if matches!(mode, RenderMode::TwoLine) {
                            lines.push(Line::from(""));
                        }
                        continue;
                    }
                    let used_pct = (w.used as f64 / w.limit.max(1) as f64).clamp(0.0, 1.0);
                    let remaining_pct = 1.0 - used_pct;
                    let time_frac = time_remaining_fraction(w);
                    let color = bar_color(remaining_pct);
                    let bar_spans = marked_bar(remaining_pct, time_frac, bar_width, color);

                    match mode {
                        RenderMode::TwoLine => {
                            let mut l1 = vec![Span::raw(format!(
                                "{:<width$} ",
                                truncate(&w.window_type, label_w),
                                width = label_w
                            ))];
                            l1.extend(bar_spans);
                            l1.push(Span::raw(format!(" {:>3.0}%", remaining_pct * 100.0)));
                            lines.push(Line::from(l1));
                            lines.push(Line::from(vec![Span::raw(format!(
                                "{:width$}{} / {} left",
                                "",
                                format_num(w.remaining),
                                format_num(w.limit),
                                width = label_w + 1
                            ))
                            .dim()]));
                        }
                        RenderMode::OneLine => {
                            let mut l = vec![Span::raw(format!(
                                "{:<width$} ",
                                truncate(&w.window_type, label_w),
                                width = label_w
                            ))];
                            l.extend(bar_spans);
                            l.push(Span::raw(format!(" {:>3.0}% ", remaining_pct * 100.0)));
                            l.push(Span::raw(format_num(w.remaining)).dim());
                            lines.push(Line::from(l));
                        }
                    }
                }

                if total > shown_count {
                    lines.push(Line::from(
                        Span::raw(format!("+ {} more · Enter for detail", total - shown_count))
                            .dim()
                            .italic(),
                    ));
                }
            }
            ProviderStatus::Unavailable { info } => {
                lines.push(Line::from(
                    Span::raw(format!("Unavailable: {}", info.reason)).yellow(),
                ));
                if let Some(url) = &info.console_url {
                    lines.push(Line::from(Span::raw(url.clone()).dim()));
                }
            }
            ProviderStatus::AuthRequired => {
                lines.push(Line::from(Span::raw("Auth required").red()));
                lines.push(Line::from(Span::raw("Set API key in env or config").dim()));
            }
            ProviderStatus::NetworkError { message } => {
                lines.push(Line::from(Span::raw("Network error").red()));
                lines.push(Line::from(Span::raw(message.clone()).dim()));
            }
        }

        let paragraph = Paragraph::new(Text::from(lines))
            .wrap(Wrap { trim: false })
            .alignment(ratatui::layout::Alignment::Left);
        f.render_widget(paragraph, inner);
    }

    pub fn page_up(&mut self) {
        let layout = self.last_layout.get();
        if layout.per_page == 0 {
            return;
        }
        let page = self.current_page();
        if page > 0 {
            let new_page = page - 1;
            self.selected_index = new_page * layout.per_page;
        }
    }

    pub fn page_down(&mut self) {
        let layout = self.last_layout.get();
        if layout.per_page == 0 {
            return;
        }
        let total = self.entries.len();
        let page = self.current_page();
        let pages = total.div_ceil(layout.per_page);
        if page + 1 < pages {
            self.selected_index = (page + 1) * layout.per_page;
        }
    }

    fn render_detail(&self, f: &mut Frame) {
        let area = f.area();

        let title = Paragraph::new(vec![
            Line::from(vec![Span::raw(" QUOTA DETAIL ").bold().white()]),
            Line::from(vec![Span::raw("Enter: back  C: copy JSON  Q: quit ").dim()]),
        ])
        .block(Block::new().borders(Borders::BOTTOM));
        f.render_widget(title, Rect::new(area.x, area.y, area.width, 2));

        if let Some(selected) = self.selected_provider() {
            let view = DetailView::new(selected.clone());
            let detail_area = Rect::new(
                area.x,
                area.y + 2,
                area.width,
                area.height.saturating_sub(3),
            );
            let text = view.render(detail_area.width);
            let paragraph = Paragraph::new(text)
                .block(Block::new().borders(Borders::NONE))
                .wrap(Wrap { trim: false })
                .scroll((0, 0));
            f.render_widget(paragraph, detail_area);
        } else {
            let p = Paragraph::new("Provider still loading…")
                .block(Block::new().borders(Borders::NONE));
            f.render_widget(
                p,
                Rect::new(
                    area.x,
                    area.y + 2,
                    area.width,
                    area.height.saturating_sub(3),
                ),
            );
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum RenderMode {
    /// Two lines per window: bar+pct, then exact `used / limit left`.
    TwoLine,
    /// One line per window: label, bar, pct, remaining count.
    OneLine,
}

/// Pick the densest rendering that fits the most windows in the available
/// vertical space. Returns the chosen mode and the number of windows to
/// actually render — anything beyond that is summarized as "+ N more".
fn pick_layout(total: usize, usable_lines: usize) -> (RenderMode, usize) {
    if total == 0 || usable_lines == 0 {
        return (RenderMode::TwoLine, 0);
    }
    // Try the comfortable two-line layout first.
    let two_fits = usable_lines / 2;
    if two_fits >= total {
        return (RenderMode::TwoLine, total);
    }
    // Otherwise switch to compact one-line format.
    let one_fits = usable_lines;
    if one_fits >= total {
        return (RenderMode::OneLine, total);
    }
    // Still doesn't fit — show as many as possible compactly and reserve
    // the last line for the "+ N more" indicator (the caller already
    // subtracted that line from usable_lines).
    (RenderMode::OneLine, one_fits.min(total))
}

/// Fraction of the window's time period that is *still remaining*, based on
/// `reset_at` minus "now" over the total `period_seconds`. Returns None if
/// either input is missing. Mirrors the semantics of `remaining_pct` on the
/// quota bar, so both can share a single axis.
fn time_remaining_fraction(w: &QuotaWindow) -> Option<f64> {
    let reset = w.reset_at?;
    let period = w.period_seconds?;
    if period <= 0 {
        return None;
    }
    let remaining = (reset - Utc::now()).num_seconds();
    if remaining <= 0 {
        return Some(0.0);
    }
    Some((remaining as f64 / period as f64).clamp(0.0, 1.0))
}

/// Build a quota bar as styled spans, with `remaining_pct` as the fill and
/// an optional `┃` marker at the position corresponding to the fraction of
/// time *remaining* in the window. If the marker sits inside the filled
/// region, you're underspending (good); in the empty region, overspending.
fn marked_bar<'a>(
    remaining_pct: f64,
    time_remaining_pct: Option<f64>,
    width: u16,
    color: Color,
) -> Vec<Span<'a>> {
    let w = width as usize;
    if w == 0 {
        return Vec::new();
    }
    let filled = ((remaining_pct.clamp(0.0, 1.0)) * w as f64).round() as usize;
    let marker_pos = time_remaining_pct
        .map(|t| (((t.clamp(0.0, 1.0)) * w as f64).round() as usize).min(w.saturating_sub(1)));

    // Render each column and coalesce same-style runs into minimal spans.
    enum Cell {
        Full,
        Empty,
        Marker,
    }
    let mut cells: Vec<Cell> = (0..w)
        .map(|i| if i < filled { Cell::Full } else { Cell::Empty })
        .collect();
    if let Some(pos) = marker_pos {
        cells[pos] = Cell::Marker;
    }

    let bar_style = Style::new().fg(color);
    let marker_style = Style::new().fg(Color::White).bold();
    let mut out: Vec<Span<'a>> = Vec::new();
    let mut buf = String::new();
    let mut cur_marker = matches!(cells[0], Cell::Marker);
    for cell in &cells {
        let is_marker = matches!(cell, Cell::Marker);
        if is_marker != cur_marker && !buf.is_empty() {
            out.push(Span::styled(
                std::mem::take(&mut buf),
                if cur_marker { marker_style } else { bar_style },
            ));
            cur_marker = is_marker;
        }
        buf.push(match cell {
            Cell::Full => '█',
            Cell::Empty => '░',
            Cell::Marker => '┃',
        });
    }
    if !buf.is_empty() {
        out.push(Span::styled(
            buf,
            if cur_marker { marker_style } else { bar_style },
        ));
    }
    out
}

fn bar_color(remaining_pct: f64) -> Color {
    // Colors reflect the *remaining* fraction — healthy when lots of quota
    // left, red when almost exhausted.
    if remaining_pct <= 0.10 {
        Color::Red
    } else if remaining_pct <= 0.25 {
        Color::Yellow
    } else {
        Color::Green
    }
}

fn format_num(n: i64) -> String {
    if n.abs() >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n.abs() >= 1_000 {
        format!("{:.1}k", n as f64 / 1_000.0)
    } else {
        n.to_string()
    }
}

fn truncate(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        s.to_string()
    } else {
        let mut out: String = s.chars().take(n.saturating_sub(1)).collect();
        out.push('…');
        out
    }
}

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

    fn bar_as_string(spans: &[Span<'_>]) -> String {
        spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn marked_bar_without_marker_renders_full_and_empty() {
        let s = bar_as_string(&marked_bar(1.0, None, 4, Color::Green));
        assert_eq!(s, "████");
        let s = bar_as_string(&marked_bar(0.0, None, 4, Color::Green));
        assert_eq!(s, "░░░░");
    }

    #[test]
    fn marked_bar_places_marker_in_filled_region_when_ahead() {
        // 80% quota remaining (filled=3 of 4), 50% time remaining (marker
        // at idx 2) — marker overlays the filled region, which visually
        // indicates "ahead of schedule".
        let s = bar_as_string(&marked_bar(0.8, Some(0.5), 4, Color::Green));
        assert_eq!(s, "██┃░");
    }

    #[test]
    fn marked_bar_places_marker_in_empty_region_when_behind() {
        // 20% quota remaining, 75% time remaining → marker sits in empty
        // area at index 3 of 4.
        let s = bar_as_string(&marked_bar(0.2, Some(0.75), 4, Color::Red));
        assert_eq!(s, "█░░┃");
    }

    #[test]
    fn format_num_scales() {
        assert_eq!(format_num(500), "500");
        assert_eq!(format_num(1_500), "1.5k");
        assert_eq!(format_num(2_500_000), "2.5M");
    }

    #[test]
    fn truncate_short_unchanged() {
        assert_eq!(truncate("hi", 8), "hi");
        assert_eq!(truncate("abcdefghij", 5), "abcd…");
    }
}