stama 1.1.1

A terminal user interface for monitoring and managing slurm jobs.
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
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEventKind};
use ratatui::{
    layout::Flex,
    prelude::*,
    style::{Color, Style},
    widgets::*,
};
use ratatui_textarea::{CursorMove, TextArea};

use crate::app::Action;
use crate::columns::JobColumn;
use crate::job::{explain_reason, reason_code, Job, JobStatus};
use crate::job_rows::JobRow;
use crate::joblist::{JobList, JobListAction};
use crate::menus::help::HelpContext;
use crate::menus::OpenMenu;
use crate::mouse_input::MouseInput;

#[derive(Debug, Clone, PartialEq)]
pub enum WindowFocus {
    JobDetails,
    Log,
}

#[derive(Default)]
pub struct MouseAreas {
    pub joblist_title: Rect,
    pub squeue_command: Rect,
    pub details_title: Rect,
    pub bottom_symbol: Rect,
    pub log_title: Rect,
    pub joblist: Rect,
    pub categories: Vec<Rect>,
}

pub struct JobOverview {
    pub collapsed_top: bool,               // if the job list is collapsed
    pub collapsed_bot: bool,               // if the job details are collapsed
    pub focus: WindowFocus,                // which part of the window is in focus
    pub state: TableState,                 // the state of the job list
    pub mouse_areas: MouseAreas,           // the mouse areas of the window
    pub squeue_command: TextArea<'static>, // the squeue command
    pub edit_squeue: bool,                 // if the squeue command is being edited
    pub refresh_rate: usize,               // the refresh rate of the window
    pub log_height: u16,                   // the height of the log section
    pub columns: Vec<JobColumn>,           // the configured job table columns
    pub filter_prompt: bool,               // if the filter prompt is open
    // the filter input; mirrors the joblist's active display filter
    // (it is applied live on every keystroke)
    pub filter_input: String,
}

// ====================================================================
//  CONSTRUCTOR
// ====================================================================

impl JobOverview {
    pub fn new(refresh_rate: usize, squeue_command: &str, columns: Vec<JobColumn>) -> Self {
        let mut state = TableState::default();
        state.select(Some(0));
        // create one mouse area per configured column
        let mut mouse_areas = MouseAreas::default();
        for _ in 0..columns.len() {
            mouse_areas.categories.push(Rect::default());
        }
        let command = squeue_command.to_string();
        let mut textarea = TextArea::from([command]);
        textarea.move_cursor(CursorMove::End);
        Self {
            collapsed_top: false,
            collapsed_bot: true,
            focus: WindowFocus::JobDetails,
            state,
            mouse_areas,
            squeue_command: textarea,
            edit_squeue: false,
            refresh_rate,
            log_height: 0,
            columns,
            filter_prompt: false,
            filter_input: String::new(),
        }
    }
}

// ====================================================================
//  METHODS
// ====================================================================

impl JobOverview {
    fn get_squeue_command(&self) -> String {
        self.squeue_command.lines().join("\n")
    }

    fn exit_squeue_edit(&mut self, action: &mut Action) {
        let new_command = self.get_squeue_command();
        *action = Action::UpdateJobList(JobListAction::UpdateSqueueCommand(new_command));
        self.edit_squeue = false;
    }

    /// Applies the current filter input to the job list (an empty
    /// input clears the filter). Called on every prompt keystroke, so
    /// the visible rows narrow live while typing.
    fn apply_filter(&self, action: &mut Action) {
        *action = Action::UpdateJobList(JobListAction::SetFilter(self.filter_input.clone()));
    }

    /// Clears the filter input and the joblist's display filter.
    fn clear_filter(&mut self, action: &mut Action) {
        self.filter_input.clear();
        self.apply_filter(action);
    }
}

// ====================================================================
//  RENDERING
// ====================================================================

impl JobOverview {
    pub fn render(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        let mut constraints = vec![Constraint::Length(1)];
        if self.collapsed_top && self.collapsed_bot {
            constraints.push(Constraint::Length(1));
            constraints.push(Constraint::Length(1));
        } else if self.collapsed_top && !self.collapsed_bot {
            constraints.push(Constraint::Length(1));
            constraints.push(Constraint::Min(1));
        } else if !self.collapsed_top && self.collapsed_bot {
            constraints.push(Constraint::Min(1));
            constraints.push(Constraint::Length(1));
        } else {
            constraints.push(Constraint::Percentage(30));
            constraints.push(Constraint::Percentage(70));
        }

        // create a layout for the title
        let layout = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints.as_slice())
            .split(*area);

