gregg 1.0.0

Compact keyboard-first terminal monitor that polls greggd endpoints and renders each system in four rows.
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
#![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 gregg_protocol::StatusSnapshot;

use crate::action::Action;
use crate::config::Config;
use crate::endpoint::Endpoint;
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, 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,
    },
}

/// 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.
    pub latest: Option<StatusSnapshot>,
    /// 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)>,
}

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(|entry| 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,
            })
            .collect();

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

        Self {
            systems,
            selected_id,
            viewport_top_id,
            last_applied_generation: 0,
            refresh_status: RefreshStatus::Idle,
            terminal_size: 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) {
                match &result.outcome {
                    PollOutcome::Cancelled => {}
                    PollOutcome::Online(snapshot) => {
                        system.reachability = Reachability::Online;
                        system.latest = Some((**snapshot).clone());
                        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;
    }

    /// Apply a user action.
    pub fn apply_action(&mut self, action: Action) {
        match action {
            Action::SelectNext => {
                let order = self.display_order();
                self.move_selection(&order, 1);
            }
            Action::SelectPrevious => {
                let order = self.display_order();
                self.move_selection(&order, -1_isize);
            }
            Action::PageDown => {
                let order = self.display_order();
                let page = self.page_size();
                self.move_selection(&order, page);
            }
            Action::PageUp => {
                let order = self.display_order();
                let page = self.page_size();
                self.move_selection(&order, -page);
            }
            Action::SelectFirst => {
                let order = self.display_order();
                self.selected_id = order
                    .first()
                    .and_then(|&i| self.systems.get(i).map(|s| &s.id))
                    .cloned();
            }
            Action::SelectLast => {
                let order = self.display_order();
                self.selected_id = order
                    .last()
                    .and_then(|&i| self.systems.get(i).map(|s| &s.id))
                    .cloned();
            }
            Action::RefreshNow | Action::Quit => {} // Handled by caller.
            Action::ConfigReloaded(config) => self.rebuild_from_config(&config),
            Action::Resize { width, height } => {
                self.terminal_size = Some((width, height));
                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
    }

    /// Rebuild systems from a new config, preserving state for systems
    /// that still exist (matched by ID).
    pub fn rebuild_from_config(&mut self, config: &Config) {
        let old_systems: Vec<SystemState> = self.systems.drain(..).collect();

        self.systems = config
            .systems
            .iter()
            .map(|entry| {
                if let Some(existing) = old_systems.iter().find(|s| s.id == entry.id) {
                    let mut updated = existing.clone();
                    updated.endpoint = entry.to_endpoint();
                    updated.configured_name.clone_from(&entry.name);
                    updated
                } else {
                    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,
                    }
                }
            })
            .collect();

        // Ensure selection is valid.
        if let Some(ref sel) = self.selected_id {
            if !self.systems.iter().any(|s| &s.id == sel) {
                self.selected_id = self.systems.first().map(|s| s.id.clone());
            }
        } else {
            self.selected_id = self.systems.first().map(|s| s.id.clone());
        }

        // Ensure viewport is valid.
        if let Some(ref top) = self.viewport_top_id {
            if !self.systems.iter().any(|s| &s.id == top) {
                self.viewport_top_id = self.selected_id.clone();
            }
        } else {
            self.viewport_top_id = self.selected_id.clone();
        }
    }

    /// 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(2); // Reserve rows for headers/footers.

        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.systems[idx]);
            if rows + h > height && count > 0 {
                break;
            }
            rows += h;
            count += 1;
        }

        count.max(1)
    }
}

/// Return the row height for a system entry.
///
/// Online entries occupy 4 rows; pending and offline entries occupy 1 row.
#[must_use]
pub fn entry_height(system: &SystemState) -> u16 {
    match system.reachability {
        Reachability::Online => 4,
        Reachability::Pending | Reachability::Offline => 1,
    }
}

