gregg 1.0.6

Compact keyboard-first terminal monitor that polls greggd endpoints and renders each system in a compact five-row base block.
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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
#![allow(dead_code)]

//! Application state model for the polling engine and TUI.
//!
//! [`AppState`] owns the list of monitored systems, the selection, and the
//! viewport. It is mutated exclusively through [`Action`]s and poll
//! [`PollBatch`]es, making the reducer deterministic and testable.

use std::ops::Range;
use std::time::{Duration, Instant};

use crate::action::Action;
use crate::config::Config;
use crate::eggpool::{EggpoolFetchOutcome, EggpoolPeriod, EggpoolResult, EggpoolSummary};
use crate::endpoint::Endpoint;
use crate::normalized::NormalizedSnapshot;
use crate::poller::{PollBatch, PollOutcome};

/// A stable system identifier (UUID v4 string).
pub type SystemId = String;

/// Reachability state for a single system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reachability {
    /// No poll result received yet.
    Pending,
    /// The most recent poll succeeded.
    Online,
    /// The most recent poll failed.
    Offline,
}

/// Whether the poll scheduler is currently idle or running a generation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefreshStatus {
    /// No poll in progress.
    Idle,
    /// A poll generation is in flight.
    Polling {
        /// The generation number of the in-flight poll.
        generation: u64,
    },
}

/// The TUI presentation mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SystemViewMode {
    /// The detailed, one-block-per-system view.
    Normal,
    /// The one-row-per-system fleet view.
    Condensed,
}

/// The two fixed top-level panes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
    /// The configured system fleet.
    Systems,
    /// The optional `EggPool` summary.
    Eggpool,
}

/// Whether the `EggPool` pane is waiting for or displaying a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EggpoolStatus {
    /// No request is currently in flight.
    Idle,
    /// A request has been requested and is being dispatched.
    Refreshing,
    /// The local worker is unavailable; no request can be dispatched.
    WorkerUnavailable,
}

/// Reducer-owned transient state for the optional `EggPool` pane.
#[derive(Debug, Clone)]
pub struct EggpoolState {
    /// The configured source displayed by the pane.
    pub endpoint: crate::config::EggpoolEntry,
    /// Currently selected rolling window.
    pub period: EggpoolPeriod,
    /// Latest desired request identity.
    pub request_generation: u64,
    /// Current request status.
    pub status: EggpoolStatus,
    /// Last successful summary for the selected period.
    pub summary: Option<EggpoolSummary>,
    /// Completion time of the last successful request.
    pub last_success_at: Option<Instant>,
    /// Completion time of the last request attempt.
    pub last_attempt_at: Option<Instant>,
    /// Most recent non-cancelled failure.
    pub last_error: Option<EggpoolFetchOutcome>,
}

/// Per-system mutable state.
#[derive(Debug, Clone)]
pub struct SystemState {
    /// Stable unique identifier matching the config entry.
    pub id: SystemId,
    /// The endpoint used for polling.
    pub endpoint: Endpoint,
    /// Configured display name, if any.
    pub configured_name: Option<String>,
    /// Current reachability.
    pub reachability: Reachability,
    /// Most recent successful snapshot (normalized from v1 or v2).
    pub latest: Option<NormalizedSnapshot>,
    /// When the most recent successful poll completed.
    pub last_success_at: Option<Instant>,
    /// When the most recent poll attempt completed (success or failure).
    pub last_attempt_at: Option<Instant>,
    /// Round-trip latency of the most recent successful poll.
    pub latency: Option<Duration>,
    /// The outcome of the most recent failed poll, if any.
    pub last_error: Option<PollOutcome>,
}

/// The top-level application state.
#[derive(Debug)]
pub struct AppState {
    /// Ordered list of all monitored systems.
    pub systems: Vec<SystemState>,
    /// Currently selected system, by stable ID.
    pub selected_id: Option<SystemId>,
    /// The first visible system in the viewport, by stable ID.
    pub viewport_top_id: Option<SystemId>,
    /// Last generation whose results were applied.
    pub last_applied_generation: u64,
    /// Current refresh status.
    pub refresh_status: RefreshStatus,
    /// Terminal dimensions (width, height), if known.
    pub terminal_size: Option<(u16, u16)>,
    /// Currently active top-level pane.
    pub active_pane: Pane,
    /// Current Systems presentation mode.
    pub system_view_mode: SystemViewMode,
    /// Whether the selected online system's drives are expanded.
    pub drives_expanded: bool,
    /// Optional `EggPool` pane state.
    pub eggpool: Option<EggpoolState>,
}

impl AppState {
    /// Create initial state from a configuration.
    ///
    /// All systems start in [`Reachability::Pending`]. The first system
    /// (in display order) is selected if any systems exist.
    #[must_use]
    pub fn from_config(config: &Config) -> Self {
        let systems: Vec<SystemState> = config.systems.iter().map(system_from_entry).collect();

        let selected_id = systems.first().map(|s| s.id.clone());
        let viewport_top_id = selected_id.clone();

        let eggpool = config.eggpool.clone().map(|endpoint| EggpoolState {
            endpoint,
            period: EggpoolPeriod::Hour,
            request_generation: 0,
            status: EggpoolStatus::Idle,
            summary: None,
            last_success_at: None,
            last_attempt_at: None,
            last_error: None,
        });
        Self {
            systems,
            selected_id,
            viewport_top_id,
            last_applied_generation: 0,
            refresh_status: RefreshStatus::Idle,
            terminal_size: None,
            active_pane: if config.systems.is_empty() && eggpool.is_some() {
                Pane::Eggpool
            } else {
                Pane::Systems
            },
            system_view_mode: SystemViewMode::Normal,
            drives_expanded: false,
            eggpool,
        }
    }