        // render the title, job list, and job details
        self.render_title(f, &layout[0]);
        self.render_joblist(f, &layout[1], jobs);
        self.render_bottom_section(f, &layout[2], jobs);
    }

    fn render_title(&self, f: &mut Frame, area: &Rect) {
        f.render_widget(
            Paragraph::new("SLURM TASK MANAGER")
                .style(Style::default().fg(Color::Red))
                .alignment(Alignment::Center),
            *area,
        );
    }

    // ----------------------------------------------------------------------
    // RENDERING THE JOB LIST
    // ----------------------------------------------------------------------

    fn render_joblist(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        // set the state of the table
        self.state.select(Some(jobs.get_index()));
        match self.collapsed_top {
            true => self.render_joblist_collapsed(f, area, jobs),
            false => self.render_joblist_extended(f, area, jobs),
        }
    }

    fn render_joblist_collapsed(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        // update the mouse areas
        self.mouse_areas.joblist_title = *area;
        self.mouse_areas.joblist = Rect::default();

        let job = match jobs.get_job() {
            Some(job) => job,
            None => {
                let title = "▶ Job list (collapsed)".to_string();
                f.render_widget(Line::from(title), *area);
                return;
            }
        };

        let col = get_job_color(job);

        // the collapsed one-line row shows the configured columns
        let mut content_strings = vec!["▶ Job: ".to_string()];
        content_strings.extend(self.columns.iter().map(|column| column.cell(job)));

        let constraints = content_strings
            .iter()
            .map(|s| Constraint::Min(s.len() as u16 + 2))
            .collect::<Vec<Constraint>>();

        let layout = Layout::default()
            .direction(Direction::Horizontal)
            .constraints::<Vec<Constraint>>(constraints)
            .split(*area);

        // update the mouse areas of the categories
        for category in self.mouse_areas.categories.iter_mut() {
            *category = Rect::default();
        }

        content_strings.iter().enumerate().for_each(|(i, s)| {
            let line = Line::from(s.clone()).style(Style::default().fg(col));
            f.render_widget(line, layout[i]);
        });
    }

    fn render_joblist_extended(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        let title = "▼ Job list: ";
        let title_len = title.len() as u16;

        let refresh_rate = format!("{} ms", self.refresh_rate);

        let mut block = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .title_top(Line::from(refresh_rate).alignment(Alignment::Right));

        // the filter prompt / active-filter indicator in the bottom
        // border of the job list (only rendered while filtering, so
        // the frame is unchanged when no filter is involved)
        if self.filter_prompt {
            block = block.title_bottom(
                Line::from(format!(" filter: {}", self.filter_input))
                    .alignment(Alignment::Left)
                    .style(Style::default().fg(Color::Yellow)),
            );
        } else if let Some(text) = jobs.filter_text() {
            let indicator = format!(
                " filter: {} ({}/{}) ",
                text,
                jobs.filter_match_count(),
                jobs.jobs.len()
            );
            block = block.title_bottom(Line::from(indicator).alignment(Alignment::Left));
        }

        // update the mouse areas
        // clip manually constructed rects to the frame area: rendering a
        // widget into a rect that extends beyond the buffer panics in
        // ratatui (Buffer::index_of) on narrow terminals
        let mut top_row = *area;
        top_row.height = 1;
        top_row.width = title_len - 2;
        let top_row = top_row.intersection(f.area());
        self.mouse_areas.joblist_title = top_row;
        let mut joblist_area = block.inner(*area);

        f.render_widget(block.clone(), *area);

        // render the squeue command
        let buffer = self.get_squeue_command();
        let mut squeue_rect = *area;
        squeue_rect.height = 1;
        squeue_rect.width = buffer.len() as u16 + 1;
        squeue_rect.x = title_len - 1;
        let squeue_rect = squeue_rect.intersection(f.area());
        self.mouse_areas.squeue_command = squeue_rect;
        if !squeue_rect.is_empty() {
            self.render_squeue_command(f, &squeue_rect);
        }

        if jobs.is_empty() {
            self.render_empty_joblist(f, &joblist_area);
            return;
        }

        // there are jobs, but the active filter hides all of them
        // (jobs.len() counts the *visible* rows, jobs.is_empty() the
        // unfiltered job list, hence no is_empty() shorthand here)
        let visible_rows = jobs.len();
        if visible_rows == 0 {
            let text = Span::styled("No jobs match the filter", Style::default().fg(Color::Gray));
            let paragraph = Paragraph::new(text).alignment(Alignment::Center);
            f.render_widget(paragraph, joblist_area);
            return;
        }

        // ----------------------------------------------
        //  CREATE THE JOB LIST
        // ----------------------------------------------

        // Create the titles for the configured columns
        let mut title_names = self
            .columns
            .iter()
            .map(|column| Span::raw(column.header()))
            .collect::<Vec<Span>>();
        // mark the sort category with a direction arrow (the sort
        // category may not be displayed; then no title is marked)
        let cat_ind = self
            .columns
            .iter()
            .position(|column| column == jobs.get_sort_category());
        if let Some(cat_ind) = cat_ind {
            let new_title = format!(
                "{} {}",
                self.columns[cat_ind].header(),
                if jobs.is_reverse() { "" } else { "" }
            );
            title_names[cat_ind] = Span::styled(new_title, Style::default().fg(Color::Blue));
        }

        // Create the rows for the job list: single jobs, array-group
        // headers and (for expanded groups) indented task rows
        let rows = jobs
            .rows()
            .iter()
            .map(|row| self.render_row(row, jobs))
            .collect::<Vec<Row>>();

        // Create the widths for the columns
        let widths = self
            .columns
            .iter()
            .map(|column| Constraint::Min(column.min_width()))
            .collect::<Vec<Constraint>>();

        // set the flex and spacing for the columns

        let flex = Flex::SpaceBetween;
        let column_spacing = 1;

        // get the rects for the columnss and update the mouse areas
        let mut rects = Layout::horizontal(widths.clone())
            .flex(flex)
            .spacing(column_spacing)
            .split(joblist_area);
        // set height of each rect to 1
        rects = rects
            .iter()
            .map(|rect| {
                let mut r = *rect;
                r.height = 1;
                r
            })
            .collect();
        self.mouse_areas.categories = rects.to_vec();

        // create the table

        let table = Table::new(rows, widths)
            .column_spacing(column_spacing)
            .header(Row::new(title_names).style(Style::new().bold()))
            .flex(flex)
            .row_highlight_style(Style::new().reversed());

        // render the table
        f.render_stateful_widget(table, joblist_area, &mut self.state);

        // update the mouse areas
        joblist_area.y += 1; // remove the header row
        joblist_area.height = joblist_area.height.saturating_sub(1);
        self.mouse_areas.joblist = joblist_area;
    }

    /// Builds one table row for a display row of the job list.
    fn render_row<'a>(&self, row: &JobRow, jobs: &'a JobList) -> Row<'a> {
        match row {
            JobRow::Single { job_index } => {
                let job = &jobs.jobs[*job_index];
                Row::new(
                    self.columns
                        .iter()
                        .map(|column| column.cell(job))
                        .collect::<Vec<String>>(),
                )
                .style(Style::default().fg(get_job_color(job)))
            }
            JobRow::Group {
                base_id,
                task_indices,
                expanded,
            } => {
                let tasks: Vec<&Job> = task_indices.iter().map(|&i| &jobs.jobs[i]).collect();
                Row::new(
                    self.columns
                        .iter()
                        .map(|column| column.group_cell(base_id, &tasks, *expanded))
                        .collect::<Vec<String>>(),
                )
                .style(Style::default().fg(get_group_color(&tasks)))
            }
            JobRow::Task { job_index, last } => {
                let job = &jobs.jobs[*job_index];
                Row::new(
                    self.columns
                        .iter()
                        .map(|column| {
                            // indent the id with a tree glyph to show the
                            // task belongs to the group header above
                            if *column == JobColumn::Id {
                                let glyph = if *last { "" } else { "" };
                                format!("{} {}", glyph, job.id)
                            } else {
                                column.cell(job)
                            }
                        })
                        .collect::<Vec<String>>(),
                )
                .style(Style::default().fg(get_job_color(job)))
            }
        }
    }

    fn render_squeue_command(&mut self, f: &mut Frame, area: &Rect) {
        let textarea = &mut self.squeue_command;
        if self.edit_squeue {
            textarea.set_cursor_style(Style::default().bg(Color::Red));
            textarea.set_cursor_line_style(
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            );
        } else {
            textarea.set_cursor_line_style(Style::default());
            textarea.set_cursor_style(Style::default());
        }
        f.render_widget(&*textarea, *area);
    }

    fn render_empty_joblist(&self, f: &mut Frame, area: &Rect) {
        let text = "No jobs found";
        let text = Span::styled(text, Style::default().fg(Color::Gray));
        let paragraph = Paragraph::new(text).alignment(Alignment::Center);
        f.render_widget(paragraph, *area);
    }

    // ----------------------------------------------------------------------
    // RENDERING THE JOB DETAILS AND LOG SECTION
    // ----------------------------------------------------------------------
    fn render_bottom_section(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        self.log_height = area.height.saturating_sub(2);
        match self.collapsed_bot {
            true => self.render_bottom_collapsed(f, area),
            false => self.render_bottom_extended(f, area, jobs),
        }
    }

    fn render_bottom_collapsed(&mut self, f: &mut Frame, area: &Rect) {
        let title = vec![
            Span::raw(""),
            Span::raw("1. Job details"),
            Span::raw("  "),
            Span::raw("2. Log"),
        ];

        // update the mouse areas
        self.update_bottom_mouse_positions(area, title.clone(), 0);

        let line = Line::from(title).style(Style::default().fg(Color::Gray));
        f.render_widget(line, *area);
    }

    fn render_bottom_extended(&mut self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        let mut title = vec![
            Span::raw(""),
            Span::raw("1. Job details"),
            Span::raw("  "),
            Span::raw("2. Log"),
        ];

        // update the mouse areas
        self.update_bottom_mouse_positions(area, title.clone(), 1);

        match self.focus {
            WindowFocus::JobDetails => {
                title[1] = Span::styled("1. Job details", Style::default().fg(Color::Blue));
            }
            WindowFocus::Log => {
                title[3] = Span::styled("2. Log", Style::default().fg(Color::Blue));
            }
        }

        let block = Block::default()
            .title(title)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded);

        f.render_widget(block.clone(), *area);
        let rect = block.inner(*area);
        match self.focus {
            WindowFocus::JobDetails => {
                self.render_job_details(f, &rect, jobs);
            }
            WindowFocus::Log => {
                self.render_log(f, &rect, jobs);
            }
        }
    }

    fn render_job_details(&self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        // insight lines about the selected job (pending reason or
        // seff-style efficiency stats) are shown above the scontrol text
        let mut lines: Vec<Line> = Vec::new();
        if let Some(job) = jobs.get_job() {
            append_pending_reason_lines(&mut lines, job);
            append_efficiency_lines(&mut lines, job);
        }
        for line in jobs.get_job_details().lines() {
            lines.push(Line::from(line.to_string()));
        }

        let paragraph = Paragraph::new(Text::from(lines))
            .alignment(Alignment::Left)
            .wrap(Wrap { trim: true });

        f.render_widget(paragraph, *area);
    }

    fn render_log(&self, f: &mut Frame, area: &Rect, jobs: &JobList) {
        let mut paragraph = Paragraph::new(jobs.get_log_tail())
            .alignment(Alignment::Left)
            .wrap(Wrap { trim: true });

        // calculate the scroll offset such that the last line is visible
        let lines = paragraph.line_count(area.width);
        let offset = (lines as u16).saturating_sub(self.log_height);
        paragraph = paragraph.scroll((offset, 0));

        f.render_widget(paragraph, *area);
    }

    fn update_bottom_mouse_positions(&mut self, area: &Rect, title: Vec<Span>, offset: u16) {
        if title.len() != 4 {
            return;
        }
        let mut top_row = *area;
        top_row.height = 1;
        let mut symbol = top_row;
        symbol.width = title[0].width() as u16;
        symbol.x += offset;
        let mut details_title = top_row;
        details_title.width = title[1].width() as u16;
        details_title.x += symbol.width + symbol.x;
        let mut log_title = top_row;
        log_title.width = title[3].width() as u16;
        log_title.x += details_title.width + details_title.x + 2;
        // clip the manually constructed rects to the containing area so the
        // mouse areas never extend beyond the rendered region
        self.mouse_areas.bottom_symbol = symbol.intersection(*area);
        self.mouse_areas.details_title = details_title.intersection(*area);
        self.mouse_areas.log_title = log_title.intersection(*area);
    }
}

