sbom-tools 0.2.0

Semantic SBOM diff and analysis tool
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
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
//! Multi-SBOM comparison dashboard view.
//!
//! Displays 1:N baseline comparison with deviation analysis.

use crate::diff::{MultiDiffResult, SecurityImpact};
use crate::tui::app::{MultiDiffState, MultiViewFilterPreset, MultiViewSortBy, SortDirection};
use crate::tui::theme::colors;
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Cell, Clear, Gauge, Paragraph, Row, Table, Wrap},
};

/// Render the multi-diff dashboard
pub fn render_multi_dashboard(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
    status: Option<&str>,
) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Length(5), // Baseline info
            Constraint::Min(15),   // Main content
            Constraint::Length(3), // Status bar
        ])
        .split(area);

    // Header with title and filter/sort info
    render_header(f, chunks[0], result, state);

    // Baseline info panel
    render_baseline_info(f, chunks[1], result);

    // Main content area - split into left (targets) and right (details)
    let main_chunks = if state.show_cross_target {
        // Show cross-target analysis panel instead of normal layout
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(25),
                Constraint::Percentage(40),
                Constraint::Percentage(35),
            ])
            .split(chunks[2])
    } else {
        Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Percentage(35), Constraint::Percentage(65)])
            .split(chunks[2])
    };

    render_targets_list(f, main_chunks[0], result, state);

    // Resolve the selected *display* index to a raw comparison index so the details
    // panel shows the same comparison the Targets list highlights. `usize::MAX` (when
    // the selection is past the filtered set) resolves to no comparison.
    let selected_raw = ordered_comparison_indices(result, state)
        .get(state.selected_target)
        .copied()
        .unwrap_or(usize::MAX);

    if state.show_cross_target && main_chunks.len() > 2 {
        render_cross_target_analysis(f, main_chunks[1], result, state);
        render_details_panel(f, main_chunks[2], result, selected_raw, state);
    } else if main_chunks.len() > 1 {
        render_details_panel(f, main_chunks[1], result, selected_raw, state);
    }

    // Status bar
    render_status_bar(f, chunks[3], result, state, status);

    // Render overlays
    if state.show_detail_modal {
        render_detail_modal(f, area, result, state);
    }

    if state.show_variable_drill_down {
        render_variable_drill_down(f, area, result, state);
    }

    if state.search.active {
        render_search_overlay(f, area, state);
    }
}

fn render_header(f: &mut Frame, area: Rect, result: &MultiDiffResult, state: &MultiDiffState) {
    let scheme = colors();
    let title = format!(
        " Multi-SBOM Comparison: {} vs {} targets ",
        result.baseline.name,
        result.comparisons.len()
    );

    // Build header line with filter/sort info
    let text = vec![Line::from(vec![
        Span::styled(
            title,
            Style::default()
                .fg(scheme.primary)
                .add_modifier(Modifier::BOLD),
        ),
        Span::raw(" │ "),
        Span::styled("Filter: ", Style::default().fg(scheme.text_muted)),
        Span::styled(
            state.filter_preset.label(),
            Style::default().fg(scheme.accent),
        ),
        Span::raw(" │ "),
        Span::styled("Sort: ", Style::default().fg(scheme.text_muted)),
        Span::styled(
            format!(
                "{} {}",
                state.sort_by.label(),
                state.sort_direction.indicator()
            ),
            Style::default().fg(scheme.accent),
        ),
        if state.heat_map_mode {
            Span::styled(" │ Heat Map", Style::default().fg(scheme.warning))
        } else {
            Span::raw("")
        },
    ])];

    let header = Paragraph::new(text).block(Block::default().borders(Borders::ALL));

    f.render_widget(header, area);
}

