modelsdev 0.11.4

A fast TUI and CLI for browsing AI models, benchmarks, and coding agents
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
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Clear, Paragraph},
    Frame,
};

use super::app::{App, Mode, Tab};
use crate::status::ProviderHealth;
use crate::tui::widgets::scroll_offset::ScrollOffset;
use crate::tui::widgets::scrollable_panel::ScrollablePanel;

/// Border style: Cyan when focused, DarkGray when not.
pub(super) fn focus_border(focused: bool) -> Style {
    Style::default().fg(if focused {
        Color::Cyan
    } else {
        Color::DarkGray
    })
}

/// Caret prefix for list items: "> " when focused, "  " when not.
pub(super) fn caret(focused: bool) -> &'static str {
    if focused {
        "> "
    } else {
        "  "
    }
}

/// Selection style: Yellow + BOLD when selected, default otherwise.
pub(super) fn selection_style(selected: bool) -> Style {
    if selected {
        Style::default()
            .fg(Color::Yellow)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
    }
}

/// Build a help-popup line: 16-char padded key in Yellow + description.
fn help_line<'a>(key: &'a str, desc: &'a str) -> Line<'a> {
    Line::from(vec![
        Span::styled(format!("  {:<14}", key), Style::default().fg(Color::Yellow)),
        Span::raw(desc),
    ])
}

pub(super) fn status_health_style(health: ProviderHealth) -> Style {
    match health {
        ProviderHealth::Operational => Style::default().fg(Color::Green),
        ProviderHealth::Degraded => Style::default().fg(Color::Yellow),
        ProviderHealth::Outage => Style::default().fg(Color::Red),
        ProviderHealth::Maintenance => Style::default().fg(Color::Blue),
        ProviderHealth::Unknown => Style::default().fg(Color::DarkGray),
    }
}

pub(super) fn status_health_icon(health: ProviderHealth) -> &'static str {
    match health {
        ProviderHealth::Operational => "",
        ProviderHealth::Degraded => "",
        ProviderHealth::Outage => "",
        ProviderHealth::Maintenance => "",
        ProviderHealth::Unknown => "?",
    }
}

/// Compute the visual height of a single line when word-wrapped to `wrap_width`.
///
/// Returns 1 for empty or zero-width lines, otherwise `div_ceil(width, wrap_width)`
/// with +1 buffer for lines that actually wrap (ratatui's word-wrap can overshoot
/// `div_ceil` by one row).
fn visual_line_height(line: &Line<'_>, wrap_width: usize) -> u16 {
    let w = line.width();
    if wrap_width == 0 || w == 0 {
        1
    } else {
        let base = w.div_ceil(wrap_width).max(1) as u16;
        if w > wrap_width {
            base + 1
        } else {
            base
        }
    }
}

/// Sum visual (wrapped) heights for a slice of lines.
///
/// Uses `div_ceil(line.width(), wrap_width)` with a +1 buffer for lines that
/// actually wrap, since ratatui's word-wrap can produce one extra visual row.
#[allow(dead_code)]
pub(in crate::tui) fn visual_line_total(lines: &[Line<'_>], wrap_width: usize) -> u16 {
    lines
        .iter()
        .map(|line| visual_line_height(line, wrap_width))
        .sum()
}

/// Return per-line visual (wrapped) heights for a slice of lines.
///
/// Callers can derive cumulative offsets by scanning the returned `Vec`.
#[allow(dead_code)]
pub(in crate::tui) fn visual_line_heights(lines: &[Line<'_>], wrap_width: usize) -> Vec<u16> {
    lines
        .iter()
        .map(|line| visual_line_height(line, wrap_width))
        .collect()
}

/// Build a dash-padded section header line like `"── Title ──────"`.
///
/// The result is styled DarkGray + BOLD, matching the models detail panel pattern.
#[allow(dead_code)]
pub(in crate::tui) fn section_header_line(title: &str, width: usize) -> Line<'static> {
    let prefix = format!("\u{2500}\u{2500} {} ", title);
    let fill_len = width.saturating_sub(prefix.chars().count());
    let header = format!("{}{}", prefix, "\u{2500}".repeat(fill_len));
    Line::from(Span::styled(
        header,
        Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::BOLD),
    ))
}