    /// Reconcile the configured system endpoint list while retaining safe
    /// state for unchanged stable IDs.
    pub fn reconcile_systems(&mut self, config: &Config) {
        let old_systems = std::mem::take(&mut self.systems);
        let old_selected = self.selected_id.clone();
        let old_by_id = old_systems
            .into_iter()
            .map(|system| (system.id.clone(), system))
            .collect::<std::collections::HashMap<_, _>>();

        self.systems = config
            .systems
            .iter()
            .map(|entry| {
                let Some(mut old) = old_by_id.get(&entry.id).cloned() else {
                    return system_from_entry(entry);
                };

                let endpoint = entry.to_endpoint();
                if old.endpoint.host == endpoint.host && old.endpoint.port == endpoint.port {
                    old.endpoint = endpoint;
                    old.configured_name.clone_from(&entry.name);
                    old
                } else {
                    system_from_entry(entry)
                }
            })
            .collect();

        self.selected_id = old_selected
            .filter(|id| self.systems.iter().any(|system| &system.id == id))
            .or_else(|| self.systems.first().map(|system| system.id.clone()));
        self.viewport_top_id = self
            .viewport_top_id
            .take()
            .filter(|id| self.systems.iter().any(|system| &system.id == id))
            .or_else(|| self.selected_id.clone());
        ensure_selected_visible(self);
        if self.systems.is_empty() {
            self.selected_id = None;
            self.viewport_top_id = None;
        }
    }

    /// Apply a poll batch to the state.
    ///
    /// Rejects batches whose generation is less than or equal to the
    /// most recently applied generation. For each result: updates
    /// reachability, latest snapshot, timestamps, latency, and error.
    pub fn apply_batch(&mut self, batch: &PollBatch) {
        if batch.generation <= self.last_applied_generation {
            return;
        }

        for result in &batch.results {
            if let Some(system) = self.systems.iter_mut().find(|s| s.id == result.system_id) {
                // A stable ID may be retained while its configured target
                // changes. Results from the superseded target are stale even
                // when their scheduler generation is otherwise current.
                if system.endpoint.host != result.endpoint.host
                    || system.endpoint.port != result.endpoint.port
                {
                    continue;
                }
                match &result.outcome {
                    PollOutcome::Cancelled => {}
                    PollOutcome::Online(snapshot) => {
                        system.reachability = Reachability::Online;
                        system.latest = Some(NormalizedSnapshot::from_v1(snapshot));
                        system.last_success_at = Some(batch.completed_at);
                        system.last_attempt_at = Some(batch.completed_at);
                        system.latency = Some(result.latency);
                        system.last_error = None;
                    }
                    PollOutcome::OnlineV2(snapshot) => {
                        system.reachability = Reachability::Online;
                        system.latest = Some(NormalizedSnapshot::from_v2_payload(snapshot));
                        system.last_success_at = Some(batch.completed_at);
                        system.last_attempt_at = Some(batch.completed_at);
                        system.latency = Some(result.latency);
                        system.last_error = None;
                    }
                    _ => {
                        system.reachability = Reachability::Offline;
                        system.last_attempt_at = Some(batch.completed_at);
                        system.last_error = Some(result.outcome.clone());
                    }
                }
            }
        }

        self.last_applied_generation = batch.generation;
        ensure_selected_visible(self);
    }

    /// Apply a user action.
    #[allow(clippy::match_same_arms)]
    pub fn apply_action(&mut self, action: Action) {
        match action {
            Action::MoveDown => {
                if self.active_pane == Pane::Eggpool {
                    self.move_eggpool_period(true);
                    return;
                }
                let order = self.display_order();
                self.move_selection(&order, 1);
            }
            Action::MoveUp => {
                if self.active_pane == Pane::Eggpool {
                    self.move_eggpool_period(false);
                    return;
                }
                let order = self.display_order();
                self.move_selection(&order, -1_isize);
            }
            Action::PageDown if self.active_pane == Pane::Systems => {
                let order = self.display_order();
                let page = self.page_size();
                self.move_selection(&order, page);
            }
            Action::PageUp if self.active_pane == Pane::Systems => {
                let order = self.display_order();
                let page = self.page_size();
                self.move_selection(&order, -page);
            }
            Action::SelectFirst if self.active_pane == Pane::Systems => {
                let order = self.display_order();
                self.selected_id = order
                    .first()
                    .and_then(|&i| self.systems.get(i).map(|s| &s.id))
                    .cloned();
            }
            Action::SelectLast if self.active_pane == Pane::Systems => {
                let order = self.display_order();
                self.selected_id = order
                    .last()
                    .and_then(|&i| self.systems.get(i).map(|s| &s.id))
                    .cloned();
            }
            Action::PreviousPane => self.cycle_pane(false),
            Action::NextPane => self.cycle_pane(true),
            Action::ToggleSystemView if self.active_pane == Pane::Systems => {
                self.system_view_mode = match self.system_view_mode {
                    SystemViewMode::Normal => SystemViewMode::Condensed,
                    SystemViewMode::Condensed => SystemViewMode::Normal,
                };
            }
            Action::PageDown
            | Action::PageUp
            | Action::SelectFirst
            | Action::SelectLast
            | Action::RefreshNow
            | Action::Quit => {}
            Action::ToggleSystemView | Action::ToggleDrives
                if self.active_pane == Pane::Eggpool => {}
            Action::ToggleSystemView => {}
            Action::ToggleDrives => {
                self.drives_expanded = !self.drives_expanded;
            }
            Action::Resize { width, height } => {
                self.terminal_size = Some((width, height));
                ensure_selected_visible(self);
            }
        }
        ensure_selected_visible(self);
    }

    /// Return the display order: online systems first (in configured
    /// order), then offline/pending systems (in configured order).
    #[must_use]
    pub fn display_order(&self) -> Vec<usize> {
        let mut online = Vec::new();
        let mut offline = Vec::new();

        for (i, system) in self.systems.iter().enumerate() {
            match system.reachability {
                Reachability::Online => online.push(i),
                Reachability::Offline | Reachability::Pending => offline.push(i),
            }
        }

        online.extend(offline);
        online
    }