fn render_baseline_info(f: &mut Frame, area: Rect, result: &MultiDiffResult) {
    let scheme = colors();
    let info = &result.baseline;
    let text = vec![
        Line::from(vec![
            Span::styled("Baseline: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                &info.name,
                Style::default()
                    .fg(scheme.text)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("  "),
            Span::styled("Format: ", Style::default().fg(scheme.text_muted)),
            Span::styled(&info.format, Style::default().fg(scheme.accent)),
        ]),
        Line::from(vec![
            Span::styled("Components: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                info.component_count.to_string(),
                Style::default().fg(scheme.primary),
            ),
            Span::raw("  "),
            Span::styled("Dependencies: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                info.dependency_count.to_string(),
                Style::default().fg(scheme.primary),
            ),
            Span::raw("  "),
            Span::styled("Max Deviation: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                format_deviation(result.summary.max_deviation),
                Style::default().fg(if result.summary.max_deviation > 0.3 {
                    scheme.removed
                } else if result.summary.max_deviation > 0.1 {
                    scheme.warning
                } else {
                    scheme.added
                }),
            ),
        ]),
    ];

    let block = Block::default()
        .title(" Baseline ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(scheme.info));

    let paragraph = Paragraph::new(text).block(block);
    f.render_widget(paragraph, area);
}

/// Render a 0-1 deviation fraction as a display percentage.
///
/// `{:.1}%` everywhere except the exact-saturation case, where "100%" beats
/// "100.0%": in the 20%-wide Targets column at 80 cols the longer form clips
/// to a dangling "100.0" and loses its unit.
pub(crate) fn format_deviation(deviation: f64) -> String {
    let pct = deviation * 100.0;
    if pct >= 99.95 {
        "100%".to_string()
    } else {
        format!("{pct:.1}%")
    }
}

/// Deviation severity band: (severity name for `severity_bg_tint`, magnitude
/// glyph that survives NO_COLOR and red/green confusion).
pub(crate) fn deviation_band(deviation: f64) -> (&'static str, &'static str) {
    if deviation > 0.5 {
        ("critical", "\u{2587}")
    } else if deviation > 0.3 {
        ("high", "\u{2585}")
    } else if deviation > 0.1 {
        ("medium", "\u{2583}")
    } else {
        ("low", "\u{2581}")
    }
}

/// Raw `result.comparisons` indices in the order shown in the Targets list, after the
/// active filter preset + sort key + direction. Display index `N` (what
/// `selected_target` refers to, what the list highlights) maps to the returned vec's
/// `N`th entry.
///
/// Single source of truth for the visible ordering: the list highlight, the details
/// panel, the detail modal, and search all resolve the *same* comparison through this.
/// Previously the highlight used `selected_target` as a display index while the details
/// panel/modal used it as a raw `comparisons` index, so under any sort or filter they
/// referred to different comparisons.
pub(crate) fn ordered_comparison_indices(
    result: &MultiDiffResult,
    state: &MultiDiffState,
) -> Vec<usize> {
    let deviation = |name: &str| {
        result
            .summary
            .deviation_scores
            .get(name)
            .copied()
            .unwrap_or(0.0)
    };

    let mut idx: Vec<usize> = result
        .comparisons
        .iter()
        .enumerate()
        .filter(|(_, comp)| match state.filter_preset {
            MultiViewFilterPreset::All => true,
            MultiViewFilterPreset::HighDeviation => deviation(&comp.target.name) > 0.3,
            MultiViewFilterPreset::ChangesOnly => comp.diff.summary.total_changes > 0,
            MultiViewFilterPreset::WithVulnerabilities => {
                comp.diff.summary.vulnerabilities_introduced > 0
            }
            MultiViewFilterPreset::AddedOnly => comp.diff.summary.components_added > 0,
            MultiViewFilterPreset::RemovedOnly => comp.diff.summary.components_removed > 0,
        })
        .map(|(i, _)| i)
        .collect();

    // Every key uses a *descending* base order so the shared `Ascending` reverse below
    // flips it to ascending. Name previously used an ascending base, which the reverse
    // then inverted (Ascending showed Z→A); using a descending base fixes it.
    match state.sort_by {
        MultiViewSortBy::Name => idx.sort_by(|a, b| {
            result.comparisons[*b]
                .target
                .name
                .cmp(&result.comparisons[*a].target.name)
        }),
        MultiViewSortBy::Deviation => idx.sort_by(|a, b| {
            deviation(&result.comparisons[*b].target.name)
                .partial_cmp(&deviation(&result.comparisons[*a].target.name))
                .unwrap_or(std::cmp::Ordering::Equal)
        }),
        MultiViewSortBy::Changes => idx.sort_by(|a, b| {
            result.comparisons[*b]
                .diff
                .summary
                .total_changes
                .cmp(&result.comparisons[*a].diff.summary.total_changes)
        }),
        MultiViewSortBy::Components => idx.sort_by(|a, b| {
            result.comparisons[*b]
                .target
                .component_count
                .cmp(&result.comparisons[*a].target.component_count)
        }),
        MultiViewSortBy::Vulnerabilities => idx.sort_by(|a, b| {
            result.comparisons[*b]
                .diff
                .summary
                .vulnerabilities_introduced
                .cmp(
                    &result.comparisons[*a]
                        .diff
                        .summary
                        .vulnerabilities_introduced,
                )
        }),
    }

    if matches!(state.sort_direction, SortDirection::Ascending) {
        idx.reverse();
    }
    idx
}

fn render_targets_list(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
) {
    let scheme = colors();
    let is_active = matches!(state.active_panel, MultiDashboardPanel::Targets);
    let selected = state.selected_target;

    // Comparisons in display order (filter + sort + direction), paired with their raw
    // index. Shared with the details panel, modal, and search via
    // `ordered_comparison_indices` so the highlighted row and the details always
    // resolve the same comparison.
    let filtered_comparisons: Vec<(usize, &crate::diff::ComparisonResult)> =
        ordered_comparison_indices(result, state)
            .into_iter()
            .map(|raw| (raw, &result.comparisons[raw]))
            .collect();

    let rows: Vec<Row> = filtered_comparisons
        .iter()
        .enumerate()
        .map(|(display_idx, (_, comp))| {
            let deviation = result
                .summary
                .deviation_scores
                .get(&comp.target.name)
                .copied()
                .unwrap_or(0.0);

            let deviation_color = if deviation > 0.3 {
                scheme.removed
            } else if deviation > 0.1 {
                scheme.warning
            } else {
                scheme.added
            };

            let style = if display_idx == selected {
                Style::default()
                    .bg(scheme.selection)
                    .add_modifier(Modifier::BOLD)
            } else if state.heat_map_mode {
                // Theme-tuned severity tint (pale in light themes, Reset
                // under monochrome — the glyph below carries the magnitude).
                let (band, _) = deviation_band(deviation);
                Style::default().bg(scheme.severity_bg_tint(band))
            } else {
                Style::default()
            };

            // Highlight search matches
            let name_style = if state.search.matches.contains(&display_idx) {
                style.fg(scheme.accent).add_modifier(Modifier::BOLD)
            } else {
                style
            };

            Row::new(vec![
                Cell::from(comp.target.name.clone()).style(name_style),
                Cell::from(comp.target.component_count.to_string()).style(style),
                // Glyph LAST: in the narrow 20% column truncation must eat
                // the magnitude cue, never the digits (a clipped "100.0" that
                // reads "10" inverts the apparent magnitude).
                Cell::from(format!(
                    "{} {}",
                    format_deviation(deviation),
                    deviation_band(deviation).1
                ))
                .style(style.fg(deviation_color)),
                Cell::from(comp.diff.summary.total_changes.to_string()).style(style),
            ])
        })
        .collect();

    // Abbreviated headers: the full words clip even in the 120-col layout's
    // 40-cell pane ("Componen", "Deviatio"), and at 80 cols they clipped
    // mid-word against the values.
    let header = Row::new(vec!["Target", "Comps", "Dev %", "Chg"])
        .style(
            Style::default()
                .fg(scheme.primary)
                .add_modifier(Modifier::BOLD),
        )
        .bottom_margin(1);

    let widths = [
        Constraint::Percentage(40),
        Constraint::Percentage(20),
        Constraint::Percentage(20),
        Constraint::Percentage(20),
    ];

    let border_color = if is_active {
        scheme.accent
    } else {
        scheme.text
    };
    let title = format!(
        " Targets ({}/{}) ",
        filtered_comparisons.len(),
        result.comparisons.len()
    );

    let table = Table::new(rows, widths)
        .header(header)
        .block(
            Block::default()
                .title(title)
                .borders(Borders::ALL)
                .border_style(Style::default().fg(border_color)),
        )
        .row_highlight_style(Style::default().add_modifier(Modifier::BOLD));

    f.render_widget(table, area);
}

fn render_details_panel(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    selected: usize,
    state: &MultiDiffState,
) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(40), // Comparison summary
            Constraint::Percentage(60), // Variable components
        ])
        .split(area);

    if let Some(comp) = result.comparisons.get(selected) {
        render_comparison_details(f, chunks[0], comp, result);
    }

    render_variable_components(f, chunks[1], result, state);
}