/// Build filter toggle spans in `[N] label` format.
///
/// Each tuple is `(key, label, active)`. Active keys render in Green, inactive
/// in DarkGray. Returns a flat `Vec<Span>` ready for `Line::from(...)`.
pub(in crate::tui) fn filter_toggle_spans(toggles: &[(&str, &str, bool)]) -> Vec<Span<'static>> {
    let mut spans = Vec::with_capacity(toggles.len() * 2);
    for (key, label, active) in toggles {
        let color = if *active {
            Color::Green
        } else {
            Color::DarkGray
        };
        spans.push(Span::styled(
            format!("[{}]", key),
            Style::default().fg(color),
        ));
        spans.push(Span::raw(format!(" {} ", label)));
    }
    spans
}

/// Create a centered rect using fixed width and height
pub(super) fn centered_rect_fixed(width: u16, height: u16, area: Rect) -> Rect {
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    Rect::new(x, y, width, height)
}

/// Create a centered rect using percentage of the available area
pub(super) fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(area);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}

pub fn draw(f: &mut Frame, app: &mut App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header
            Constraint::Min(0),    // Main content
            Constraint::Length(1), // Footer/search
        ])
        .split(f.area());

    draw_header(f, chunks[0], app);

    match app.current_tab {
        Tab::Models => {
            super::models::render::draw_main(f, chunks[1], app);
        }
        Tab::Agents => {
            super::agents::render::draw_agents_main(f, chunks[1], app);
        }
        Tab::Benchmarks => {
            super::benchmarks::render::draw_benchmarks_main(f, chunks[1], app);
        }
        Tab::Status => {
            super::status::render::draw_status_main(f, chunks[1], app);
        }
    }

    draw_footer(f, chunks[2], app);

    // Draw help popup on top if visible
    if app.show_help {
        draw_help_popup(f, &app.help_scroll, app.current_tab);
    }

    // Draw picker modal on top if visible (agents tab only)
    if app.current_tab == Tab::Agents {
        if let Some(agents_app) = &app.agents_app {
            if agents_app.show_picker {
                super::agents::render::draw_picker_modal(f, app);
            }
        }
    }
}

fn draw_header(f: &mut Frame, area: Rect, app: &App) {
    let tab_style = |tab: Tab| {
        if app.current_tab == tab {
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::DarkGray)
        }
    };

    let header = Paragraph::new(Line::from(vec![
        Span::raw(" "),
        Span::styled("Models", tab_style(Tab::Models)),
        Span::raw(" | "),
        Span::styled("Agents", tab_style(Tab::Agents)),
        Span::raw(" | "),
        Span::styled("Benchmarks", tab_style(Tab::Benchmarks)),
        Span::raw(" | "),
        Span::styled("Status", tab_style(Tab::Status)),
        Span::styled("  [/] switch tabs", Style::default().fg(Color::DarkGray)),
    ]));
    f.render_widget(header, area);
}