    /// Apply one `EggPool` result if it belongs to the current request and period.
    pub fn apply_eggpool_result(&mut self, result: &EggpoolResult) {
        let Some(eggpool) = self.eggpool.as_mut() else {
            return;
        };
        if result.generation != eggpool.request_generation || result.period != eggpool.period {
            return;
        }
        if !matches!(result.outcome, EggpoolFetchOutcome::Cancelled) {
            eggpool.request_generation = result.generation;
            eggpool.status = EggpoolStatus::Idle;
            eggpool.last_attempt_at = Some(result.completed_at);
            match &result.outcome {
                EggpoolFetchOutcome::Online(summary) => {
                    eggpool.summary = Some(summary.clone());
                    eggpool.last_success_at = Some(result.completed_at);
                    eggpool.last_error = None;
                }
                error => eggpool.last_error = Some(error.clone()),
            }
        }
    }

    /// Mark an `EggPool` activation or manual refresh as a new request.
    pub fn begin_eggpool_request(&mut self) -> Option<(EggpoolPeriod, u64)> {
        let eggpool = self.eggpool.as_mut()?;
        eggpool.request_generation = eggpool.request_generation.wrapping_add(1);
        eggpool.status = EggpoolStatus::Refreshing;
        Some((eggpool.period, eggpool.request_generation))
    }

    /// Mark the local worker as unavailable without exposing a channel error.
    pub fn mark_eggpool_worker_unavailable(&mut self) {
        if let Some(eggpool) = self.eggpool.as_mut() {
            eggpool.status = EggpoolStatus::WorkerUnavailable;
        }
    }

    /// Return the current `EggPool` request identity without changing state.
    #[must_use]
    pub fn eggpool_request(&self) -> Option<(EggpoolPeriod, u64)> {
        self.eggpool
            .as_ref()
            .map(|eggpool| (eggpool.period, eggpool.request_generation))
    }

    fn move_eggpool_period(&mut self, longer: bool) {
        let Some(eggpool) = self.eggpool.as_mut() else {
            return;
        };
        let next = if longer {
            eggpool.period.longer()
        } else {
            eggpool.period.shorter()
        };
        if next == eggpool.period {
            return;
        }
        eggpool.period = next;
        eggpool.request_generation = eggpool.request_generation.wrapping_add(1);
        eggpool.status = EggpoolStatus::Refreshing;
        eggpool.summary = None;
        eggpool.last_error = None;
    }

    fn cycle_pane(&mut self, next: bool) {
        match (
            self.active_pane,
            self.systems.is_empty(),
            self.eggpool.is_some(),
            next,
        ) {
            (Pane::Systems, false, true, _) => self.active_pane = Pane::Eggpool,
            (Pane::Eggpool, _, true, _) if !self.systems.is_empty() => {
                self.active_pane = Pane::Systems;
            }
            _ => {}
        }
    }

    /// Move selection by a relative offset in display order.
    fn move_selection(&mut self, order: &[usize], offset: isize) {
        if order.is_empty() {
            self.selected_id = None;
            return;
        }

        let current_pos = self
            .selected_id
            .as_ref()
            .and_then(|sel| order.iter().position(|&i| &self.systems[i].id == sel))
            .unwrap_or(0);

        let len = order.len();
        let new_pos = if offset >= 0 {
            current_pos.saturating_add(usize::try_from(offset).unwrap_or(len))
        } else {
            current_pos.saturating_sub(usize::try_from(-offset).unwrap_or(current_pos))
        }
        .min(len - 1);

        self.selected_id = order
            .get(new_pos)
            .and_then(|&i| self.systems.get(i))
            .map(|s| s.id.clone());
    }

    /// Compute the page size (number of systems to skip) based on
    /// terminal height and the current viewport.
    fn page_size(&self) -> isize {
        let height = self
            .terminal_size
            .map_or(24, |(_, h)| h)
            .saturating_sub(view_header_height(self.system_view_mode));

        let order = self.display_order();
        let top_pos = self
            .viewport_top_id
            .as_ref()
            .and_then(|top| order.iter().position(|&i| &self.systems[i].id == top))
            .unwrap_or(0);

        let mut rows = 0_u16;
        let mut count = 0_isize;
        for &idx in order.iter().skip(top_pos) {
            let h = entry_height(self, idx);
            if rows + h > height && count > 0 {
                break;
            }
            rows += h;
            count += 1;
        }

        count.max(1)
    }
}

fn system_from_entry(entry: &crate::config::SystemEntry) -> SystemState {
    SystemState {
        id: entry.id.clone(),
        endpoint: entry.to_endpoint(),
        configured_name: entry.name.clone(),
        reachability: Reachability::Pending,
        latest: None,
        last_success_at: None,
        last_attempt_at: None,
        latency: None,
        last_error: None,
    }
}

/// Return the full row height for a system entry in the current view.
#[must_use]
pub fn entry_height(state: &AppState, system_index: usize) -> u16 {
    let Some(system) = state.systems.get(system_index) else {
        return 0;
    };
    match (state.system_view_mode, system.reachability) {
        (SystemViewMode::Condensed, _) => {
            if state.drives_expanded
                && state.selected_id.as_deref() == Some(system.id.as_str())
                && system.reachability == Reachability::Online
            {
                1_u16.saturating_add(valid_drive_count(system))
            } else {
                1
            }
        }
        (SystemViewMode::Normal, Reachability::Pending | Reachability::Offline) => 1,
        (SystemViewMode::Normal, Reachability::Online) => {
            let details = if state.drives_expanded
                && state.selected_id.as_deref() == Some(system.id.as_str())
            {
                system
                    .latest
                    .as_ref()
                    .and_then(|snapshot| snapshot.drives.as_ref())
                    .map_or(0, |drives| valid_drive_count_from_slice(drives))
            } else {
                0
            };
            5_u16.saturating_add(details)
        }
    }
}