/// Compute which systems in display order are visible given a top
/// index, the system states, and available height.
///
/// Online entries take 4 rows; offline entries take 1. Partial entries
/// at the bottom are excluded when possible. If the terminal has fewer
/// than 4 usable rows, returns an empty range.
#[must_use]
pub fn visible_range(
    display_order: &[usize],
    systems: &[SystemState],
    top_index: usize,
    height: u16,
) -> Range<usize> {
    if height < 4 {
        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 >= systems.len() {
            break;
        }
        let h = entry_height(&systems[idx]);

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

    top_index..(top_index + count)
}

/// 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;
    };

    // Compute how many rows the currently visible region takes.
    let usable_height = height.saturating_sub(2); // Reserve for headers/footers.

    // Find which systems fit from top_pos downward.
    let visible = visible_range(&order, &state.systems, 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, scroll down so selected is visible
    // at the top of the viewport.
    if selected_pos >= top_pos {
        state.viewport_top_id = Some(state.systems[order[selected_pos]].id.clone());
    }
}

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

    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 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_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 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::SelectNext);
        assert_eq!(state.selected_id.as_deref(), Some("b"));

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

        // Should clamp at the end.
        state.apply_action(Action::SelectNext);
        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::SelectNext);
        state.apply_action(Action::SelectNext);
        assert_eq!(state.selected_id.as_deref(), Some("c"));

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

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

        // Should clamp at the beginning.
        state.apply_action(Action::SelectPrevious);
        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::SelectNext);
        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 selection_falls_back_when_system_removed() {
        let config = test_config_with_ids(&["a", "b"]);
        let mut state = AppState::from_config(&config);

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

        // Rebuild with only "a".
        let mut new_config = Config::default();
        new_config.systems.push(SystemEntry {
            id: "a".into(),
            host: "host0.local".into(),
            port: 11310,
            name: None,
        });

        state.rebuild_from_config(&new_config);
        // b is gone, selection should fall back to a.
        assert_eq!(state.selected_id.as_deref(), Some("a"));
    }

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

        // Give a a 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(make_snapshot())),
                latency: Duration::from_millis(50),
            }],
        };
        state.apply_batch(&batch);
        assert_eq!(state.systems[0].reachability, Reachability::Online);

        // Rebuild with same config.
        state.rebuild_from_config(&config);

        // State should be preserved.
        assert_eq!(state.systems.len(), 2);
        assert_eq!(state.systems[0].reachability, Reachability::Online);
        assert!(state.systems[0].latest.is_some());
        assert_eq!(state.systems[0].id, "a");
    }

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

        let mut new_config = test_config_with_ids(&["a", "b"]);
        // Use same ID for a so it's recognized.
        new_config.systems[0].id = "a".into();

        state.rebuild_from_config(&new_config);
        assert_eq!(state.systems.len(), 2);
        // New system b should be pending.
        assert_eq!(state.systems[1].reachability, Reachability::Pending);
    }

    #[test]
    fn entry_height_online_is_four() {
        let mut system = 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,
        };
        assert_eq!(entry_height(&system), 4);

        system.reachability = Reachability::Pending;
        assert_eq!(entry_height(&system), 1);

        system.reachability = Reachability::Offline;
        assert_eq!(entry_height(&system), 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.systems, 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 state = AppState::from_config(&config);
        let order = state.display_order();
        let range = visible_range(&order, &state.systems, 0, 3);
        // Terminal too small for even one online entry.
        assert!(range.is_empty());
    }

    #[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 config_reloaded_action() {
        let config = test_config_with_ids(&["a", "b"]);
        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::Online(Box::new(make_snapshot())),
                latency: Duration::from_millis(50),
            }],
        };
        state.apply_batch(&batch);

        // Reload with new config.
        let mut new_config = test_config_with_ids(&["a", "b", "c"]);
        new_config.systems[0].id = "a".into();
        new_config.systems[1].id = "b".into();
        new_config.systems[2].id = "c".into();

        state.apply_action(Action::ConfigReloaded(new_config));

        assert_eq!(state.systems.len(), 3);
        // a's state should be preserved.
        assert_eq!(state.systems[0].reachability, Reachability::Online);
    }

    #[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::SelectNext);
        assert!(state.selected_id.is_none());

        state.apply_action(Action::SelectPrevious);
        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");
    }
}