fn draw_footer(f: &mut Frame, area: Rect, app: &App) {
    // If there's a status message, show it instead of normal footer
    if let Some(status) = &app.status_message {
        let content = Line::from(vec![
            Span::styled(" ", Style::default()),
            Span::styled(status, Style::default().fg(Color::Green)),
        ]);
        let paragraph = Paragraph::new(content);
        f.render_widget(paragraph, area);
        return;
    }

    match app.mode {
        Mode::Normal => {
            // Split footer into left and right sections
            let chunks = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Min(0), Constraint::Length(10)])
                .split(area);

            let left_content = match app.current_tab {
                Tab::Models => Line::from(vec![
                    Span::styled(" q ", Style::default().fg(Color::Yellow)),
                    Span::raw("quit  "),
                    Span::styled(" ↑/↓ ", Style::default().fg(Color::Yellow)),
                    Span::raw("nav  "),
                    Span::styled(" Tab ", Style::default().fg(Color::Yellow)),
                    Span::raw("switch  "),
                    Span::styled(" / ", Style::default().fg(Color::Yellow)),
                    Span::raw("search  "),
                    Span::styled(" s/S ", Style::default().fg(Color::Yellow)),
                    Span::raw("sort  "),
                    Span::styled(" 1-6 ", Style::default().fg(Color::Yellow)),
                    Span::raw("filter  "),
                    Span::styled(" c ", Style::default().fg(Color::Yellow)),
                    Span::raw("copy"),
                ]),
                Tab::Agents => Line::from(vec![
                    Span::styled(" q ", Style::default().fg(Color::Yellow)),
                    Span::raw("quit  "),
                    Span::styled(" / ", Style::default().fg(Color::Yellow)),
                    Span::raw("search  "),
                    Span::styled(" s ", Style::default().fg(Color::Yellow)),
                    Span::raw("sort  "),
                    Span::styled(" a ", Style::default().fg(Color::Yellow)),
                    Span::raw("track  "),
                    Span::styled(" o ", Style::default().fg(Color::Yellow)),
                    Span::raw("docs  "),
                    Span::styled(" r ", Style::default().fg(Color::Yellow)),
                    Span::raw("repo"),
                ]),
                Tab::Benchmarks => {
                    if app.selections.len() >= 2 {
                        use super::benchmarks::{BenchmarkFocus, BottomView};
                        let mut spans = vec![
                            Span::styled(" q ", Style::default().fg(Color::Yellow)),
                            Span::raw("quit  "),
                            Span::styled(" h/l ", Style::default().fg(Color::Yellow)),
                            Span::raw("focus  "),
                            Span::styled(" t ", Style::default().fg(Color::Yellow)),
                            Span::raw(if app.benchmarks_app.show_creators_in_compare {
                                "models  "
                            } else {
                                "creators  "
                            }),
                            Span::styled(" Space ", Style::default().fg(Color::Yellow)),
                            Span::raw("select  "),
                            Span::styled(" v ", Style::default().fg(Color::Yellow)),
                            Span::raw("view  "),
                        ];
                        match app.benchmarks_app.bottom_view {
                            BottomView::H2H => {
                                spans.extend([
                                    Span::styled(" d ", Style::default().fg(Color::Yellow)),
                                    Span::raw("detail  "),
                                ]);
                                if app.benchmarks_app.focus == BenchmarkFocus::Compare {
                                    spans.extend([
                                        Span::styled(" j/k ", Style::default().fg(Color::Yellow)),
                                        Span::raw("scroll  "),
                                    ]);
                                }
                            }
                            BottomView::Scatter => {
                                spans.extend([
                                    Span::styled(" x ", Style::default().fg(Color::Yellow)),
                                    Span::raw("X-axis  "),
                                    Span::styled(" y ", Style::default().fg(Color::Yellow)),
                                    Span::raw("Y-axis  "),
                                ]);
                            }
                            BottomView::Radar => {
                                spans.extend([
                                    Span::styled(" a ", Style::default().fg(Color::Yellow)),
                                    Span::raw("preset  "),
                                ]);
                            }
                            BottomView::Detail => {}
                        }
                        spans.extend([
                            Span::styled(" c ", Style::default().fg(Color::Yellow)),
                            Span::raw("clear  "),
                            Span::styled(" s ", Style::default().fg(Color::Yellow)),
                            Span::raw("sort  "),
                            Span::styled(" / ", Style::default().fg(Color::Yellow)),
                            Span::raw("search"),
                        ]);
                        Line::from(spans)
                    } else {
                        Line::from(vec![
                            Span::styled(" q ", Style::default().fg(Color::Yellow)),
                            Span::raw("quit  "),
                            Span::styled(" 1 ", Style::default().fg(Color::Yellow)),
                            Span::raw("intel  "),
                            Span::styled(" 2 ", Style::default().fg(Color::Yellow)),
                            Span::raw("date  "),
                            Span::styled(" 3 ", Style::default().fg(Color::Yellow)),
                            Span::raw("speed  "),
                            Span::styled(" 4 ", Style::default().fg(Color::Yellow)),
                            Span::raw("source  "),
                            Span::styled(" 5-6 ", Style::default().fg(Color::Yellow)),
                            Span::raw("group  "),
                            Span::styled(" 7 ", Style::default().fg(Color::Yellow)),
                            Span::raw("reasoning  "),
                            Span::styled(" s ", Style::default().fg(Color::Yellow)),
                            Span::raw("sort  "),
                            Span::styled(" / ", Style::default().fg(Color::Yellow)),
                            Span::raw("search  "),
                            Span::styled(" Space ", Style::default().fg(Color::Yellow)),
                            Span::raw("select"),
                        ])
                    }
                }
                Tab::Status => {
                    let hints = vec![
                        Span::styled(" q ", Style::default().fg(Color::Yellow)),
                        Span::raw("quit  "),
                        Span::styled(" / ", Style::default().fg(Color::Yellow)),
                        Span::raw("search  "),
                        Span::styled(" Tab ", Style::default().fg(Color::Yellow)),
                        Span::raw("focus  "),
                        Span::styled(" a ", Style::default().fg(Color::Yellow)),
                        Span::raw("track  "),
                        Span::styled(" o ", Style::default().fg(Color::Yellow)),
                        Span::raw("open page  "),
                        Span::styled(" r ", Style::default().fg(Color::Yellow)),
                        Span::raw("refresh"),
                    ];
                    Line::from(hints)
                }
            };

            let right_content = Line::from(vec![
                Span::styled(" ? ", Style::default().fg(Color::Yellow)),
                Span::raw("help "),
            ]);

            f.render_widget(Paragraph::new(left_content), chunks[0]);
            f.render_widget(
                Paragraph::new(right_content).alignment(ratatui::layout::Alignment::Right),
                chunks[1],
            );
        }
        Mode::Search => {
            // Get the correct search query based on current tab
            let search_query = match app.current_tab {
                Tab::Models => &app.models_app.search_query,
                Tab::Agents => app
                    .agents_app
                    .as_ref()
                    .map(|a| &a.search_query)
                    .unwrap_or(&app.models_app.search_query),
                Tab::Benchmarks => &app.benchmarks_app.search_query,
                Tab::Status => app
                    .status_app
                    .as_ref()
                    .map(|a| &a.search_query)
                    .unwrap_or(&app.models_app.search_query),
            };
            let content = Line::from(vec![
                Span::styled(" Search: ", Style::default().fg(Color::Cyan)),
                Span::raw(search_query),
                Span::styled("_", Style::default().add_modifier(Modifier::SLOW_BLINK)),
                Span::raw("  "),
                Span::styled(" Enter/Esc ", Style::default().fg(Color::Yellow)),
                Span::raw("confirm"),
            ]);
            f.render_widget(Paragraph::new(content), area);
        }
    };
}