/// Compute which systems in display order are visible given a top
/// index, the system states, and available height.
///
/// Online entries take five base rows, with optional selected-system drive
/// rows; offline and pending entries take one row. A first entry is retained
/// even when its full dynamic height is taller than the viewport so the caller
/// can clip only detail rows while preserving its complete base block.
#[must_use]
pub fn visible_range(
    display_order: &[usize],
    state: &AppState,
    top_index: usize,
    height: u16,
) -> Range<usize> {
    if height == 0 {
        return 0..0;
    }

    let mut rows_used = 0_u16;
    let mut count = 0_usize;

    for &idx in display_order.iter().skip(top_index) {
        if idx >= state.systems.len() {
            break;
        }
        let h = entry_height(state, idx);

        if count == 0 && height < minimum_render_height(state, idx) {
            return top_index..top_index;
        }

        if rows_used + h > height && count > 0 {
            break;
        }
        rows_used += h;
        count += 1;
    }

    top_index..(top_index + count)
}

fn minimum_render_height(state: &AppState, system_index: usize) -> u16 {
    match state
        .systems
        .get(system_index)
        .map(|system| (state.system_view_mode, system.reachability))
    {
        Some((SystemViewMode::Normal, Reachability::Online)) => 5,
        Some(_) => 1,
        None => 0,
    }
}

/// Adjust `viewport_top_id` so the selected system is visible.
pub fn ensure_selected_visible(state: &mut AppState) {
    let order = state.display_order();
    if order.is_empty() {
        return;
    }

    let (_, height) = state.terminal_size.unwrap_or((80, 24));

    let selected_pos = state
        .selected_id
        .as_ref()
        .and_then(|sel| order.iter().position(|&i| &state.systems[i].id == sel));

    let top_pos = state
        .viewport_top_id
        .as_ref()
        .and_then(|top| order.iter().position(|&i| &state.systems[i].id == top))
        .unwrap_or(0);

    let Some(selected_pos) = selected_pos else {
        return;
    };

    // The renderer uses the complete frame as its viewport.
    let usable_height = height.saturating_sub(view_header_height(state.system_view_mode));

    // Find which systems fit from top_pos downward.
    let visible = visible_range(&order, state, top_pos, usable_height);

    if visible.contains(&selected_pos) {
        // Already visible, nothing to do.
        return;
    }

    // If selected is above viewport, scroll up.
    if selected_pos < top_pos {
        state.viewport_top_id = Some(state.systems[order[selected_pos]].id.clone());
        return;
    }

    // If selected is below viewport, move the top only as far as necessary.
    if selected_pos >= top_pos {
        let mut candidate = selected_pos;
        while candidate > top_pos {
            let previous = candidate - 1;
            let range = visible_range(&order, state, previous, usable_height);
            if range.contains(&selected_pos) {
                candidate = previous;
            } else {
                break;
            }
        }
        state.viewport_top_id = Some(state.systems[order[candidate]].id.clone());
    }
}

/// Rows reserved above the entries by a view.
#[must_use]
pub const fn view_header_height(system_view_mode: SystemViewMode) -> u16 {
    match system_view_mode {
        SystemViewMode::Normal => 0,
        SystemViewMode::Condensed => 2,
    }
}

fn valid_drive_count(system: &SystemState) -> u16 {
    system
        .latest
        .as_ref()
        .and_then(|snapshot| snapshot.drives.as_deref())
        .map_or(0, valid_drive_count_from_slice)
}