fn get_job_color(job: &Job) -> Color {
    match job.status {
        JobStatus::Running => Color::Green,
        JobStatus::Pending => Color::Yellow,
        JobStatus::Completing => Color::Yellow,
        JobStatus::Completed => Color::Gray,
        JobStatus::Failed => Color::Red,
        JobStatus::Timeout => Color::Red,
        JobStatus::Cancelled => Color::Red,
        JobStatus::Unknown => Color::Red,
    }
}

/// The color of an array-group header row: the "most active" status of
/// its tasks wins (running > pending/completing > failed > completed).
fn get_group_color(tasks: &[&Job]) -> Color {
    if tasks.iter().any(|job| job.status == JobStatus::Running) {
        Color::Green
    } else if tasks
        .iter()
        .any(|job| matches!(job.status, JobStatus::Pending | JobStatus::Completing))
    {
        Color::Yellow
    } else if tasks.iter().any(|job| {
        matches!(
            job.status,
            JobStatus::Failed | JobStatus::Timeout | JobStatus::Cancelled | JobStatus::Unknown
        )
    }) {
        Color::Red
    } else {
        Color::Gray
    }
}

// ====================================================================
//  JOB-DETAILS INSIGHT LINES (pending reason, efficiency stats)
// ====================================================================

/// For a pending job, prepends a one-line explanation of why it is
/// still waiting (from the squeue "Reason" field).
fn append_pending_reason_lines(lines: &mut Vec<Line>, job: &Job) {
    if job.status != JobStatus::Pending {
        return;
    }
    let raw = job.reason.as_deref().unwrap_or("None");
    let code = reason_code(raw);
    let text = match explain_reason(code) {
        // "None"/empty carry no information, so no code is shown
        Some(explanation) if code.is_empty() || code == "None" => {
            format!("Pending — {}", explanation)
        }
        Some(explanation) => format!("Pending — {}: {}", code, explanation),
        // unknown codes: show the raw reason reported by squeue
        None => format!("Pending — {}", raw),
    };
    lines.push(Line::from(Span::styled(
        text,
        Style::default().fg(Color::Yellow).bold(),
    )));
    lines.push(Line::default());
}