fn render_comparison_details(
    f: &mut Frame,
    area: Rect,
    comp: &crate::diff::ComparisonResult,
    result: &MultiDiffResult,
) {
    let scheme = colors();
    let deviation = result
        .summary
        .deviation_scores
        .get(&comp.target.name)
        .copied()
        .unwrap_or(0.0);

    let summary = &comp.diff.summary;
    let text = vec![
        Line::from(vec![
            Span::styled("Target: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                &comp.target.name,
                Style::default()
                    .fg(scheme.text)
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("+ Added: ", Style::default().fg(scheme.added)),
            Span::raw(summary.components_added.to_string()),
            Span::raw("  "),
            Span::styled("- Removed: ", Style::default().fg(scheme.removed)),
            Span::raw(summary.components_removed.to_string()),
            Span::raw("  "),
            Span::styled("~ Modified: ", Style::default().fg(scheme.modified)),
            Span::raw(summary.components_modified.to_string()),
        ]),
        // Reconcile the Targets table's "Chg" column with the component
        // breakdown above: total_changes also counts dependency/graph/
        // metadata changes that no dashboard panel itemizes. (Kept compact —
        // the panel has exactly 7 interior rows at 120x40.)
        Line::from(vec![
            Span::styled("Total Changes: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                summary.total_changes.to_string(),
                Style::default().fg(scheme.primary),
            ),
            Span::styled(
                format!(
                    "  (comps {}, deps {}, graph {}, meta {})",
                    summary.components_added
                        + summary.components_removed
                        + summary.components_modified,
                    summary.dependencies_added + summary.dependencies_removed,
                    summary.graph_changes_count,
                    summary.metadata_changes_count,
                ),
                Style::default().fg(scheme.text_muted),
            ),
        ]),
        Line::from(vec![
            Span::styled("Vulnerabilities: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                format!("+{}", summary.vulnerabilities_introduced),
                Style::default().fg(scheme.removed),
            ),
            Span::raw(" / "),
            Span::styled(
                format!("-{}", summary.vulnerabilities_resolved),
                Style::default().fg(scheme.added),
            ),
        ]),
        Line::from(""),
        // Same metric, same name, same unit as the Matrix mode's
        // "Similarity: NN.N%" (it was previously the unitless
        // "Semantic Score: NN.N").
        Line::from(vec![
            Span::styled("Similarity: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                format!("{:.1}%", comp.diff.semantic_score),
                Style::default().fg(scheme.primary),
            ),
        ]),
    ];

    // Deviation gauge
    let gauge_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(8), Constraint::Length(3)])
        .split(area);

    let block = Block::default()
        .title(format!(" {} Details ", comp.target.name))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(scheme.info));

    let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });
    f.render_widget(paragraph, gauge_area[0]);

    let gauge_color = if deviation > 0.3 {
        scheme.removed
    } else if deviation > 0.1 {
        scheme.warning
    } else {
        scheme.added
    };

    let gauge = Gauge::default()
        .block(Block::default().title(" Deviation ").borders(Borders::ALL))
        .gauge_style(Style::default().fg(gauge_color))
        .percent((deviation * 100.0).clamp(0.0, 100.0) as u16)
        .label(format_deviation(deviation));

    f.render_widget(gauge, gauge_area[1]);
}