fn valid_drive_count_from_slice(drives: &[crate::normalized::NormalizedDrive]) -> u16 {
    drives
        .iter()
        .filter(|drive| drive.total_bytes > 0 && drive.used_bytes <= drive.total_bytes)
        .count()
        .try_into()
        .unwrap_or(u16::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{EggpoolEntry, EggpoolScheme, SystemEntry};
    use gregg_protocol::test_support::LinuxSnapshotBuilder;
    use gregg_protocol::StatusSnapshot;

    fn test_config_with_ids(ids: &[&str]) -> Config {
        let mut config = Config::default();
        for (i, id) in ids.iter().enumerate() {
            config.systems.push(SystemEntry {
                id: (*id).to_string(),
                host: format!("host{i}.local"),
                port: 11310 + u16::try_from(i).unwrap(),
                name: Some(format!("System {i}")),
            });
        }
        config
    }

    fn eggpool_config(with_system: bool) -> Config {
        let mut config = if with_system {
            test_config_with_ids(&["system"])
        } else {
            Config::default()
        };
        config.eggpool = Some(EggpoolEntry {
            id: "eggpool-id".into(),
            host: "pool.local".into(),
            port: 11300,
            scheme: EggpoolScheme::Http,
            name: Some("Main EggPool".into()),
            api_key_env: None,
        });
        config
    }

    fn make_snapshot() -> StatusSnapshot {
        LinuxSnapshotBuilder::default().build()
    }

    #[test]
    fn from_config_creates_correct_initial_state() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let state = AppState::from_config(&config);

        assert_eq!(state.systems.len(), 3);
        assert_eq!(state.selected_id.as_deref(), Some("a"));
        assert_eq!(state.viewport_top_id.as_deref(), Some("a"));
        assert_eq!(state.last_applied_generation, 0);
        assert_eq!(state.refresh_status, RefreshStatus::Idle);
        assert!(state.terminal_size.is_none());

        for system in &state.systems {
            assert_eq!(system.reachability, Reachability::Pending);
            assert!(system.latest.is_none());
        }
    }

    #[test]
    fn from_config_preserves_configured_endpoint_host_exactly() {
        let mut config = Config::default();
        config.systems.push(SystemEntry {
            id: "exact".into(),
            host: "192.168.183.143".into(),
            port: 11310,
            name: None,
        });

        let state = AppState::from_config(&config);
        assert_eq!(state.systems[0].endpoint.host, "192.168.183.143");
    }

    #[test]
    fn reconcile_systems_replaces_targets_preserves_unchanged_state_and_repairs_ids() {
        let old_config = Config {
            systems: vec![
                SystemEntry {
                    id: "changed".into(),
                    host: "192.168.182.143".into(),
                    port: 11310,
                    name: Some("Old".into()),
                },
                SystemEntry {
                    id: "same".into(),
                    host: "same.local".into(),
                    port: 11311,
                    name: Some("Same".into()),
                },
                SystemEntry {
                    id: "removed".into(),
                    host: "removed.local".into(),
                    port: 11312,
                    name: None,
                },
            ],
            ..Config::default()
        };
        let mut state = AppState::from_config(&old_config);
        state.selected_id = Some("removed".into());

        let first_batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: state
                .systems
                .iter()
                .take(2)
                .map(|system| crate::poller::PollResult {
                    system_id: system.id.clone(),
                    endpoint: system.endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(25),
                })
                .collect(),
        };
        state.apply_batch(&first_batch);
        state.systems[0].last_error = Some(PollOutcome::Timeout);

        let retained_snapshot = state.systems[1].latest.clone();
        let retained_success = state.systems[1].last_success_at;
        let new_config = Config {
            systems: vec![
                SystemEntry {
                    id: "changed".into(),
                    host: "192.168.183.143".into(),
                    port: 11310,
                    name: Some("New".into()),
                },
                SystemEntry {
                    id: "same".into(),
                    host: "same.local".into(),
                    port: 11311,
                    name: Some("Renamed".into()),
                },
                SystemEntry {
                    id: "added".into(),
                    host: "added.local".into(),
                    port: 11313,
                    name: None,
                },
            ],
            ..old_config.clone()
        };

        state.reconcile_systems(&new_config);

        assert_eq!(state.systems.len(), 3);
        assert_eq!(state.systems[0].endpoint.host, "192.168.183.143");
        assert_eq!(state.systems[0].configured_name.as_deref(), Some("New"));
        assert_eq!(state.systems[0].reachability, Reachability::Pending);
        assert!(state.systems[0].latest.is_none());
        assert!(state.systems[0].last_success_at.is_none());
        assert!(state.systems[0].last_attempt_at.is_none());
        assert!(state.systems[0].latency.is_none());
        assert!(state.systems[0].last_error.is_none());

        assert_eq!(state.systems[1].configured_name.as_deref(), Some("Renamed"));
        assert_eq!(state.systems[1].reachability, Reachability::Online);
        assert_eq!(state.systems[1].latest, retained_snapshot);
        assert_eq!(state.systems[1].last_success_at, retained_success);
        assert_eq!(state.selected_id.as_deref(), Some("changed"));
        assert_eq!(state.viewport_top_id.as_deref(), Some("changed"));
        assert_eq!(state.systems[2].id, "added");
        assert_eq!(state.systems[2].reachability, Reachability::Pending);
    }

    #[test]
    fn apply_batch_rejects_result_from_superseded_endpoint() {
        let mut config = test_config_with_ids(&["a"]);
        config.systems[0].host = "new.local".into();
        let mut state = AppState::from_config(&config);
        let old_endpoint = Endpoint::new("old.local".into(), 11310, None);
        state.systems[0].endpoint = old_endpoint.clone();
        state.reconcile_systems(&config);

        state.apply_batch(&PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: old_endpoint,
                outcome: PollOutcome::Online(Box::new(make_snapshot())),
                latency: Duration::from_millis(1),
            }],
        });

        assert_eq!(state.systems[0].endpoint.host, "new.local");
        assert_eq!(state.systems[0].reachability, Reachability::Pending);
        assert!(state.systems[0].latest.is_none());
    }

    #[test]
    fn from_config_empty_systems() {
        let config = Config::default();
        let state = AppState::from_config(&config);

        assert!(state.systems.is_empty());
        assert!(state.selected_id.is_none());
        assert!(state.viewport_top_id.is_none());
    }

    #[test]
    fn pane_initialization_and_cycling_follow_configured_sources() {
        let systems = AppState::from_config(&test_config_with_ids(&["a"]));
        assert_eq!(systems.active_pane, Pane::Systems);
        let eggpool = AppState::from_config(&eggpool_config(false));
        assert_eq!(eggpool.active_pane, Pane::Eggpool);
        assert!(eggpool.eggpool.is_some());

        let mut both = AppState::from_config(&eggpool_config(true));
        both.apply_action(Action::NextPane);
        assert_eq!(both.active_pane, Pane::Eggpool);
        both.apply_action(Action::PreviousPane);
        assert_eq!(both.active_pane, Pane::Systems);
    }

    #[test]
    fn eggpool_period_movement_is_bounded_and_invalidates_old_summary() {
        let mut state = AppState::from_config(&eggpool_config(false));
        assert_eq!(state.eggpool.as_ref().unwrap().period, EggpoolPeriod::Hour);
        state.apply_action(Action::MoveUp);
        assert_eq!(state.eggpool.as_ref().unwrap().period, EggpoolPeriod::Hour);
        state.apply_action(Action::MoveDown);
        state.apply_action(Action::MoveDown);
        state.apply_action(Action::MoveDown);
        state.apply_action(Action::MoveDown);
        let eggpool = state.eggpool.as_ref().unwrap();
        assert_eq!(eggpool.period, EggpoolPeriod::Month);
        assert_eq!(eggpool.request_generation, 3);
        assert!(eggpool.summary.is_none());
    }

    #[test]
    fn eggpool_results_reject_stale_or_mismatched_requests_and_retain_same_period_failures() {
        let mut state = AppState::from_config(&eggpool_config(false));
        state.apply_action(Action::MoveDown);
        let now = Instant::now();
        let summary = EggpoolSummary {
            accounted_tokens: 42,
            cache_read_ratio: Some(0.5),
            output_tokens_per_second: 2.0,
            avg_ttft_ms: Some(12.0),
            period: EggpoolPeriod::Day,
        };
        let result = |generation, period, outcome| EggpoolResult {
            generation,
            period,
            started_at: now,
            completed_at: now,
            outcome,
        };
        state.apply_eggpool_result(&result(
            0,
            EggpoolPeriod::Day,
            EggpoolFetchOutcome::Online(summary.clone()),
        ));
        assert!(state.eggpool.as_ref().unwrap().summary.is_none());
        state.apply_eggpool_result(&result(
            1,
            EggpoolPeriod::Hour,
            EggpoolFetchOutcome::Online(summary.clone()),
        ));
        assert!(state.eggpool.as_ref().unwrap().summary.is_none());
        state.apply_eggpool_result(&result(
            1,
            EggpoolPeriod::Day,
            EggpoolFetchOutcome::Online(summary),
        ));
        assert!(state.eggpool.as_ref().unwrap().summary.is_some());
        state.apply_eggpool_result(&result(1, EggpoolPeriod::Day, EggpoolFetchOutcome::Timeout));
        assert!(state.eggpool.as_ref().unwrap().summary.is_some());
        assert!(matches!(
            state.eggpool.as_ref().unwrap().last_error,
            Some(EggpoolFetchOutcome::Timeout)
        ));
        state.apply_eggpool_result(&result(
            1,
            EggpoolPeriod::Day,
            EggpoolFetchOutcome::Online(EggpoolSummary {
                accounted_tokens: 43,
                cache_read_ratio: None,
                output_tokens_per_second: 3.0,
                avg_ttft_ms: None,
                period: EggpoolPeriod::Day,
            }),
        ));
        assert_eq!(
            state
                .eggpool
                .as_ref()
                .unwrap()
                .summary
                .as_ref()
                .unwrap()
                .accounted_tokens,
            43
        );
    }

    #[test]
    fn apply_batch_online_result() {
        let config = test_config_with_ids(&["a", "b"]);
        let mut state = AppState::from_config(&config);
        let snap = make_snapshot();

        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::Online(Box::new(snap.clone())),
                latency: Duration::from_millis(50),
            }],
        };

        state.apply_batch(&batch);

        assert_eq!(state.systems[0].reachability, Reachability::Online);
        assert!(state.systems[0].latest.is_some());
        assert!(state.systems[0].last_success_at.is_some());
        assert!(state.systems[0].latency.is_some());
        assert!(state.systems[0].last_error.is_none());
        assert_eq!(state.last_applied_generation, 1);
        // System b is still pending.
        assert_eq!(state.systems[1].reachability, Reachability::Pending);
    }

    #[test]
    fn apply_batch_offline_result() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);

        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::ConnectionRefused,
                latency: Duration::from_millis(10),
            }],
        };

        state.apply_batch(&batch);

        assert_eq!(state.systems[0].reachability, Reachability::Offline);
        assert!(state.systems[0].latest.is_none());
        assert!(state.systems[0].last_attempt_at.is_some());
        assert!(state.systems[0].last_error.is_some());
    }

    #[test]
    fn apply_batch_rejects_old_generation() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);

        let batch = PollBatch {
            generation: 2,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::Online(Box::new(make_snapshot())),
                latency: Duration::from_millis(50),
            }],
        };

        state.apply_batch(&batch);
        assert_eq!(state.last_applied_generation, 2);

        // Older batch should be rejected.
        let old_batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::ConnectionRefused,
                latency: Duration::from_millis(10),
            }],
        };

        state.apply_batch(&old_batch);
        // Generation should not have changed back.
        assert_eq!(state.last_applied_generation, 2);
        // Reachability should still be Online.
        assert_eq!(state.systems[0].reachability, Reachability::Online);
    }

    #[test]
    fn apply_batch_cancelled_no_state_change() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);

        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::Cancelled,
                latency: Duration::from_millis(50),
            }],
        };

        state.apply_batch(&batch);

        // Should still be Pending (not changed by Cancelled).
        assert_eq!(state.systems[0].reachability, Reachability::Pending);
    }

    #[test]
    fn display_order_online_first() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);

        // Make b online.
        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "b".into(),
                endpoint: state.systems[1].endpoint.clone(),
                outcome: PollOutcome::Online(Box::new(make_snapshot())),
                latency: Duration::from_millis(50),
            }],
        };
        state.apply_batch(&batch);

        let order = state.display_order();
        // b is online, should be first. a and c are pending, should follow.
        assert_eq!(order.len(), 3);
        assert_eq!(state.systems[order[0]].id, "b");
        // a and c should maintain configured order.
        let remaining: Vec<&str> = order[1..]
            .iter()
            .map(|&i| state.systems[i].id.as_str())
            .collect();
        assert_eq!(remaining, vec!["a", "c"]);
    }

    #[test]
    fn display_order_preserves_configured_order() {
        let config = test_config_with_ids(&["a", "b", "c", "d"]);
        let mut state = AppState::from_config(&config);

        // Make c and a online.
        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![
                crate::poller::PollResult {
                    system_id: "c".into(),
                    endpoint: state.systems[2].endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(50),
                },
                crate::poller::PollResult {
                    system_id: "a".into(),
                    endpoint: state.systems[0].endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(50),
                },
            ],
        };
        state.apply_batch(&batch);

        let order = state.display_order();
        // Online: a (index 0), c (index 2) in configured order.
        assert_eq!(state.systems[order[0]].id, "a");
        assert_eq!(state.systems[order[1]].id, "c");
        // Offline: b, d in configured order.
        assert_eq!(state.systems[order[2]].id, "b");
        assert_eq!(state.systems[order[3]].id, "d");
    }

    #[test]
    fn select_next_moves_forward() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);

        assert_eq!(state.selected_id.as_deref(), Some("a"));

        state.apply_action(Action::MoveDown);
        assert_eq!(state.selected_id.as_deref(), Some("b"));

        state.apply_action(Action::MoveDown);
        assert_eq!(state.selected_id.as_deref(), Some("c"));

        // Should clamp at the end.
        state.apply_action(Action::MoveDown);
        assert_eq!(state.selected_id.as_deref(), Some("c"));
    }

    #[test]
    fn select_previous_moves_backward() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);

        state.apply_action(Action::MoveDown);
        state.apply_action(Action::MoveDown);
        assert_eq!(state.selected_id.as_deref(), Some("c"));

        state.apply_action(Action::MoveUp);
        assert_eq!(state.selected_id.as_deref(), Some("b"));

        state.apply_action(Action::MoveUp);
        assert_eq!(state.selected_id.as_deref(), Some("a"));

        // Should clamp at the beginning.
        state.apply_action(Action::MoveUp);
        assert_eq!(state.selected_id.as_deref(), Some("a"));
    }

    #[test]
    fn select_first_and_last() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);

        state.apply_action(Action::SelectLast);
        assert_eq!(state.selected_id.as_deref(), Some("c"));

        state.apply_action(Action::SelectFirst);
        assert_eq!(state.selected_id.as_deref(), Some("a"));
    }

    #[test]
    fn page_down_and_up() {
        let config = test_config_with_ids(&["a", "b", "c", "d", "e", "f", "g", "h"]);
        let mut state = AppState::from_config(&config);
        state.terminal_size = Some((80, 20));

        state.apply_action(Action::PageDown);
        // Page size should be > 1, so selection should move.
        let after_page_down = state.selected_id.clone();
        assert_ne!(after_page_down.as_deref(), Some("a"));

        state.apply_action(Action::PageUp);
        // Should move back toward the beginning.
        let after_page_up = state.selected_id.clone();
        assert_eq!(after_page_up.as_deref(), Some("a"));
    }

    #[test]
    fn selection_preserved_across_reorder() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);

        // Select b.
        state.apply_action(Action::MoveDown);
        assert_eq!(state.selected_id.as_deref(), Some("b"));

        // Make a online (changes display order but b is still selected).
        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![crate::poller::PollResult {
                system_id: "a".into(),
                endpoint: state.systems[0].endpoint.clone(),
                outcome: PollOutcome::Online(Box::new(make_snapshot())),
                latency: Duration::from_millis(50),
            }],
        };
        state.apply_batch(&batch);

        assert_eq!(state.selected_id.as_deref(), Some("b"));
    }

    #[test]
    fn entry_height_online_is_five() {
        let mut state = AppState {
            systems: vec![SystemState {
                id: "test".into(),
                endpoint: Endpoint::new("host".into(), 11310, None),
                configured_name: None,
                reachability: Reachability::Online,
                latest: None,
                last_success_at: None,
                last_attempt_at: None,
                latency: None,
                last_error: None,
            }],
            selected_id: Some("test".into()),
            viewport_top_id: Some("test".into()),
            last_applied_generation: 0,
            refresh_status: RefreshStatus::Idle,
            terminal_size: None,
            active_pane: Pane::Systems,
            system_view_mode: SystemViewMode::Normal,
            drives_expanded: false,
            eggpool: None,
        };
        assert_eq!(entry_height(&state, 0), 5);

        state.systems[0].reachability = Reachability::Pending;
        assert_eq!(entry_height(&state, 0), 1);

        state.systems[0].reachability = Reachability::Offline;
        assert_eq!(entry_height(&state, 0), 1);
    }

    #[test]
    fn visible_range_handles_mixed_heights() {
        let config = test_config_with_ids(&["a", "b", "c", "d", "e"]);
        let state = AppState::from_config(&config);
        let order = state.display_order();
        let range = visible_range(&order, &state, 0, 20);
        // Should include some entries.
        assert!(!range.is_empty());
    }

    #[test]
    fn visible_range_small_terminal() {
        let config = test_config_with_ids(&["a", "b", "c"]);
        let mut state = AppState::from_config(&config);
        state.systems[0].reachability = Reachability::Online;
        let order = state.display_order();
        let range = visible_range(&order, &state, 0, 3);
        // Terminal too small for even one online entry.
        assert!(range.is_empty());
    }

    #[test]
    fn visible_range_online_boundary_is_five_rows() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);
        state.systems[0].reachability = Reachability::Online;
        let order = state.display_order();

        assert!(visible_range(&order, &state, 0, 4).is_empty());
        assert_eq!(visible_range(&order, &state, 0, 5), 0..1);
    }

    #[test]
    fn visible_range_first_offline_entry_does_not_reserve_online_height() {
        let config = test_config_with_ids(&["offline", "online"]);
        let mut state = AppState::from_config(&config);
        state.systems[1].reachability = Reachability::Online;
        let order = vec![0, 1];

        assert_eq!(visible_range(&order, &state, 0, 1), 0..1);
    }

    #[test]
    fn visible_range_expanded_online_entry_clips_only_drive_rows() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);
        state.systems[0].reachability = Reachability::Online;
        state.systems[0].latest = Some(NormalizedSnapshot::from_v1(&make_snapshot()));
        state.systems[0].latest.as_mut().unwrap().drives = Some(
            (0..3)
                .map(|index| crate::normalized::NormalizedDrive {
                    name: format!("drive{index}"),
                    used_bytes: 1,
                    total_bytes: 2,
                    available_bytes: None,
                })
                .collect(),
        );
        state.selected_id = Some("a".into());
        state.drives_expanded = true;
        let order = state.display_order();

        assert_eq!(visible_range(&order, &state, 0, 5), 0..1);
        assert_eq!(visible_range(&order, &state, 0, 6), 0..1);
        assert_eq!(entry_height(&state, 0), 8);

        let viewport =
            crate::ui::layout::compute_viewport(&state, ratatui::layout::Rect::new(0, 0, 80, 5));
        assert_eq!(viewport[0].drive_rows_visible, 0);
        let viewport =
            crate::ui::layout::compute_viewport(&state, ratatui::layout::Rect::new(0, 0, 80, 6));
        assert_eq!(viewport[0].drive_rows_visible, 1);
    }

    #[test]
    fn ensure_selected_visible_adjusts_viewport() {
        let config = test_config_with_ids(&["a", "b", "c", "d", "e"]);
        let mut state = AppState::from_config(&config);
        state.terminal_size = Some((80, 6)); // Very small: 4 usable rows

        // Select the last system.
        state.apply_action(Action::SelectLast);
        assert_eq!(state.selected_id.as_deref(), Some("e"));

        // Ensure selected is visible.
        ensure_selected_visible(&mut state);

        // The viewport should have been adjusted so e is visible.
        let order = state.display_order();
        let top_pos = state
            .viewport_top_id
            .as_ref()
            .and_then(|top| order.iter().position(|&i| &state.systems[i].id == top));
        let selected_pos = order
            .iter()
            .position(|&i| &state.systems[i].id == state.selected_id.as_ref().unwrap());
        assert!(top_pos.is_some());
        assert!(selected_pos.is_some());
        assert!(selected_pos.unwrap() >= top_pos.unwrap());
    }

    #[test]
    fn selection_stays_visible_across_dynamic_online_entries() {
        let config = test_config_with_ids(&["a", "b", "c", "d"]);
        let mut state = AppState::from_config(&config);
        state.terminal_size = Some((80, 10));
        for system in &mut state.systems {
            system.reachability = Reachability::Online;
            system.latest = Some(NormalizedSnapshot::from_v1(&make_snapshot()));
        }

        state.apply_action(Action::SelectLast);
        let order = state.display_order();
        let top = order
            .iter()
            .position(|&index| state.systems[index].id == state.viewport_top_id.clone().unwrap())
            .unwrap();
        let selected = order
            .iter()
            .position(|&index| state.systems[index].id == state.selected_id.clone().unwrap())
            .unwrap();
        assert_eq!(top, 2);
        assert!(visible_range(&order, &state, top, 10).contains(&selected));

        state.apply_action(Action::MoveUp);
        assert_eq!(state.viewport_top_id.as_deref(), Some("c"));
    }

    #[test]
    fn expansion_changes_only_selected_entry_height() {
        let config = test_config_with_ids(&["a", "b"]);
        let mut state = AppState::from_config(&config);
        for system in &mut state.systems {
            system.reachability = Reachability::Online;
            system.latest = Some(NormalizedSnapshot::from_v1(&make_snapshot()));
        }
        state.systems[0].latest.as_mut().unwrap().drives =
            Some(vec![crate::normalized::NormalizedDrive {
                name: "/".into(),
                used_bytes: 1,
                total_bytes: 2,
                available_bytes: None,
            }]);
        assert_eq!(entry_height(&state, 0), 5);
        assert_eq!(entry_height(&state, 1), 5);
        state.apply_action(Action::ToggleDrives);
        assert_eq!(entry_height(&state, 0), 6);
        assert_eq!(entry_height(&state, 1), 5);
    }

    #[test]
    fn resize_updates_terminal_size() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);

        state.apply_action(Action::Resize {
            width: 120,
            height: 40,
        });

        assert_eq!(state.terminal_size, Some((120, 40)));
    }

    #[test]
    fn empty_config_no_selection() {
        let config = Config::default();
        let mut state = AppState::from_config(&config);

        state.apply_action(Action::MoveDown);
        assert!(state.selected_id.is_none());

        state.apply_action(Action::MoveUp);
        assert!(state.selected_id.is_none());

        state.apply_action(Action::SelectFirst);
        assert!(state.selected_id.is_none());

        state.apply_action(Action::SelectLast);
        assert!(state.selected_id.is_none());
    }

    #[test]
    fn multiple_systems_online_offline_mixed_display_order() {
        let config = test_config_with_ids(&["a", "b", "c", "d", "e"]);
        let mut state = AppState::from_config(&config);

        // Make a, c, e online.
        let batch = PollBatch {
            generation: 1,
            started_at: Instant::now(),
            completed_at: Instant::now(),
            results: vec![
                crate::poller::PollResult {
                    system_id: "a".into(),
                    endpoint: state.systems[0].endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(50),
                },
                crate::poller::PollResult {
                    system_id: "c".into(),
                    endpoint: state.systems[2].endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(50),
                },
                crate::poller::PollResult {
                    system_id: "e".into(),
                    endpoint: state.systems[4].endpoint.clone(),
                    outcome: PollOutcome::Online(Box::new(make_snapshot())),
                    latency: Duration::from_millis(50),
                },
            ],
        };
        state.apply_batch(&batch);

        let order = state.display_order();
        assert_eq!(order.len(), 5);
        // Online first: a, c, e (in configured order).
        assert_eq!(state.systems[order[0]].id, "a");
        assert_eq!(state.systems[order[1]].id, "c");
        assert_eq!(state.systems[order[2]].id, "e");
        // Offline: b, d.
        assert_eq!(state.systems[order[3]].id, "b");
        assert_eq!(state.systems[order[4]].id, "d");
    }

    #[test]
    fn view_controls_wrap_and_preserve_selection_and_expansion() {
        let config = test_config_with_ids(&["a", "b"]);
        let mut state = AppState::from_config(&config);
        state.terminal_size = Some((80, 8));
        state.systems[0].reachability = Reachability::Online;
        state.systems[0].latest = Some(NormalizedSnapshot::from_v1(&make_snapshot()));
        state.selected_id = Some("a".into());

        state.apply_action(Action::ToggleDrives);
        state.apply_action(Action::ToggleSystemView);
        assert_eq!(state.system_view_mode, SystemViewMode::Condensed);
        assert!(state.drives_expanded);
        assert_eq!(state.selected_id.as_deref(), Some("a"));
        state.apply_action(Action::ToggleSystemView);
        assert_eq!(state.system_view_mode, SystemViewMode::Normal);
        assert!(state.drives_expanded);
    }

    #[test]
    fn condensed_expansion_counts_only_valid_drive_rows() {
        let config = test_config_with_ids(&["a"]);
        let mut state = AppState::from_config(&config);
        state.system_view_mode = SystemViewMode::Condensed;
        state.drives_expanded = true;
        state.systems[0].reachability = Reachability::Online;
        let mut snapshot = NormalizedSnapshot::from_v1(&make_snapshot());
        snapshot.drives = Some(vec![
            crate::normalized::NormalizedDrive {
                name: "/".into(),
                used_bytes: 1,
                total_bytes: 2,
                available_bytes: None,
            },
            crate::normalized::NormalizedDrive {
                name: "/bad".into(),
                used_bytes: 3,
                total_bytes: 2,
                available_bytes: None,
            },
        ]);
        state.systems[0].latest = Some(snapshot);
        assert_eq!(entry_height(&state, 0), 2);
    }
}