/// The width (in cells) of the efficiency bars.
const EFFICIENCY_BAR_WIDTH: usize = 20;

/// For a started job with fetched stats, prepends seff-style
/// efficiency bars (CPU, memory, share of the time limit used).
fn append_efficiency_lines(lines: &mut Vec<Line>, job: &Job) {
    let stats = match &job.stats {
        Some(stats) if stats.has_any() => stats,
        // degrade gracefully: no stats, no extra lines
        _ => return,
    };
    lines.push(Line::from(Span::styled(
        "Efficiency  (Mem: red = underused · Time: red = near limit)",
        Style::default().fg(Color::Gray),
    )));
    if let Some(mem) = stats.mem_efficiency {
        lines.push(efficiency_line("Mem ", mem, utilization_color(mem)));
    }
    if let Some(time) = stats.elapsed_frac_of_limit {
        lines.push(efficiency_line("Time", time, time_limit_color(time)));
    }
    lines.push(Line::default());
}

/// Builds one efficiency line, e.g. "CPU   85% ████████████████▌░░░".
fn efficiency_line(label: &str, fraction: f64, color: Color) -> Line<'static> {
    Line::from(vec![
        Span::raw(format!("{} ", label)),
        Span::styled(
            format!(
                "{:>4.0}% {}",
                fraction * 100.0,
                bar_string(fraction, EFFICIENCY_BAR_WIDTH)
            ),
            Style::default().fg(color),
        ),
    ])
}

/// Renders a fraction (clamped to 0..=1) as a bar of block characters
/// with eighth-block resolution, padded to `width` cells.
fn bar_string(fraction: f64, width: usize) -> String {
    const PARTIAL_BLOCKS: [char; 8] = [' ', '', '', '', '', '', '', ''];
    let clamped = fraction.clamp(0.0, 1.0);
    let eighths = (clamped * (width * 8) as f64).round() as usize;
    let mut bar = "".repeat(eighths / 8);
    if !eighths.is_multiple_of(8) {
        bar.push(PARTIAL_BLOCKS[eighths % 8]);
    }
    let filled = bar.chars().count();
    bar.push_str(&"".repeat(width.saturating_sub(filled)));
    bar
}

/// Color for CPU/memory utilization: *low* utilization is the warning
/// (allocated resources sit idle).
fn utilization_color(fraction: f64) -> Color {
    if fraction < 0.3 {
        Color::Red
    } else if fraction < 0.6 {
        Color::Yellow
    } else {
        Color::Green
    }
}

/// Color for the used share of the time limit: *high* usage is the
/// warning (the job is close to being killed by the limit).
fn time_limit_color(fraction: f64) -> Color {
    if fraction < 0.7 {
        Color::Green
    } else if fraction <= 0.9 {
        Color::Yellow
    } else {
        Color::Red
    }
}

// ====================================================================
//  USER INPUT
// ====================================================================

impl JobOverview {
    /// Handle user input for the job overview window
    /// Returns true if the input was handled
    /// Returns false if the input was not handled
    pub fn input(&mut self, action: &mut Action, key_event: KeyEvent) -> bool {
        if self.edit_squeue {
            match key_event.code {
                KeyCode::Esc | KeyCode::Enter => {
                    self.exit_squeue_edit(action);
                    return true;
                }
                _ => {
                    self.squeue_command.input(key_event);
                    return true;
                }
            }
        }

        // the filter prompt captures every key while it is open; the
        // filter is applied live on each edit
        if self.filter_prompt {
            match key_event.code {
                // cancel: close the prompt and clear the filter
                KeyCode::Esc => {
                    self.filter_prompt = false;
                    self.clear_filter(action);
                }
                // confirm: close the prompt, keep the (already
                // applied) filter active
                KeyCode::Enter => {
                    self.filter_prompt = false;
                    if self.filter_input.is_empty() {
                        // confirming an empty prompt clears the filter
                        self.apply_filter(action);
                    }
                }
                KeyCode::Backspace => {
                    self.filter_input.pop();
                    self.apply_filter(action);
                }
                KeyCode::Char(c) => {
                    self.filter_input.push(c);
                    self.apply_filter(action);
                }
                _ => {}
            }
            return true;
        }

        match key_event.code {
            // Escaping the program
            KeyCode::Char('q') => {
                *action = Action::Quit;
            }
            // Next / Previous job
            KeyCode::Down | KeyCode::Char('j') => {
                self.next_job(action);
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.prev_job(action);
            }
            // Open job action menu
            KeyCode::Enter | KeyCode::Char('l') => {
                *action = Action::OpenMenu(OpenMenu::JobActions);
            }
            // Open the fullscreen live log view of the selected job
            KeyCode::Char('L') => {
                *action = Action::OpenMenu(OpenMenu::LogView);
            }
            // Expand/collapse the selected job-array group
            KeyCode::Char(' ') => {
                *action = Action::UpdateJobList(JobListAction::ToggleGroup);
            }
            // Change sorting category
            KeyCode::Tab => {
                *action = Action::UpdateJobList(JobListAction::NextSortCategory);
            }
            KeyCode::Char('r') => {
                *action = Action::UpdateJobList(JobListAction::ReverseSortDirection);
            }
            // Switching focus between job details and log
            KeyCode::Char('1') => {
                self.select_details();
            }
            KeyCode::Char('2') => {
                self.select_log();
            }
            KeyCode::Right | KeyCode::Left => {
                self.toggle_focus();
            }
            // Open job allocation menu
            KeyCode::Char('a') => {
                *action = Action::OpenMenu(OpenMenu::Salloc);
            }
            KeyCode::Char('o') => {
                *action = Action::OpenMenu(OpenMenu::UserOptions);
            }
            KeyCode::Char('?') => {
                *action = Action::OpenMenu(OpenMenu::Help(HelpContext::JobOverview));
            }
            // Collapsing/Extending the joblist
            KeyCode::Char('m') => {
                self.collapsed_top = !self.collapsed_top;
            }
            KeyCode::Char('n') => {
                self.collapsed_bot = !self.collapsed_bot;
            }
            // Edit the squeue command
            KeyCode::Char('/') => {
                self.collapsed_top = false;
                self.edit_squeue = true;
            }
            // Open the filter prompt (prefilled with the active filter)
            KeyCode::Char('f') => {
                self.collapsed_top = false;
                self.filter_prompt = true;
            }
            // Esc clears an active filter (it is otherwise unbound in
            // the job overview)
            KeyCode::Esc => {
                if self.filter_input.is_empty() {
                    return false;
                }
                self.clear_filter(action);
            }
            _ => {
                return false;
            }
        };
        true
    }