fn render_variable_components(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
) {
    let scheme = colors();

    if result.summary.variable_components.is_empty() {
        let block = Block::default()
            .title(" Variable Components (0 total) [v: drill-down] ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(scheme.critical));
        let placeholder = Paragraph::new(Line::from(Span::styled(
            "No variable components \u{2014} all targets match the baseline",
            Style::default().fg(scheme.text_muted),
        )))
        .block(block);
        f.render_widget(placeholder, area);
        return;
    }
    // Window around the selection sized to the REAL pane height (borders +
    // table header + spacing = 4 rows of chrome): with the selection bounds
    // now populated, the drill-down cursor can travel past the fold and must
    // stay visible at any terminal size.
    let visible_rows = (area.height.saturating_sub(4) as usize).max(1);
    let window_start = state
        .selected_variable_component
        .saturating_sub(visible_rows - 1);
    let rows: Vec<Row> = result
        .summary
        .variable_components
        .iter()
        .enumerate()
        .skip(window_start)
        .take(visible_rows)
        .map(|(i, vc)| {
            let is_selected = i == state.selected_variable_component;
            let base_style = if is_selected {
                Style::default()
                    .bg(scheme.selection)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };

            let impact_style = match vc.security_impact {
                SecurityImpact::Critical => {
                    base_style.fg(scheme.critical).add_modifier(Modifier::BOLD)
                }
                SecurityImpact::High => base_style.fg(scheme.high),
                SecurityImpact::Medium => base_style.fg(scheme.medium),
                SecurityImpact::Low => base_style.fg(scheme.low),
            };

            // App-standard severity chip instead of the hand-rolled "[C] ".
            let name_line = Line::from(vec![
                crate::tui::theme::severity_indicator(vc.security_impact.label()),
                Span::raw(" "),
                Span::styled(vc.name.clone(), base_style),
            ]);

            Row::new(vec![
                Cell::from(name_line),
                Cell::from(vc.version_spread.baseline.clone().unwrap_or_default())
                    .style(base_style),
                Cell::from(format!(
                    "{} versions",
                    vc.version_spread.unique_versions.len()
                ))
                .style(base_style),
                Cell::from(vc.security_impact.label()).style(impact_style),
            ])
        })
        .collect();

    let header = Row::new(vec!["Component", "Baseline", "Spread", "Impact"])
        .style(
            Style::default()
                .fg(scheme.primary)
                .add_modifier(Modifier::BOLD),
        )
        .bottom_margin(1);

    let widths = [
        Constraint::Percentage(40),
        Constraint::Percentage(20),
        Constraint::Percentage(20),
        Constraint::Percentage(20),
    ];

    let table = Table::new(rows, widths).header(header).block(
        Block::default()
            .title(format!(
                " Variable Components ({} total) [v: drill-down] ",
                result.summary.variable_components.len()
            ))
            .borders(Borders::ALL)
            .border_style(Style::default().fg(scheme.critical)),
    );

    f.render_widget(table, area);
}

fn render_status_bar(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
    status: Option<&str>,
) {
    let scheme = colors();
    let universal_count = result.summary.universal_components.len();
    let inconsistent_count = result.summary.inconsistent_components.len();

    let mut spans = vec![
        Span::styled("Universal: ", Style::default().fg(scheme.text_muted)),
        Span::styled(
            universal_count.to_string(),
            Style::default().fg(scheme.added),
        ),
        Span::raw("  "),
        Span::styled("Variable: ", Style::default().fg(scheme.text_muted)),
        Span::styled(
            result.summary.variable_components.len().to_string(),
            Style::default().fg(scheme.warning),
        ),
        Span::raw("  "),
        Span::styled("Inconsistent: ", Style::default().fg(scheme.text_muted)),
        Span::styled(
            inconsistent_count.to_string(),
            Style::default().fg(scheme.removed),
        ),
        Span::raw("  \u{2502}  "),
    ];
    // An open modal swallows every key, so the mode hints would all be false
    // advertising; show the modal's own keys instead (#198).
    let modal_hints: Option<&[(&str, &str)]> = if state.show_detail_modal {
        Some(&[("Esc", "close")])
    } else if state.show_variable_drill_down {
        Some(&[("j/k", "select"), ("Esc", "close")])
    } else {
        None
    };
    if let Some(hints) = modal_hints {
        super::matrix::extend_with_modal_hints(&mut spans, hints);
    } else {
        crate::tui::views::matrix_status_tail(&mut spans, area, status, "multi");
    }

    let block = Block::default().borders(Borders::ALL);
    let paragraph = Paragraph::new(Line::from(spans)).block(block);
    f.render_widget(paragraph, area);
}

/// Render cross-target analysis panel
fn render_cross_target_analysis(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    _state: &MultiDiffState,
) {
    let scheme = colors();

    // Find components that appear in most targets but with different versions
    let mut cross_target_info: Vec<Line> = vec![
        Line::from(vec![Span::styled(
            "Cross-Target Analysis",
            Style::default()
                .fg(scheme.primary)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(""),
    ];

    // Add inconsistent components summary
    cross_target_info.push(Line::from(vec![
        Span::styled(
            "Inconsistent Components: ",
            Style::default().fg(scheme.text_muted),
        ),
        Span::styled(
            result.summary.inconsistent_components.len().to_string(),
            Style::default().fg(scheme.warning),
        ),
    ]));

    // Show top variable components across targets with security badges
    for (i, vc) in result
        .summary
        .variable_components
        .iter()
        .take(8)
        .enumerate()
    {
        let versions_str = vc
            .version_spread
            .unique_versions
            .iter()
            .take(3)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");

        cross_target_info.push(Line::from(vec![
            Span::styled(
                format!("{}. ", i + 1),
                Style::default().fg(scheme.text_muted),
            ),
            crate::tui::theme::severity_indicator(vc.security_impact.label()),
            Span::raw(" "),
            Span::styled(&vc.name, Style::default().fg(scheme.text)),
            Span::raw(": "),
            Span::styled(versions_str, Style::default().fg(scheme.accent)),
        ]));
    }

    // Add deviation distribution
    cross_target_info.push(Line::from(""));
    cross_target_info.push(Line::from(vec![Span::styled(
        "Deviation Distribution:",
        Style::default().fg(scheme.text_muted),
    )]));

    let high_dev = result
        .comparisons
        .iter()
        .filter(|c| {
            result
                .summary
                .deviation_scores
                .get(&c.target.name)
                .copied()
                .unwrap_or(0.0)
                > 0.3
        })
        .count();
    let med_dev = result
        .comparisons
        .iter()
        .filter(|c| {
            let d = result
                .summary
                .deviation_scores
                .get(&c.target.name)
                .copied()
                .unwrap_or(0.0);
            d > 0.1 && d <= 0.3
        })
        .count();
    let low_dev = result.comparisons.len() - high_dev - med_dev;

    cross_target_info.push(Line::from(vec![
        Span::styled("  High (>30%): ", Style::default().fg(scheme.removed)),
        Span::raw(high_dev.to_string()),
        Span::raw("  "),
        Span::styled("Med (10-30%): ", Style::default().fg(scheme.warning)),
        Span::raw(med_dev.to_string()),
        Span::raw("  "),
        Span::styled("Low (<10%): ", Style::default().fg(scheme.added)),
        Span::raw(low_dev.to_string()),
    ]));

    let block = Block::default()
        .title(" Cross-Target Analysis ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(scheme.info));

    let paragraph = Paragraph::new(cross_target_info)
        .block(block)
        .wrap(Wrap { trim: true });
    f.render_widget(paragraph, area);
}

/// Render detail modal for selected target
fn render_detail_modal(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
) {
    let scheme = colors();

    // Create modal area (centered, 80% width, 70% height)
    let modal_width = area.width * 80 / 100;
    let modal_height = area.height * 70 / 100;
    let modal_x = (area.width - modal_width) / 2;
    let modal_y = (area.height - modal_height) / 2;
    let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height);

    // Clear the area
    f.render_widget(Clear, modal_area);

    let Some(comp) = ordered_comparison_indices(result, state)
        .get(state.selected_target)
        .and_then(|&raw| result.comparisons.get(raw))
    else {
        return;
    };

    let deviation = result
        .summary
        .deviation_scores
        .get(&comp.target.name)
        .copied()
        .unwrap_or(0.0);

    let mut lines = vec![
        Line::from(vec![
            Span::styled("Target: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                &comp.target.name,
                Style::default()
                    .fg(scheme.primary)
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("Deviation: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                format_deviation(deviation),
                Style::default().fg(if deviation > 0.3 {
                    scheme.removed
                } else {
                    scheme.added
                }),
            ),
            Span::raw("  "),
            Span::styled("Similarity: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                format!("{:.1}%", comp.diff.semantic_score),
                Style::default().fg(scheme.primary),
            ),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "Component Changes:",
            Style::default().fg(scheme.text_muted),
        )]),
        Line::from(vec![
            Span::styled("  + Added: ", Style::default().fg(scheme.added)),
            Span::raw(comp.diff.summary.components_added.to_string()),
            Span::raw("  "),
            Span::styled("  - Removed: ", Style::default().fg(scheme.removed)),
            Span::raw(comp.diff.summary.components_removed.to_string()),
            Span::raw("  "),
            Span::styled("  ~ Modified: ", Style::default().fg(scheme.modified)),
            Span::raw(comp.diff.summary.components_modified.to_string()),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "Vulnerabilities:",
            Style::default().fg(scheme.text_muted),
        )]),
        Line::from(vec![
            Span::styled("  Introduced: ", Style::default().fg(scheme.removed)),
            Span::raw(comp.diff.summary.vulnerabilities_introduced.to_string()),
            Span::raw("  "),
            Span::styled("  Resolved: ", Style::default().fg(scheme.added)),
            Span::raw(comp.diff.summary.vulnerabilities_resolved.to_string()),
        ]),
        Line::from(""),
    ];

    // Add top component changes
    lines.push(Line::from(vec![Span::styled(
        "Top Added Components:",
        Style::default().fg(scheme.added),
    )]));
    for comp_change in comp.diff.components.added.iter().take(5) {
        lines.push(Line::from(vec![
            Span::raw("  + "),
            Span::styled(&comp_change.name, Style::default().fg(scheme.text)),
            Span::raw(" "),
            Span::styled(
                comp_change.new_version.as_deref().unwrap_or(""),
                Style::default().fg(scheme.text_muted),
            ),
        ]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(vec![Span::styled(
        "Top Removed Components:",
        Style::default().fg(scheme.removed),
    )]));
    for comp_change in comp.diff.components.removed.iter().take(5) {
        lines.push(Line::from(vec![
            Span::raw("  - "),
            Span::styled(&comp_change.name, Style::default().fg(scheme.text)),
            Span::raw(" "),
            Span::styled(
                comp_change.old_version.as_deref().unwrap_or(""),
                Style::default().fg(scheme.text_muted),
            ),
        ]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("Press ", Style::default().fg(scheme.text_muted)),
        Span::styled("Esc", Style::default().fg(scheme.primary)),
        Span::styled(" to close", Style::default().fg(scheme.text_muted)),
    ]));

    let block = Block::default()
        .title(format!(" {} Details ", comp.target.name))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(scheme.accent))
        .style(Style::default().bg(scheme.background_alt));

    let paragraph = Paragraph::new(lines).block(block).wrap(Wrap { trim: true });
    f.render_widget(paragraph, modal_area);
}

/// Render variable component drill-down modal
fn render_variable_drill_down(
    f: &mut Frame,
    area: Rect,
    result: &MultiDiffResult,
    state: &MultiDiffState,
) {
    let scheme = colors();

    // Create modal area
    let modal_width = area.width * 75 / 100;
    let modal_height = area.height * 60 / 100;
    let modal_x = (area.width - modal_width) / 2;
    let modal_y = (area.height - modal_height) / 2;
    let modal_area = Rect::new(modal_x, modal_y, modal_width, modal_height);

    f.render_widget(Clear, modal_area);

    let Some(vc) = result
        .summary
        .variable_components
        .get(state.selected_variable_component)
    else {
        return;
    };

    // The component name is already the modal's block title; repeating it as
    // the first body line just costs a row.
    let mut lines = vec![
        Line::from(vec![
            Span::styled("Security Impact: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                vc.security_impact.label(),
                match vc.security_impact {
                    SecurityImpact::Critical => Style::default().fg(scheme.critical),
                    SecurityImpact::High => Style::default().fg(scheme.high),
                    SecurityImpact::Medium => Style::default().fg(scheme.medium),
                    SecurityImpact::Low => Style::default().fg(scheme.low),
                },
            ),
        ]),
        Line::from(""),
        Line::from(vec![
            Span::styled("Baseline Version: ", Style::default().fg(scheme.text_muted)),
            Span::styled(
                vc.version_spread.baseline.as_deref().unwrap_or("N/A"),
                Style::default().fg(scheme.primary),
            ),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "Version Spread:",
            Style::default().fg(scheme.text_muted),
        )]),
    ];

    // Show all unique versions
    for version in &vc.version_spread.unique_versions {
        lines.push(Line::from(vec![
            Span::raw("  • "),
            Span::styled(version, Style::default().fg(scheme.accent)),
        ]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(vec![Span::styled(
        "Targets with this component:",
        Style::default().fg(scheme.text_muted),
    )]));

    // Presence comes from the engine's per-SBOM version map
    // (targets_with_component), NOT from the pair-diff buckets: an id in
    // `components.removed` means the target LACKS the component, and the old
    // added||removed||modified test listed exactly those targets as having it.
    // The version shown is the target's own: the pairwise change entry's new
    // version when the pair diff touched it, else the baseline version
    // (present and unchanged).
    let present: Vec<(&str, String)> = result
        .comparisons
        .iter()
        .filter(|comp| {
            vc.targets_with_component
                .iter()
                .any(|t| t == &comp.target.name)
        })
        .map(|comp| {
            let version = comp
                .diff
                .components
                .modified
                .iter()
                .chain(comp.diff.components.added.iter())
                .find(|c| crate::diff::strip_purl_version(&c.id) == vc.id)
                .and_then(|c| c.new_version.clone())
                .or_else(|| vc.version_spread.baseline.clone())
                .unwrap_or_else(|| "version unknown".to_string());
            (comp.target.name.as_str(), version)
        })
        .collect();

    if present.is_empty() {
        lines.push(Line::from(vec![Span::styled(
            "  (none — only the baseline has it)",
            Style::default().fg(scheme.text_muted),
        )]));
    }
    let shown = present.len().min(10);
    for (name, version) in &present[..shown] {
        lines.push(Line::from(vec![
            Span::raw("  "),
            Span::styled((*name).to_string(), Style::default().fg(scheme.text)),
            Span::raw(": "),
            Span::styled(version.clone(), Style::default().fg(scheme.accent)),
        ]));
    }
    if present.len() > shown {
        lines.push(Line::from(vec![Span::styled(
            format!("  … and {} more", present.len() - shown),
            Style::default().fg(scheme.text_muted),
        )]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("j/k", Style::default().fg(scheme.primary)),
        Span::raw(": navigate  "),
        Span::styled("Esc", Style::default().fg(scheme.primary)),
        Span::raw(": close"),
    ]));

    let block = Block::default()
        .title(format!(" Variable Component: {} ", vc.name))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(scheme.warning))
        .style(Style::default().bg(scheme.background_alt));

    let paragraph = Paragraph::new(lines).block(block).wrap(Wrap { trim: true });
    f.render_widget(paragraph, modal_area);
}

/// Render search overlay
fn render_search_overlay(f: &mut Frame, area: Rect, state: &MultiDiffState) {
    crate::tui::views::render_multi_search_bar(f, area, "Search: ", &state.search);
}

/// Panels in the multi-dashboard
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MultiDashboardPanel {
    Targets,
    Details,
}

#[cfg(test)]
mod ordering_tests {
    use super::*;
    use crate::tui::test_support::demo_multi_diff;

    fn state(
        sort: MultiViewSortBy,
        dir: SortDirection,
        filter: MultiViewFilterPreset,
    ) -> MultiDiffState {
        let mut s = MultiDiffState::new();
        s.sort_by = sort;
        s.sort_direction = dir;
        s.filter_preset = filter;
        s
    }

    #[test]
    fn name_ascending_is_a_to_z_and_reorders_raw_indices() {
        let result = demo_multi_diff();
        let order = ordered_comparison_indices(
            &result,
            &state(
                MultiViewSortBy::Name,
                SortDirection::Ascending,
                MultiViewFilterPreset::All,
            ),
        );
        // A→Z by name (the bug rendered Ascending as Z→A).
        let names: Vec<&str> = order
            .iter()
            .map(|&i| result.comparisons[i].target.name.as_str())
            .collect();
        let mut sorted = names.clone();
        sorted.sort_unstable();
        assert_eq!(names, sorted, "Ascending Name sort should be A→Z");
        // Display order differs from raw order, so resolving details by the raw
        // `selected_target` (the old bug) would show a different comparison than the
        // highlighted row. Guards that this fixture actually exercises the defect.
        assert_ne!(order, (0..result.comparisons.len()).collect::<Vec<_>>());
        // Still a permutation of every comparison (filter = All).
        let mut perm = order.clone();
        perm.sort_unstable();
        assert_eq!(perm, (0..result.comparisons.len()).collect::<Vec<_>>());
    }

    #[test]
    fn descending_name_is_the_reverse_of_ascending() {
        let result = demo_multi_diff();
        let asc = ordered_comparison_indices(
            &result,
            &state(
                MultiViewSortBy::Name,
                SortDirection::Ascending,
                MultiViewFilterPreset::All,
            ),
        );
        let mut desc = ordered_comparison_indices(
            &result,
            &state(
                MultiViewSortBy::Name,
                SortDirection::Descending,
                MultiViewFilterPreset::All,
            ),
        );
        desc.reverse();
        assert_eq!(asc, desc);
    }

    #[test]
    fn with_vulnerabilities_filter_keeps_only_matching() {
        let result = demo_multi_diff();
        let order = ordered_comparison_indices(
            &result,
            &state(
                MultiViewSortBy::Name,
                SortDirection::Ascending,
                MultiViewFilterPreset::WithVulnerabilities,
            ),
        );
        assert!(order.len() <= result.comparisons.len());
        for &i in &order {
            assert!(
                result.comparisons[i]
                    .diff
                    .summary
                    .vulnerabilities_introduced
                    > 0
            );
        }
    }
}

#[cfg(test)]
mod truthfulness_tests {
    use super::*;
    use crate::tui::test_support::{demo_multi_diff, pin_theme, render_to_text};

    #[test]
    fn format_deviation_is_percent_with_unit() {
        assert_eq!(format_deviation(0.0), "0.0%");
        assert_eq!(format_deviation(0.465), "46.5%");
        // Rounds (never truncates), and exact saturation drops the decimal so
        // the narrow column can't clip it to a unitless "100.0".
        assert_eq!(format_deviation(0.4649), "46.5%");
        assert_eq!(format_deviation(0.9996), "100%");
        assert_eq!(format_deviation(1.0), "100%");
    }

    /// The dashboard renders deviations as real percentages (<= 100%), the
    /// similarity metric carries the same name and unit as Matrix mode, and
    /// the Total Changes line reconciles the Chg column with the component
    /// breakdown.
    #[test]
    fn dashboard_renders_percentages_not_double_scaled_values() {
        pin_theme();
        let result = demo_multi_diff();
        assert!(
            result.summary.max_deviation <= 1.0,
            "engine contract: deviation is a 0-1 fraction"
        );
        let mut state = MultiDiffState::new();
        state.total_targets = result.comparisons.len();
        state.total_variable_components = result.summary.variable_components.len();

        let text = render_to_text(120, 40, |f| {
            render_multi_dashboard(f, f.area(), &result, &state, None);
        });

        let expected_max = format!(
            "Max Deviation: {}",
            format_deviation(result.summary.max_deviation)
        );
        assert!(
            text.contains(&expected_max),
            "max deviation must render as a true percentage:\n{text}"
        );
        // The double-scaled artifacts (10000.0% / 7000.0% style values).
        for bogus in ["10000", "7000.0%", "4651.2%", "4225.8%"] {
            assert!(
                !text.contains(bogus),
                "no >100% deviation may render ({bogus}):\n{text}"
            );
        }
        assert!(
            text.contains("Similarity:") && !text.contains("Semantic Score"),
            "the similarity metric must use the Matrix mode's name and % unit:\n{text}"
        );
        assert!(
            text.contains("Total Changes:") && text.contains("comps "),
            "the Chg column must be reconciled by the Total Changes breakdown:\n{text}"
        );
    }

    /// Status-bar partition counts are per logical component: no package may
    /// appear twice in Inconsistent because of a version bump, and a version
    /// bump must surface in Variable.
    #[test]
    fn status_counts_are_logical_not_version_qualified() {
        let result = demo_multi_diff();
        let mut names: Vec<&str> = result
            .summary
            .inconsistent_components
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        let total = names.len();
        names.sort_unstable();
        names.dedup();
        assert_eq!(
            names.len(),
            total,
            "a version-bumped package must not count twice in Inconsistent"
        );
        assert!(
            result
                .summary
                .variable_components
                .iter()
                .any(|vc| vc.name == "lodash"),
            "a purl-versioned upgrade (lodash 4.17.20 -> 4.17.21) must be Variable"
        );
    }

    /// The drill-down's "Targets with this component" lists only targets that
    /// actually contain the component (removed-from-target used to count as
    /// presence) and shows each target's own version.
    #[test]
    fn variable_drilldown_lists_only_targets_that_have_the_component() {
        pin_theme();
        let result = demo_multi_diff();
        let idx = result
            .summary
            .variable_components
            .iter()
            .position(|vc| vc.name == "acme-webapp")
            .expect("demo fixture has the acme-webapp variable component");

        let mut state = MultiDiffState::new();
        state.total_targets = result.comparisons.len();
        state.total_variable_components = result.summary.variable_components.len();
        state.selected_variable_component = idx;
        state.show_variable_drill_down = true;

        let text = render_to_text(120, 40, |f| {
            render_multi_dashboard(f, f.area(), &result, &state, None);
        });

        assert!(
            text.contains("webapp: 2.0.0"),
            "the target that has the component must list it with ITS version:\n{text}"
        );
        assert!(
            !text.contains("ai-service:"),
            "ai-service does not contain acme-webapp and must not be listed:\n{text}"
        );
    }
}

#[cfg(test)]
mod deviation_band_tests {
    use super::deviation_band;

    /// Bands map to the theme's severity tints with symbolic magnitude glyphs
    /// that survive NO_COLOR.
    #[test]
    fn deviation_band_maps_to_theme_tint() {
        crate::tui::test_support::pin_theme();
        let scheme = crate::tui::theme::colors();
        assert_eq!(deviation_band(0.55), ("critical", "\u{2587}"));
        assert_eq!(deviation_band(0.35), ("high", "\u{2585}"));
        assert_eq!(deviation_band(0.15), ("medium", "\u{2583}"));
        assert_eq!(deviation_band(0.05), ("low", "\u{2581}"));
        // Each named band resolves through the theme's per-scheme tints.
        assert_eq!(
            scheme.severity_bg_tint(deviation_band(0.55).0),
            scheme.severity_bg_tint("critical")
        );
    }
}