fn draw_help_popup(f: &mut Frame, scroll: &ScrollOffset, current_tab: Tab) {
    let area = centered_rect(50, 70, f.area());

    // Clear the area behind the popup
    f.render_widget(Clear, area);

    let help_section = |title: &'static str| -> Line<'static> {
        Line::from(Span::styled(
            title,
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ))
    };

    let mut help_text = vec![
        // Common: Navigation
        help_section("Navigation"),
        help_line("j/↓", "Move down"),
        help_line("k/↑", "Move up"),
        help_line("g", "First item"),
        help_line("G", "Last item"),
        help_line("Ctrl+d/PgDn", "Page down"),
        help_line("Ctrl+u/PgUp", "Page up"),
        Line::from(""),
        // Common: Panels
        help_section("Panels"),
        help_line("h/←/l/→", "Switch panels"),
        help_line("Tab", "Switch panels"),
        Line::from(""),
        // Common: Search
        help_section("Search"),
        help_line("/", "Start search"),
        help_line("Enter/Esc", "Exit search mode"),
        help_line("Esc", "Clear search (in normal mode)"),
        Line::from(""),
    ];

    // Tab-specific sections
    match current_tab {
        Tab::Models => {
            help_text.extend(vec![
                help_section("Filters & Sort"),
                help_line("s", "Cycle sort (name → date → cost → context)"),
                help_line("S", "Toggle sort direction"),
                help_line("1", "Toggle reasoning models filter"),
                help_line("2", "Toggle tools filter"),
                help_line("3", "Toggle open weights filter"),
                help_line("4", "Toggle free models filter"),
                help_line("5", "Cycle provider category filter"),
                help_line("6", "Toggle category grouping"),
                Line::from(""),
                help_section("Copy & Open"),
                help_line("c", "Copy provider/model"),
                help_line("C", "Copy model only"),
                help_line("o", "Open provider docs in browser"),
                help_line("D", "Copy provider docs URL"),
                help_line("A", "Copy provider API URL"),
                Line::from(""),
            ]);
        }
        Tab::Agents => {
            help_text.extend(vec![
                help_section("Filters & Sort"),
                help_line("s", "Cycle sort (name → updated → stars → status)"),
                help_line("1", "Toggle installed filter"),
                help_line("2", "Toggle CLI filter"),
                help_line("3", "Toggle open source filter"),
                Line::from(""),
                help_section("Actions"),
                help_line("o", "Open docs in browser"),
                help_line("r", "Open GitHub repo in browser"),
                help_line("c", "Copy agent name"),
                help_line("a", "Add/remove tracked agents"),
                Line::from(""),
                help_section("Search Navigation"),
                help_line("n", "Next search match"),
                help_line("N", "Previous search match"),
                Line::from(""),
                help_section("Status Indicators"),
                Line::from(vec![
                    Span::styled(
                        format!("  {:<14}", ""),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::raw("Not tracked"),
                ]),
                Line::from(vec![
                    Span::styled(format!("  {:<14}", ""), Style::default().fg(Color::Yellow)),
                    Span::raw("Loading GitHub data"),
                ]),
                Line::from(vec![
                    Span::styled(format!("  {:<14}", ""), Style::default().fg(Color::Green)),
                    Span::raw("Up to date"),
                ]),
                Line::from(vec![
                    Span::styled(format!("  {:<14}", ""), Style::default().fg(Color::Blue)),
                    Span::raw("Update available"),
                ]),
                Line::from(vec![
                    Span::styled(format!("  {:<14}", ""), Style::default().fg(Color::Red)),
                    Span::raw("Fetch failed"),
                ]),
                Line::from(""),
            ]);
        }
        Tab::Benchmarks => {
            help_text.extend(vec![
                help_section("Quick Sort (press again to flip direction)"),
                help_line("1", "Sort by Intelligence index"),
                help_line("2", "Sort by Release date"),
                help_line("3", "Sort by Speed (tok/s)"),
                Line::from(""),
                help_section("Filters"),
                help_line("4", "Cycle source filter (Open/Closed/Mixed)"),
                help_line("5", "Cycle region filter (US/China/Europe/...)"),
                help_line("6", "Cycle type filter (Startup/Big Tech/Research)"),
                help_line("7", "Cycle reasoning filter (All/Reasoning/Non-reasoning)"),
                Line::from(""),
                help_section("Sort (full cycle)"),
                help_line("s", "Open sort picker"),
                help_line("S", "Toggle sort direction"),
                Line::from(""),
                help_section("Actions"),
                help_line("o", "Open Artificial Analysis page"),
                Line::from(""),
                help_section("Compare"),
                help_line("Space", "Toggle model for comparison (max 8)"),
                help_line("c", "Clear all selections"),
                help_line("v", "Cycle view: H2H → Scatter → Radar"),
                help_line("d", "Show detail overlay (H2H view)"),
                help_line("x", "Cycle scatter X-axis"),
                help_line("y", "Cycle scatter Y-axis"),
                help_line("a", "Cycle radar preset"),
                help_line("j/k", "Scroll H2H table (when Compare focused)"),
                help_line("h/l", "Switch focus: List ↔ Compare"),
                help_line("t", "Toggle left panel: Models ↔ Creators"),
                Line::from(""),
            ]);
        }
        Tab::Status => {
            help_text.extend(vec![
                help_section("Actions"),
                help_line("o", "Open provider status page"),
                help_line("r", "Refresh provider status"),
                help_line("a", "Add/remove tracked providers"),
                Line::from(""),
                help_section("Status view"),
                help_line("Tab/h/l", "Switch list/details focus"),
                help_line("/", "Search providers"),
                Line::from(""),
            ]);
        }
    }

    // Common: Tabs and Other
    help_text.extend(vec![
        help_section("Tabs"),
        help_line("[", "Previous tab"),
        help_line("]", "Next tab"),
        Line::from(""),
        help_section("Other"),
        help_line("q", "Quit"),
        help_line("?", "Toggle this help"),
    ]);

    let title = match current_tab {
        Tab::Models => "Models Help - ? or Esc to close (j/k to scroll)",
        Tab::Agents => "Agents Help - ? or Esc to close (j/k to scroll)",
        Tab::Benchmarks => "Benchmarks Help - ? or Esc to close (j/k to scroll)",
        Tab::Status => "Status Help - ? or Esc to close (j/k to scroll)",
    };

    ScrollablePanel::new(title, help_text, scroll, true)
        .with_wrap(false)
        .render(f, area);
}

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

    #[test]
    fn visual_line_height_empty() {
        let line = Line::from("");
        assert_eq!(visual_line_height(&line, 40), 1);
    }

    #[test]
    fn visual_line_height_fits() {
        let line = Line::from("short");
        assert_eq!(visual_line_height(&line, 40), 1);
    }

    #[test]
    fn visual_line_height_wraps() {
        // 10 chars in a 4-wide viewport: div_ceil(10, 4) = 3, +1 buffer = 4
        let line = Line::from("abcdefghij");
        assert_eq!(visual_line_height(&line, 4), 4);
    }

    #[test]
    fn visual_line_height_exact_fit() {
        // Exactly fits: no +1 buffer
        let line = Line::from("abcd");
        assert_eq!(visual_line_height(&line, 4), 1);
    }

    #[test]
    fn visual_line_height_zero_wrap() {
        let line = Line::from("hello");
        assert_eq!(visual_line_height(&line, 0), 1);
    }

    #[test]
    fn visual_line_total_sums() {
        let lines = vec![
            Line::from("short"),        // fits in 40 → 1
            Line::from(""),             // empty → 1
            Line::from("a".repeat(80)), // wraps in 40 → div_ceil(80,40)=2 +1 = 3
        ];
        assert_eq!(visual_line_total(&lines, 40), 5);
    }

    #[test]
    fn visual_line_heights_returns_per_line() {
        let lines = vec![Line::from("short"), Line::from("a".repeat(80))];
        let heights = visual_line_heights(&lines, 40);
        assert_eq!(heights, vec![1, 3]);
    }

    #[test]
    fn section_header_line_format() {
        let line = section_header_line("Pricing", 30);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.starts_with("\u{2500}\u{2500} Pricing "));
        assert_eq!(text.chars().count(), 30);
        // Verify style
        let style = line.spans[0].style;
        assert_eq!(style.fg, Some(Color::DarkGray));
        assert!(style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn section_header_line_short_width() {
        // Width shorter than prefix — no trailing dashes, no panic
        let line = section_header_line("Title", 5);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.contains("Title"));
    }

    #[test]
    fn filter_toggle_spans_active_and_inactive() {
        let spans = filter_toggle_spans(&[("1", "reasoning", true), ("2", "tools", false)]);
        assert_eq!(spans.len(), 4);
        // Active key is Green
        assert_eq!(spans[0].style.fg, Some(Color::Green));
        assert_eq!(spans[0].content.as_ref(), "[1]");
        assert_eq!(spans[1].content.as_ref(), " reasoning ");
        // Inactive key is DarkGray
        assert_eq!(spans[2].style.fg, Some(Color::DarkGray));
        assert_eq!(spans[2].content.as_ref(), "[2]");
        assert_eq!(spans[3].content.as_ref(), " tools ");
    }

    #[test]
    fn filter_toggle_spans_empty() {
        let spans = filter_toggle_spans(&[]);
        assert!(spans.is_empty());
    }
}