    fn select_details(&mut self) {
        // if the job details are already in focus, toggle collapse
        if self.focus == WindowFocus::JobDetails {
            self.collapsed_bot = !self.collapsed_bot;
        } else {
            self.focus = WindowFocus::JobDetails;
            self.collapsed_bot = false;
        }
    }

    fn select_log(&mut self) {
        // if the log is already in focus, toggle collapse
        if self.focus == WindowFocus::Log {
            self.collapsed_bot = !self.collapsed_bot;
        } else {
            self.focus = WindowFocus::Log;
            self.collapsed_bot = false;
        }
    }

    /// Toggle the focus between the job details and the log section
    /// (there are only two sections, so next and previous coincide)
    fn toggle_focus(&mut self) {
        self.focus = match self.focus {
            WindowFocus::JobDetails => WindowFocus::Log,
            WindowFocus::Log => WindowFocus::JobDetails,
        };
    }

    fn next_job(&mut self, action: &mut Action) {
        *action = Action::UpdateJobList(JobListAction::Next);
    }

    fn prev_job(&mut self, action: &mut Action) {
        *action = Action::UpdateJobList(JobListAction::Previous);
    }

    pub fn set_index(&mut self, index: i32) {
        self.state.select(Some(index as usize));
    }
}

// ====================================================================
//  MOUSE INPUT
// ====================================================================

impl JobOverview {
    pub fn mouse_input(&mut self, action: &mut Action, mouse_input: &mut MouseInput) {
        let mouse_pos = mouse_input.get_position();

        if let Some(event_kind) = mouse_input.kind() {
            match event_kind {
                MouseEventKind::Down(MouseButton::Left) => {
                    // if the squeue command is being edited, go back
                    // to normal mode
                    if self.edit_squeue {
                        self.exit_squeue_edit(action);
                        return;
                    }
                    // a click closes the filter prompt (the live
                    // applied filter stays active, like Enter)
                    if self.filter_prompt {
                        self.filter_prompt = false;
                        return;
                    }
                    // joblist title
                    if self.mouse_areas.joblist_title.contains(mouse_pos) {
                        self.collapsed_top = !self.collapsed_top;
                        mouse_input.click();
                    }
                    // squeue Command
                    if self.mouse_areas.squeue_command.contains(mouse_pos) {
                        self.edit_squeue = true;
                        mouse_input.click();
                    }
                    // joblist categories (one mouse area per column)
                    for (i, category) in self.mouse_areas.categories.iter().enumerate() {
                        if category.contains(mouse_pos) {
                            if let Some(new_cat) = self.columns.get(i).copied() {
                                *action = Action::UpdateJobList(JobListAction::SelectSortCategory(
                                    new_cat,
                                ));
                                mouse_input.click();
                            }
                        }
                    }
                    // joblist entries
                    if self.mouse_areas.joblist.contains(mouse_pos) {
                        let rel_y = mouse_pos.y - self.mouse_areas.joblist.y;
                        let new_index = rel_y as usize + self.state.offset();
                        *action = Action::UpdateJobList(JobListAction::Select(new_index));
                        if mouse_input.is_double_click() {
                            *action = Action::OpenMenu(OpenMenu::JobActions);
                        }
                        mouse_input.click();
                    }
                    // collapse symbol
                    if self.mouse_areas.bottom_symbol.contains(mouse_pos) {
                        self.collapsed_bot = !self.collapsed_bot;
                        mouse_input.click();
                    }
                    // details title
                    if self.mouse_areas.details_title.contains(mouse_pos) {
                        self.select_details();
                        mouse_input.click();
                    }
                    // log title
                    if self.mouse_areas.log_title.contains(mouse_pos) {
                        self.select_log();
                        mouse_input.click();
                    }
                }
                MouseEventKind::ScrollDown => {
                    self.next_job(action);
                }
                MouseEventKind::ScrollUp => {
                    self.prev_job(action);
                }
                _ => {}
            }
        }
    }
}

// ====================================================================
//  TESTS
// ====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn make_running_job() -> Job {
        Job::new(
            "424242",
            "train_model",
            JobStatus::Running,
            "12:34:56",
            "gpu",
            2,
            "/home/user/project",
            "/home/user/project/run.sh",
            None,
        )
    }

    /// Render the job overview into a test terminal of the given size and
    /// return the resulting buffer content as a single string.
    fn render_to_string(width: u16, height: u16, jobs: &JobList) -> String {
        render_overview(width, height, jobs, false)
    }

    /// Like [`render_to_string`], with an expanded job-details pane.
    fn render_with_details(width: u16, height: u16, jobs: &JobList) -> String {
        render_overview(width, height, jobs, true)
    }

    fn render_overview(width: u16, height: u16, jobs: &JobList, expand_details: bool) -> String {
        render_overview_with_columns(width, height, jobs, expand_details, JobColumn::defaults())
    }

    fn render_overview_with_columns(
        width: u16,
        height: u16,
        jobs: &JobList,
        expand_details: bool,
        columns: Vec<JobColumn>,
    ) -> String {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut overview = JobOverview::new(250, "squeue -u user", columns);
        overview.collapsed_bot = !expand_details;
        terminal
            .draw(|f| {
                let area = f.area();
                overview.render(f, &area, jobs);
            })
            .unwrap();
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|cell| cell.symbol())
            .collect()
    }

    #[test]
    fn test_render_job_overview_with_running_job() {
        let mut jobs = JobList::new();
        jobs.jobs.push(make_running_job());
        jobs.set_index(0).unwrap();

        let content = render_to_string(80, 20, &jobs);
        assert!(content.contains("SLURM TASK MANAGER"));
        assert!(content.contains("424242"));
        assert!(content.contains("train_model"));
        assert!(content.contains("Running"));
    }

    /// Regression test: with the default configuration the job table
    /// shows exactly the historical six column headers.
    #[test]
    fn test_render_default_columns_shows_historical_headers() {
        let mut jobs = JobList::new();
        jobs.jobs.push(make_running_job());
        jobs.set_index(0).unwrap();

        let content = render_to_string(100, 20, &jobs);
        for header in ["ID", "Name", "Status", "Time", "Partition", "Nodes"] {
            assert!(content.contains(header), "missing header {:?}", header);
        }
        // headers of non-default columns are not shown
        assert!(!content.contains("Priority"));
        assert!(!content.contains("Account"));
    }

    #[test]
    fn test_render_custom_columns_with_priority() {
        let mut job = make_running_job();
        job.priority = 4294901760;
        let mut jobs = JobList::new();
        jobs.jobs.push(job);
        jobs.set_index(0).unwrap();

        // the user replaced the Nodes column with Priority
        let columns = vec![
            JobColumn::Id,
            JobColumn::Name,
            JobColumn::Status,
            JobColumn::Time,
            JobColumn::Partition,
            JobColumn::Priority,
        ];
        let content = render_overview_with_columns(100, 20, &jobs, false, columns);

        // the Priority header and value are shown ...
        assert!(content.contains("Priority"));
        assert!(content.contains("4294901760"));
        // ... and the Nodes column is gone
        assert!(!content.contains("Nodes"));
    }

    // ----------------------------------------------------------------
    // job-array group rows
    // ----------------------------------------------------------------

    /// A job list with two tasks of the array 12345 and one single job.
    fn make_array_joblist() -> JobList {
        let mut jobs = JobList::new();
        let mut task1 = make_running_job();
        task1.id = "12345_1".to_string();
        let mut task2 = make_running_job();
        task2.id = "12345_2".to_string();
        task2.status = JobStatus::Pending;
        jobs.jobs.push(task1);
        jobs.jobs.push(task2);
        jobs.jobs.push(make_running_job());
        jobs.set_index(0).unwrap();
        jobs
    }

    #[test]
    fn test_render_collapsed_group_row_shows_base_id_and_counts() {
        let jobs = make_array_joblist();

        let content = render_to_string(100, 20, &jobs);
        // the group row shows the collapsed marker, "base[]" and the
        // aggregate status counts
        assert!(content.contains("▶ 12345[]"));
        assert!(content.contains("1R 1PD"));
        // the task ids are hidden while the group is collapsed
        assert!(!content.contains("12345_1"));
        assert!(!content.contains("12345_2"));
        // the single job is unaffected
        assert!(content.contains("424242"));
    }

    #[test]
    fn test_render_expanded_group_shows_indented_tasks() {
        let mut jobs = make_array_joblist();
        // expand the group under the cursor (row 0)
        jobs.handle_joblist_action(JobListAction::ToggleGroup, &JobColumn::defaults());

        let content = render_to_string(100, 20, &jobs);
        assert!(content.contains("▼ 12345[]"));
        // the tasks are rendered indented below the header, the last
        // one with the closing tree glyph
        assert!(content.contains("├ 12345_1"));
        assert!(content.contains("└ 12345_2"));
    }

    // ----------------------------------------------------------------
    // display filter (prompt, indicator, filtered rows)
    // ----------------------------------------------------------------

    use crossterm::event::KeyModifiers;

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    /// A job list with three distinctly named jobs.
    fn make_filter_joblist() -> JobList {
        let mut jobs = JobList::new();
        jobs.jobs.push(make_running_job());
        let mut preprocess = make_running_job();
        preprocess.id = "424243".to_string();
        preprocess.name = "preprocess".to_string();
        preprocess.status = JobStatus::Pending;
        jobs.jobs.push(preprocess);
        let mut download = make_running_job();
        download.id = "424241".to_string();
        download.name = "download_data".to_string();
        jobs.jobs.push(download);
        jobs.set_index(0).unwrap();
        jobs
    }

    #[test]
    fn test_render_active_filter_shows_indicator_and_reduced_rows() {
        let mut jobs = make_filter_joblist();
        jobs.set_filter("train", &JobColumn::defaults());

        let content = render_to_string(100, 20, &jobs);
        // the indicator shows the filter text and matching/total counts
        assert!(content.contains("filter: train (1/3)"));
        // only the matching job is listed
        assert!(content.contains("train_model"));
        assert!(!content.contains("preprocess"));
        assert!(!content.contains("download_data"));
    }

    #[test]
    fn test_render_without_filter_shows_no_indicator() {
        let jobs = make_filter_joblist();
        let content = render_to_string(100, 20, &jobs);
        assert!(!content.contains("filter:"));
    }

    #[test]
    fn test_render_filter_without_matches_shows_empty_hint() {
        let mut jobs = make_filter_joblist();
        jobs.set_filter("no such job", &JobColumn::defaults());

        let content = render_to_string(100, 20, &jobs);
        assert!(content.contains("No jobs match the filter"));
        assert!(content.contains("filter: no such job (0/3)"));
        // distinct from the empty-joblist message
        assert!(!content.contains("No jobs found"));
    }

    #[test]
    fn test_render_open_filter_prompt_shows_input_and_cursor() {
        let jobs = make_filter_joblist();
        let backend = TestBackend::new(100, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut overview = JobOverview::new(250, "squeue -u user", JobColumn::defaults());
        let mut action = Action::None;
        overview.input(&mut action, key(KeyCode::Char('f')));
        for c in "gpu".chars() {
            overview.input(&mut action, key(KeyCode::Char(c)));
        }
        terminal
            .draw(|f| {
                let area = f.area();
                overview.render(f, &area, &jobs);
            })
            .unwrap();
        let content: String = terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(|cell| cell.symbol())
            .collect();
        assert!(content.contains("filter: gpu▏"));
    }

    #[test]
    fn test_filter_key_opens_prompt_and_typing_emits_filter_actions() {
        let mut overview = JobOverview::new(250, "squeue -u user", JobColumn::defaults());
        let mut action = Action::None;

        // 'f' opens the prompt (and expands a collapsed job list)
        overview.collapsed_top = true;
        assert!(overview.input(&mut action, key(KeyCode::Char('f'))));
        assert!(overview.filter_prompt);
        assert!(!overview.collapsed_top);

        // every keystroke applies the filter live
        overview.input(&mut action, key(KeyCode::Char('g')));
        match &action {
            Action::UpdateJobList(JobListAction::SetFilter(text)) => assert_eq!(text, "g"),
            other => panic!("expected SetFilter, got {:?}", other),
        }
        overview.input(&mut action, key(KeyCode::Char('p')));
        overview.input(&mut action, key(KeyCode::Char('u')));
        match &action {
            Action::UpdateJobList(JobListAction::SetFilter(text)) => assert_eq!(text, "gpu"),
            other => panic!("expected SetFilter, got {:?}", other),
        }

        // Backspace edits the input
        overview.input(&mut action, key(KeyCode::Backspace));
        match &action {
            Action::UpdateJobList(JobListAction::SetFilter(text)) => assert_eq!(text, "gp"),
            other => panic!("expected SetFilter, got {:?}", other),
        }

        // Enter confirms: the prompt closes, the input is kept
        action = Action::None;
        overview.input(&mut action, key(KeyCode::Enter));
        assert!(!overview.filter_prompt);
        assert_eq!(overview.filter_input, "gp");
        assert!(matches!(action, Action::None));

        // reopening the prompt keeps the input prefilled
        overview.input(&mut action, key(KeyCode::Char('f')));
        assert!(overview.filter_prompt);
        assert_eq!(overview.filter_input, "gp");
    }

    #[test]
    fn test_escape_in_prompt_cancels_and_clears_the_filter() {
        let mut overview = JobOverview::new(250, "squeue -u user", JobColumn::defaults());
        let mut action = Action::None;

        overview.input(&mut action, key(KeyCode::Char('f')));
        overview.input(&mut action, key(KeyCode::Char('x')));
        overview.input(&mut action, key(KeyCode::Esc));

        assert!(!overview.filter_prompt);
        assert_eq!(overview.filter_input, "");
        match &action {
            Action::UpdateJobList(JobListAction::SetFilter(text)) => assert!(text.is_empty()),
            other => panic!("expected a clearing SetFilter, got {:?}", other),
        }
    }

    #[test]
    fn test_escape_outside_prompt_clears_an_active_filter() {
        let mut overview = JobOverview::new(250, "squeue -u user", JobColumn::defaults());
        let mut action = Action::None;

        // no filter active: Esc is not consumed
        assert!(!overview.input(&mut action, key(KeyCode::Esc)));

        // confirm a filter, then Esc clears it
        overview.input(&mut action, key(KeyCode::Char('f')));
        overview.input(&mut action, key(KeyCode::Char('a')));
        overview.input(&mut action, key(KeyCode::Enter));
        assert_eq!(overview.filter_input, "a");

        action = Action::None;
        assert!(overview.input(&mut action, key(KeyCode::Esc)));
        assert_eq!(overview.filter_input, "");
        match &action {
            Action::UpdateJobList(JobListAction::SetFilter(text)) => assert!(text.is_empty()),
            other => panic!("expected a clearing SetFilter, got {:?}", other),
        }
    }

    /// Regression test: rendering into a terminal narrower than the
    /// manually constructed squeue command rect must not panic.
    #[test]
    fn test_render_narrow_terminal_does_not_panic() {
        let mut jobs = JobList::new();
        jobs.jobs.push(make_running_job());
        jobs.set_index(0).unwrap();

        render_to_string(10, 5, &jobs);
    }

    #[test]
    fn test_render_empty_joblist() {
        let mut jobs = JobList::new();
        jobs.set_index(0).unwrap();

        let content = render_to_string(80, 20, &jobs);
        assert!(content.contains("SLURM TASK MANAGER"));
        assert!(content.contains("No jobs found"));
    }

    // ----------------------------------------------------------------
    // details pane: pending reason and efficiency stats
    // ----------------------------------------------------------------

    #[test]
    fn test_render_pending_job_shows_reason_explanation() {
        let mut job = make_running_job();
        job.status = JobStatus::Pending;
        job.reason = Some("Priority".to_string());
        let mut jobs = JobList::new();
        jobs.jobs.push(job);
        jobs.set_index(0).unwrap();

        let content = render_with_details(100, 24, &jobs);
        assert!(content.contains("Pending — Priority:"));
        assert!(content.contains("higher-priority jobs are ahead in the queue"));
    }

    #[test]
    fn test_render_pending_job_with_unknown_reason_shows_raw_code() {
        let mut job = make_running_job();
        job.status = JobStatus::Pending;
        job.reason = Some("SomeNewSlurmReason".to_string());
        let mut jobs = JobList::new();
        jobs.jobs.push(job);
        jobs.set_index(0).unwrap();

        let content = render_with_details(100, 24, &jobs);
        assert!(content.contains("Pending — SomeNewSlurmReason"));
    }

    #[test]
    fn test_render_running_job_with_stats_shows_gauges() {
        let mut job = make_running_job();
        job.stats = Some(Box::new(crate::job::JobStats {
            mem_efficiency: Some(0.42),
            elapsed_frac_of_limit: Some(0.61),
        }));
        let mut jobs = JobList::new();
        jobs.jobs.push(job);
        jobs.set_index(0).unwrap();

        let content = render_with_details(100, 24, &jobs);
        assert!(content.contains("Efficiency"));
        assert!(!content.contains("CPU"));
        assert!(content.contains("Mem"));
        assert!(content.contains("42%"));
        assert!(content.contains("Time"));
        assert!(content.contains("61%"));
        // the bars are drawn with block characters
        assert!(content.contains("████"));
    }

    #[test]
    fn test_render_running_job_without_stats_shows_no_gauges() {
        let mut jobs = JobList::new();
        jobs.jobs.push(make_running_job());
        jobs.set_index(0).unwrap();

        let content = render_with_details(100, 24, &jobs);
        // no stats fetched: the efficiency block is omitted entirely
        assert!(!content.contains("Efficiency"));
        // a running job never shows the pending line
        assert!(!content.contains("Pending —"));
    }

    // ----------------------------------------------------------------
    // bar rendering helpers
    // ----------------------------------------------------------------

    #[test]
    fn test_bar_string_widths_and_clamping() {
        // empty and full bars are exactly `width` cells
        assert_eq!(bar_string(0.0, 4), "░░░░");
        assert_eq!(bar_string(1.0, 4), "████");
        // values beyond the range are clamped
        assert_eq!(bar_string(-0.5, 4), "░░░░");
        assert_eq!(bar_string(2.5, 4), "████");
        // a half-filled bar uses the half block
        assert_eq!(bar_string(0.5, 4), "██░░");
        assert_eq!(bar_string(0.625, 4), "██▌░");
        // every bar is padded to the requested width
        for i in 0..=10 {
            let bar = bar_string(i as f64 / 10.0, 7);
            assert_eq!(bar.chars().count(), 7, "wrong width for {}", i);
        }
    }

    #[test]
    fn test_efficiency_colors() {
        // CPU/memory: low utilization is the warning
        assert_eq!(utilization_color(0.1), Color::Red);
        assert_eq!(utilization_color(0.45), Color::Yellow);
        assert_eq!(utilization_color(0.9), Color::Green);
        // time limit: high usage is the warning
        assert_eq!(time_limit_color(0.5), Color::Green);
        assert_eq!(time_limit_color(0.8), Color::Yellow);
        assert_eq!(time_limit_color(0.95), Color::Red);
    }

    // ----------------------------------------------------------------
    // snapshot tests: lock in the exact rendered frames
    // ----------------------------------------------------------------
    //
    // All inputs are fixed (job fields, refresh rate, squeue command,
    // grouping flag), so the frames are deterministic. The squeue
    // command shown in the title comes from `JobOverview::new`'s
    // argument, not from `JobList` (whose $USER-derived command is
    // never rendered here), so the snapshots do not depend on the
    // environment.

    /// Renders the overview into a 100x24 test terminal with fixed,
    /// deterministic inputs and returns the terminal for snapshotting.
    fn snapshot_terminal(
        jobs: &JobList,
        collapsed_top: bool,
        collapsed_bot: bool,
    ) -> Terminal<TestBackend> {
        let backend = TestBackend::new(100, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut overview = JobOverview::new(250, "squeue -u user", JobColumn::defaults());
        overview.collapsed_top = collapsed_top;
        overview.collapsed_bot = collapsed_bot;
        terminal
            .draw(|f| {
                let area = f.area();
                overview.render(f, &area, jobs);
            })
            .unwrap();
        terminal
    }

    /// A job list with a few fixed single jobs (no array groups).
    fn make_snapshot_joblist() -> JobList {
        let mut jobs = JobList::new();
        jobs.set_group_job_arrays(true);
        jobs.jobs.push(make_running_job());
        let mut pending = make_running_job();
        pending.id = "424243".to_string();
        pending.name = "preprocess".to_string();
        pending.status = JobStatus::Pending;
        pending.time = "0:00".to_string();
        pending.nodes = 1;
        jobs.jobs.push(pending);
        let mut done = make_running_job();
        done.id = "424241".to_string();
        done.name = "download_data".to_string();
        done.status = JobStatus::Completed;
        done.time = "1:23:45".to_string();
        done.partition = "cpu".to_string();
        done.nodes = 1;
        jobs.jobs.push(done);
        jobs.set_index(0).unwrap();
        jobs
    }

    #[test]
    fn test_snapshot_collapsed_layout() {
        let jobs = make_snapshot_joblist();
        let terminal = snapshot_terminal(&jobs, true, true);
        insta::assert_snapshot!("collapsed_layout", terminal.backend());
    }

    #[test]
    fn test_snapshot_extended_layout() {
        let jobs = make_snapshot_joblist();
        let terminal = snapshot_terminal(&jobs, false, false);
        insta::assert_snapshot!("extended_layout", terminal.backend());
    }

    #[test]
    fn test_snapshot_empty_joblist() {
        let mut jobs = JobList::new();
        jobs.set_group_job_arrays(true);
        jobs.set_index(0).unwrap();
        let terminal = snapshot_terminal(&jobs, false, true);
        insta::assert_snapshot!("empty_joblist", terminal.backend());
    }

    #[test]
    fn test_snapshot_pending_job_with_reason() {
        let mut jobs = make_snapshot_joblist();
        jobs.jobs[1].reason = Some("Priority".to_string());
        // select the pending job so its reason shows in the details pane
        jobs.set_index(1).unwrap();
        let terminal = snapshot_terminal(&jobs, false, false);
        insta::assert_snapshot!("pending_job_with_reason", terminal.backend());
    }

    #[test]
    fn test_snapshot_running_job_with_stats() {
        let mut jobs = make_snapshot_joblist();
        jobs.jobs[0].stats = Some(Box::new(crate::job::JobStats {
            mem_efficiency: Some(0.42),
            elapsed_frac_of_limit: Some(0.61),
        }));
        jobs.set_index(0).unwrap();
        let terminal = snapshot_terminal(&jobs, false, false);
        insta::assert_snapshot!("running_job_with_stats", terminal.backend());
    }

    #[test]
    fn test_snapshot_filtered_joblist() {
        let mut jobs = make_snapshot_joblist();
        // deterministic filter: only "train_model" matches, and the
        // title shows the indicator with the 1/3 counts
        jobs.set_filter("train", &JobColumn::defaults());
        let terminal = snapshot_terminal(&jobs, false, true);
        insta::assert_snapshot!("filtered_joblist", terminal.backend());
    }

    #[test]
    fn test_snapshot_array_group_collapsed() {
        let mut jobs = make_array_joblist();
        jobs.set_group_job_arrays(true);
        let terminal = snapshot_terminal(&jobs, false, true);
        insta::assert_snapshot!("array_group_collapsed", terminal.backend());
    }

    #[test]
    fn test_snapshot_array_group_expanded() {
        let mut jobs = make_array_joblist();
        jobs.set_group_job_arrays(true);
        jobs.handle_joblist_action(JobListAction::ToggleGroup, &JobColumn::defaults());
        let terminal = snapshot_terminal(&jobs, false, true);
        insta::assert_snapshot!("array_group_expanded", terminal.backend());
    }
}