kdash 1.1.0

A fast and simple dashboard for Kubernetes
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
use std::collections::VecDeque;

use async_trait::async_trait;
use ratatui::{
  layout::Rect,
  style::{Modifier, Style},
  text::{Line as RatatuiLine, Span},
  widgets::{Block, List, ListItem, ListState, TableState},
  Frame,
};
use serde::Serialize;

use super::{ActiveBlock, App, Route};
use crate::network::Network;

#[async_trait]
pub trait AppResource {
  fn render(block: ActiveBlock, f: &mut Frame<'_>, app: &mut App, area: Rect);

  async fn get_resource(network: &Network<'_>);
}
/// Trait for workload resources that own pods via a label selector.
pub trait HasPodSelector {
  /// Returns a comma-separated label selector string (e.g., "app=web,version=v2")
  /// suitable for use with `ListParams::labels()`. Returns `None` if the resource
  /// has no selector (e.g., missing spec).
  fn pod_label_selector(&self) -> Option<String>;
}

/// Helper to convert a BTreeMap of labels to a comma-separated selector string.
pub fn labels_to_selector(labels: &std::collections::BTreeMap<String, String>) -> String {
  labels
    .iter()
    .map(|(k, v)| format!("{}={}", k, v))
    .collect::<Vec<_>>()
    .join(",")
}

/// Minimal trait for types that expose a resource name (used by filtering/display).
pub trait Named {
  fn get_name(&self) -> &String;
}

pub trait KubeResource<T: Serialize>: Named {
  fn get_k8s_obj(&self) -> &T;

  /// generate YAML from the original kubernetes resource
  fn resource_to_yaml(&self) -> String {
    match serde_yaml::to_string(&self.get_k8s_obj()) {
      Ok(yaml) => yaml,
      Err(_) => "".into(),
    }
  }
}

pub trait Scrollable {
  fn handle_scroll(&mut self, up: bool, page: bool) {
    // support page up/down
    let inc_or_dec = if page { 10 } else { 1 };
    if up {
      self.scroll_up(inc_or_dec);
    } else {
      self.scroll_down(inc_or_dec);
    }
  }
  fn scroll_down(&mut self, inc_or_dec: usize);
  fn scroll_up(&mut self, inc_or_dec: usize);
}

pub struct StatefulList<T> {
  pub state: ListState,
  pub items: Vec<T>,
}

impl<T> StatefulList<T> {
  pub fn new() -> StatefulList<T> {
    StatefulList {
      state: ListState::default(),
      items: Vec::new(),
    }
  }
  pub fn with_items(items: Vec<T>) -> StatefulList<T> {
    let mut state = ListState::default();
    if !items.is_empty() {
      state.select(Some(0));
    }
    StatefulList { state, items }
  }
}

impl<T> Scrollable for StatefulList<T> {
  // for lists we cycle back to the beginning when we reach the end
  fn scroll_down(&mut self, increment: usize) {
    let i = match self.state.selected() {
      Some(i) => {
        if i >= self.items.len().saturating_sub(increment) {
          0
        } else {
          i + increment
        }
      }
      None => 0,
    };
    self.state.select(Some(i));
  }
  // for lists we cycle back to the end when we reach the beginning
  fn scroll_up(&mut self, decrement: usize) {
    let i = match self.state.selected() {
      Some(i) => {
        if i == 0 {
          self.items.len().saturating_sub(decrement)
        } else {
          i.saturating_sub(decrement)
        }
      }
      None => 0,
    };
    self.state.select(Some(i));
  }
}

#[derive(Clone, Debug)]
pub struct StatefulTable<T> {
  pub state: TableState,
  pub items: Vec<T>,
  pub filter: String,
  pub filter_active: bool,
  /// When a filter is active, maps visible row index → `items` index.
  /// Empty when no filter is applied.
  pub filtered_indices: Vec<usize>,
}

pub trait FilterableTable {
  fn is_filter_active(&self) -> bool;
  fn count_label(&self) -> String;
  fn filter_parts_mut(&mut self) -> (&mut String, &mut bool, &mut TableState);
}

impl<T> StatefulTable<T> {
  pub fn new() -> StatefulTable<T> {
    StatefulTable {
      state: TableState::default(),
      items: Vec::new(),
      filter: String::new(),
      filter_active: false,
      filtered_indices: Vec::new(),
    }
  }

  pub fn with_items(items: Vec<T>) -> StatefulTable<T> {
    let mut table = StatefulTable::new();
    if !items.is_empty() {
      table.state.select(Some(0));
    }
    table.set_items(items);
    table
  }

  pub fn set_items(&mut self, items: Vec<T>) {
    let item_len = items.len();
    self.items = items;
    if !self.items.is_empty() {
      let i = self.state.selected().map_or(0, |i| {
        if i > 0 && i < item_len {
          i
        } else if i >= item_len {
          item_len - 1
        } else {
          0
        }
      });
      self.state.select(Some(i));
    }
  }
}

impl<T> FilterableTable for StatefulTable<T> {
  fn is_filter_active(&self) -> bool {
    self.filter_active
  }

  fn count_label(&self) -> String {
    if self.filter.is_empty() {
      self.items.len().to_string()
    } else {
      format!("{}/{}", self.filtered_indices.len(), self.items.len())
    }
  }

  fn filter_parts_mut(&mut self) -> (&mut String, &mut bool, &mut TableState) {
    (&mut self.filter, &mut self.filter_active, &mut self.state)
  }
}

impl<T> Scrollable for StatefulTable<T> {
  fn scroll_down(&mut self, increment: usize) {
    if let Some(i) = self.state.selected() {
      if (i + increment) < self.items.len() {
        self.state.select(Some(i + increment));
      } else {
        self.state.select(Some(self.items.len().saturating_sub(1)));
      }
    }
  }

  fn scroll_up(&mut self, decrement: usize) {
    if let Some(i) = self.state.selected() {
      if i != 0 {
        self.state.select(Some(i.saturating_sub(decrement)));
      }
    }
  }
}

impl<T: Clone> StatefulTable<T> {
  /// A clone of the currently selected item.
  /// When a filter is active, maps the visual index through `filtered_indices`
  /// so the correct item is returned regardless of filtering.
  pub fn get_selected_item_copy(&self) -> Option<T> {
    if !self.items.is_empty() {
      self.state.selected().and_then(|i| {
        if self.filtered_indices.is_empty() {
          self.items.get(i).cloned()
        } else {
          self
            .filtered_indices
            .get(i)
            .and_then(|&real| self.items.get(real).cloned())
        }
      })
    } else {
      None
    }
  }
}

#[derive(Clone)]
pub struct TabRoute {
  pub title: String,
  pub route: Route,
}

pub struct TabsState {
  pub items: Vec<TabRoute>,
  pub index: usize,
  pub scroll_start: usize,
}

impl TabsState {
  pub fn new(items: Vec<TabRoute>) -> TabsState {
    TabsState {
      items,
      index: 0,
      scroll_start: 0,
    }
  }
  pub fn set_index(&mut self, index: usize) -> &TabRoute {
    self.index = index;
    &self.items[self.index]
  }
  pub fn get_active_route(&self) -> &Route {
    &self.items[self.index].route
  }

  pub fn next(&mut self) {
    self.index = (self.index + 1) % self.items.len();
  }
  pub fn previous(&mut self) {
    if self.index > 0 {
      self.index -= 1;
    } else {
      self.index = self.items.len() - 1;
    }
  }
}

#[derive(Debug)]
pub struct ScrollableTxt {
  items: Vec<String>,
  pub offset: usize,
  /// Pre-joined text, computed once when items change.
  txt_cache: String,
  /// Cached syntax-highlighted lines, reused across render frames.
  /// Invalidated when content or theme changes.
  pub highlighted_lines: Vec<RatatuiLine<'static>>,
  /// The theme used to produce `highlighted_lines` (true = light).
  pub highlight_light_theme: bool,
}

impl PartialEq for ScrollableTxt {
  fn eq(&self, other: &Self) -> bool {
    self.items == other.items && self.offset == other.offset
  }
}

impl Eq for ScrollableTxt {}

impl ScrollableTxt {
  pub fn new() -> ScrollableTxt {
    ScrollableTxt {
      items: vec![],
      offset: 0,
      txt_cache: String::new(),
      highlighted_lines: Vec::new(),
      highlight_light_theme: false,
    }
  }

  pub fn with_string(item: String) -> ScrollableTxt {
    let items: Vec<&str> = item.split('\n').collect();
    let items: Vec<String> = items.iter().map(|it| it.to_string()).collect();
    ScrollableTxt {
      txt_cache: item,
      items,
      offset: 0,
      highlighted_lines: Vec::new(),
      highlight_light_theme: false,
    }
  }

  pub fn get_txt(&self) -> &str {
    &self.txt_cache
  }
}

impl Scrollable for ScrollableTxt {
  fn scroll_down(&mut self, increment: usize) {
    // Ratatui's Paragraph with Wrap counts scroll offset in *visual* rows
    // (post-wrap), but we only know the number of source lines.  We cap at
    // items.len() - 1 so at least the last source line remains visible,
    // while still allowing enough scroll range for wrapped content.
    let max_offset = self.items.len().saturating_sub(1);
    if self.offset < max_offset {
      self.offset = (self.offset + increment).min(max_offset);
    }
  }
  fn scroll_up(&mut self, decrement: usize) {
    if self.offset > 0 {
      self.offset = self.offset.saturating_sub(decrement);
    }
  }
}

// TODO implement line buffer to avoid gathering too much data in memory
const MAX_LOG_RECORDS: usize = 10_000;

#[derive(Debug, Clone)]
pub struct LogsState {
  /// Stores the log messages to be displayed
  ///
  /// (original_message, (wrapped_message, wrapped_at_width))
  #[allow(clippy::type_complexity)]
  records: VecDeque<(String, Option<(Vec<ListItem<'static>>, u16)>)>,
  wrapped_length: usize,
  viewport_height: usize,
  pub state: ListState,
  pub id: String,
}

impl LogsState {
  pub fn new(id: String) -> LogsState {
    LogsState {
      records: VecDeque::with_capacity(512),
      state: ListState::default(),
      wrapped_length: 0,
      viewport_height: 0,
      id,
    }
  }

  /// get a plain text version of the logs
  pub fn get_plain_text(&self) -> String {
    self.records.iter().fold(String::new(), |mut acc, v| {
      acc.push('\n');
      acc.push_str(v.0.as_str());
      acc
    })
  }

  /// Render the current state as a list widget
  pub fn render_list(
    &mut self,
    f: &mut Frame<'_>,
    logs_area: Rect,
    block: Block<'_>,
    style: Style,
    follow: bool,
  ) {
    let available_lines = logs_area.height as usize;
    self.viewport_height = available_lines;
    let wrap_width = logs_area.width.max(1);
    let mut items = self.wrapped_items(wrap_width, style);
    self.wrapped_length = items.len();

    if follow {
      self.unselect();
      let wrapped_lines_to_skip = items.len().saturating_sub(available_lines);
      items = items.into_iter().skip(wrapped_lines_to_skip).collect();
    }

    // TODO: All this is a workaround. we should be wrapping text with paragraph, but it currently
    // doesn't support wrapping and staying scrolled to the bottom
    //
    // see https://github.com/fdehau/tui-rs/issues/89
    let list = List::new(items)
      .block(block)
      .highlight_style(Style::default().add_modifier(Modifier::BOLD));

    f.render_stateful_widget(list, logs_area, &mut self.state);
  }
  /// Add a record to be displayed
  #[cfg(test)]
  pub fn add_record(&mut self, record: String) {
    self.records.push_back((record, None));
    while self.records.len() > MAX_LOG_RECORDS {
      self.records.pop_front();
    }
  }

  /// Add multiple records in a batch
  pub fn add_records(&mut self, records: Vec<String>) {
    for record in records {
      self.records.push_back((record, None));
    }
    while self.records.len() > MAX_LOG_RECORDS {
      self.records.pop_front();
    }
  }

  /// Get the last n raw log lines (for dedup on reconnect)
  pub fn last_n_records(&self, n: usize) -> Vec<&str> {
    self
      .records
      .iter()
      .rev()
      .take(n)
      .map(|(s, _)| s.as_str())
      .collect()
  }

  fn unselect(&mut self) {
    self.state.select(None);
  }

  pub fn freeze_follow_position(&mut self) {
    if self.state.selected().is_none() {
      let offset = self.wrapped_length.saturating_sub(self.viewport_height);
      self.state.select(Some(offset));
    }
  }

  fn wrapped_items(&mut self, width: u16, style: Style) -> Vec<ListItem<'static>> {
    let logs_area_width = width as usize;

    self
      .records
      .iter_mut()
      .flat_map(|record| {
        if let Some(wrapped) = &record.1 {
          if wrapped.1 == width {
            return wrapped.0.clone();
          }
        }

        record.1 = Some((
          textwrap::wrap(record.0.as_ref(), logs_area_width)
            .into_iter()
            .map(|line| line.to_string())
            .map(|line| Span::styled(line, style))
            .map(ListItem::new)
            .collect::<Vec<ListItem<'_>>>(),
          width,
        ));

        record
          .1
          .as_ref()
          .map(|wrapped| wrapped.0.clone())
          .unwrap_or_default()
      })
      .collect()
  }
}

impl Scrollable for LogsState {
  fn scroll_down(&mut self, increment: usize) {
    let i = self.state.selected().map_or(0, |i| {
      if i >= self.wrapped_length.saturating_sub(increment) {
        i
      } else {
        i + increment
      }
    });
    self.state.select(Some(i));
  }

  fn scroll_up(&mut self, decrement: usize) {
    let i = self.state.selected().map_or(0, |i| {
      if i != 0 {
        i.saturating_sub(decrement)
      } else {
        0
      }
    });
    self.state.select(Some(i));
  }
}

#[cfg(test)]
mod tests {
  use k8s_openapi::api::core::v1::Namespace;
  use kube::api::ObjectMeta;
  use ratatui::{backend::TestBackend, buffer::Buffer, layout::Position, Terminal};

  use super::*;
  use crate::app::{ns::KubeNs, ActiveBlock, RouteId};

  #[test]
  fn test_kube_resource() {
    struct TestStruct {
      name: String,
      k8s_obj: Namespace,
    }
    impl Named for TestStruct {
      fn get_name(&self) -> &String {
        &self.name
      }
    }
    impl KubeResource<Namespace> for TestStruct {
      fn get_k8s_obj(&self) -> &Namespace {
        &self.k8s_obj
      }
    }
    let ts = TestStruct {
      name: "test".into(),
      k8s_obj: Namespace {
        metadata: ObjectMeta {
          name: Some("test".into()),
          namespace: Some("test".into()),
          ..ObjectMeta::default()
        },
        ..Namespace::default()
      },
    };
    assert_eq!(
      ts.resource_to_yaml(),
      "apiVersion: v1\nkind: Namespace\nmetadata:\n  name: test\n  namespace: test\n"
    )
  }

  #[test]
  fn test_stateful_table() {
    let mut sft: StatefulTable<KubeNs> = StatefulTable::new();

    assert_eq!(sft.items.len(), 0);
    assert_eq!(sft.state.selected(), None);
    assert!(sft.filter.is_empty());
    assert!(!sft.filter_active);
    // check default selection on set
    sft.set_items(vec![KubeNs::default(), KubeNs::default()]);
    assert_eq!(sft.items.len(), 2);
    assert_eq!(sft.state.selected(), Some(0));
    // check selection retain on set
    sft.state.select(Some(1));
    sft.set_items(vec![
      KubeNs::default(),
      KubeNs::default(),
      KubeNs::default(),
    ]);
    assert_eq!(sft.items.len(), 3);
    assert_eq!(sft.state.selected(), Some(1));
    // check selection overflow prevention
    sft.state.select(Some(2));
    sft.set_items(vec![KubeNs::default(), KubeNs::default()]);
    assert_eq!(sft.items.len(), 2);
    assert_eq!(sft.state.selected(), Some(1));
    // check scroll down
    sft.state.select(Some(0));
    assert_eq!(sft.state.selected(), Some(0));
    sft.scroll_down(1);
    assert_eq!(sft.state.selected(), Some(1));
    // check scroll overflow
    sft.scroll_down(1);
    assert_eq!(sft.state.selected(), Some(1));
    sft.scroll_up(1);
    assert_eq!(sft.state.selected(), Some(0));
    // check scroll overflow
    sft.scroll_up(1);
    assert_eq!(sft.state.selected(), Some(0));
    // check increment
    sft.scroll_down(10);
    assert_eq!(sft.state.selected(), Some(1));

    let sft2 = StatefulTable::with_items(vec![KubeNs::default(), KubeNs::default()]);
    assert_eq!(sft2.state.selected(), Some(0));
  }

  #[test]
  fn test_filtered_selection_returns_correct_item() {
    let mut sft: StatefulTable<&str> = StatefulTable::new();
    sft.set_items(vec!["alpha", "beta", "gamma", "delta", "epsilon"]);

    // Simulate a filter that shows items at indices 1, 3 (beta, delta)
    sft.filtered_indices = vec![1, 3];

    // Visual row 0 → items[1] = "beta"
    sft.state.select(Some(0));
    assert_eq!(sft.get_selected_item_copy(), Some("beta"));

    // Visual row 1 → items[3] = "delta"
    sft.state.select(Some(1));
    assert_eq!(sft.get_selected_item_copy(), Some("delta"));
  }

  #[test]
  fn test_no_filter_returns_direct_index() {
    let mut sft: StatefulTable<&str> = StatefulTable::new();
    sft.set_items(vec!["alpha", "beta", "gamma"]);

    // No filter — filtered_indices is empty
    sft.state.select(Some(2));
    assert_eq!(sft.get_selected_item_copy(), Some("gamma"));
  }

  #[test]
  fn test_filtered_selection_out_of_range_returns_none() {
    let mut sft: StatefulTable<&str> = StatefulTable::new();
    sft.set_items(vec!["alpha", "beta", "gamma"]);

    // Filter shows 1 item but selection points past it
    sft.filtered_indices = vec![2];
    sft.state.select(Some(5));
    assert_eq!(sft.get_selected_item_copy(), None);
  }

  #[test]
  fn test_filtered_empty_matches_returns_none() {
    let mut sft: StatefulTable<&str> = StatefulTable::new();
    sft.set_items(vec!["alpha", "beta"]);

    // Filter matches nothing
    sft.filtered_indices = vec![];
    sft.state.select(Some(0));
    // filtered_indices is empty → direct indexing (no filter active)
    assert_eq!(sft.get_selected_item_copy(), Some("alpha"));
  }

  #[test]
  fn test_handle_table_scroll() {
    let mut item: StatefulTable<&str> = StatefulTable::new();
    item.set_items(vec!["A", "B", "C"]);

    assert_eq!(item.state.selected(), Some(0));

    item.handle_scroll(false, false);
    assert_eq!(item.state.selected(), Some(1));

    item.handle_scroll(false, false);
    assert_eq!(item.state.selected(), Some(2));

    item.handle_scroll(false, false);
    assert_eq!(item.state.selected(), Some(2));
    // previous
    item.handle_scroll(true, false);
    assert_eq!(item.state.selected(), Some(1));
    // page down
    item.handle_scroll(false, true);
    assert_eq!(item.state.selected(), Some(2));
    // page up
    item.handle_scroll(true, true);
    assert_eq!(item.state.selected(), Some(0));
  }

  #[test]
  fn test_stateful_tab() {
    let mut tab = TabsState::new(vec![
      TabRoute {
        title: "Hello".into(),
        route: Route {
          active_block: ActiveBlock::Pods,
          id: RouteId::Home,
        },
      },
      TabRoute {
        title: "Test".into(),
        route: Route {
          active_block: ActiveBlock::Nodes,
          id: RouteId::Home,
        },
      },
    ]);

    assert_eq!(tab.index, 0);
    assert_eq!(tab.scroll_start, 0);
    assert_eq!(tab.get_active_route().active_block, ActiveBlock::Pods);
    tab.next();
    assert_eq!(tab.index, 1);
    assert_eq!(tab.get_active_route().active_block, ActiveBlock::Nodes);
    tab.next();
    assert_eq!(tab.index, 0);
    assert_eq!(tab.get_active_route().active_block, ActiveBlock::Pods);
    tab.previous();
    assert_eq!(tab.index, 1);
    assert_eq!(tab.get_active_route().active_block, ActiveBlock::Nodes);
    tab.previous();
    assert_eq!(tab.index, 0);
    assert_eq!(tab.get_active_route().active_block, ActiveBlock::Pods);
  }

  #[test]
  fn test_scrollable_txt() {
    let mut stxt = ScrollableTxt::with_string("test\n multiline\n string".into());

    assert_eq!(stxt.offset, 0);
    assert_eq!(stxt.items.len(), 3);

    assert_eq!(stxt.get_txt(), "test\n multiline\n string");

    // 3 items → max offset = 2 (last line visible)
    stxt.scroll_down(1);
    assert_eq!(stxt.offset, 1);
    stxt.scroll_down(5);
    assert_eq!(stxt.offset, 2);

    // 10 lines → max offset = 9
    let mut stxt2 = ScrollableTxt::with_string("te\nst\nmul\ntil\ni\nne\nstr\ni\nn\ng".into());
    assert_eq!(stxt2.items.len(), 10);
    stxt2.scroll_down(1);
    assert_eq!(stxt2.offset, 1);
    stxt2.scroll_down(1);
    assert_eq!(stxt2.offset, 2);
    stxt2.scroll_down(5);
    assert_eq!(stxt2.offset, 7);
    for _ in 0..5 {
      stxt2.scroll_down(1);
    }
    // capped at len - 1 = 9
    assert_eq!(stxt2.offset, 9);
    stxt2.scroll_up(1);
    assert_eq!(stxt2.offset, 8);
    stxt2.scroll_up(8);
    assert_eq!(stxt2.offset, 0);
    stxt2.scroll_up(1);
    // no overflow past (0)
    assert_eq!(stxt2.offset, 0);
  }

  #[test]
  fn test_scrollable_txt_viewport_reaches_end() {
    // 100 lines → max offset = 99
    let lines: Vec<String> = (0..100).map(|i| format!("line {}", i)).collect();
    let mut stxt = ScrollableTxt::with_string(lines.join("\n"));

    assert_eq!(stxt.items.len(), 100);
    for _ in 0..110 {
      stxt.scroll_down(1);
    }
    assert_eq!(stxt.offset, 99);
  }

  #[test]
  fn test_scrollable_txt_single_line_no_scroll() {
    // 1 line → max offset = 0
    let mut stxt = ScrollableTxt::with_string("hello".into());

    stxt.scroll_down(1);
    assert_eq!(stxt.offset, 0);
  }

  #[test]
  fn test_scrollable_txt_scroll_cap_is_len_minus_one() {
    // 20 lines → max offset = 19 regardless of viewport
    let lines: Vec<String> = (0..20).map(|i| format!("line {}", i)).collect();
    let mut stxt = ScrollableTxt::with_string(lines.join("\n"));

    for _ in 0..30 {
      stxt.scroll_down(1);
    }
    assert_eq!(stxt.offset, 19);
  }

  #[test]
  fn test_scrollable_txt_beyond_u16_max() {
    let line_count = u16::MAX as usize + 100; // 65635 lines
    let lines: Vec<String> = (0..line_count).map(|i| format!("line {}", i)).collect();
    let mut stxt = ScrollableTxt::with_string(lines.join("\n"));
    assert_eq!(stxt.items.len(), line_count);
    assert_eq!(stxt.offset, 0);

    // Scroll down past u16::MAX in large steps — should not wrap or panic
    let target = line_count.saturating_sub(1); // max reachable offset (len - 1)
    for _ in 0..(target / 1000) {
      stxt.scroll_down(1000);
    }
    // Finish off with single increments to reach the cap
    for _ in 0..1000 {
      stxt.scroll_down(1);
    }

    // Offset must be beyond what u16 could hold and must not have wrapped
    assert!(
      stxt.offset > u16::MAX as usize,
      "offset {} should exceed u16::MAX (65535)",
      stxt.offset
    );
    // Must be capped at items.len() - 1
    assert!(
      stxt.offset <= target,
      "offset {} should be at most {}",
      stxt.offset,
      target
    );

    // Scroll back up past u16::MAX boundary — should not wrap or panic
    for _ in 0..(stxt.offset / 1000) {
      stxt.scroll_up(1000);
    }
    for _ in 0..1000 {
      stxt.scroll_up(1);
    }
    assert_eq!(stxt.offset, 0);
  }

  #[test]
  fn test_scrollable_txt_last_line_always_reachable() {
    // 10 source lines → max offset = 9 (last line at top of viewport)
    let lines: Vec<String> = (0..10).map(|i| format!("line {}", i)).collect();
    let mut stxt = ScrollableTxt::with_string(lines.join("\n"));

    for _ in 0..20 {
      stxt.scroll_down(1);
    }
    assert_eq!(stxt.offset, 9);
  }

  #[test]
  fn test_logs_state() {
    let mut log = LogsState::new("1".into());
    log.add_record("record 1".into());
    log.add_record("record 2".into());

    assert_eq!(log.get_plain_text(), "\nrecord 1\nrecord 2");

    let backend = TestBackend::new(20, 7);
    let mut terminal = Terminal::new(backend).unwrap();

    log.add_record("record 4 should be long enough to be wrapped".into());
    log.add_record("record 5".into());
    log.add_record("record 6".into());
    log.add_record("record 7".into());
    log.add_record("record 8".into());

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), true))
      .unwrap();

    let expected = Buffer::with_lines(vec![
      "record 4 should be  ",
      "long enough to be   ",
      "wrapped             ",
      "record 5            ",
      "record 6            ",
      "record 7            ",
      "record 8            ",
    ]);

    terminal.backend().assert_buffer(&expected);

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), false))
      .unwrap();

    let expected2 = Buffer::with_lines(vec![
      "record 1            ",
      "record 2            ",
      "record 4 should be  ",
      "long enough to be   ",
      "wrapped             ",
      "record 5            ",
      "record 6            ",
    ]);

    terminal.backend().assert_buffer(&expected2);

    log.add_record("record 9".into());
    log.add_record("record 10 which is again looooooooooooooooooooooooooooooonnnng".into());
    log.add_record("record 11".into());
    // enabling follow should scroll back to bottom
    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), true))
      .unwrap();

    let expected3 = Buffer::with_lines(vec![
      "record 8            ",
      "record 9            ",
      "record 10           ",
      "which is again      ",
      "looooooooooooooooooo",
      "oooooooooooonnnng   ",
      "record 11           ",
    ]);

    terminal.backend().assert_buffer(&expected3);

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), false))
      .unwrap();

    let expected4 = Buffer::with_lines(vec![
      "record 1            ",
      "record 2            ",
      "record 4 should be  ",
      "long enough to be   ",
      "wrapped             ",
      "record 5            ",
      "record 6            ",
    ]);

    terminal.backend().assert_buffer(&expected4);

    log.scroll_up(1); // to reset select state
    log.scroll_down(11);

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), false))
      .unwrap();

    let mut expected5 = Buffer::with_lines(vec![
      "record 5            ",
      "record 6            ",
      "record 7            ",
      "record 8            ",
      "record 9            ",
      "record 10           ",
      "which is again      ",
    ]);

    // Second row table header style
    for col in 0..=19 {
      expected5
        .cell_mut(Position::new(col, 6))
        .unwrap()
        .set_style(Style::default().add_modifier(Modifier::BOLD));
    }

    terminal.backend().assert_buffer(&expected5);
  }

  #[test]
  fn test_logs_state_bounded() {
    let mut log = LogsState::new("bounded".into());

    // Add more than MAX_LOG_RECORDS entries
    for i in 0..MAX_LOG_RECORDS + 100 {
      log.add_record(format!("record {}", i));
    }

    // Should be capped at MAX_LOG_RECORDS
    assert_eq!(log.records.len(), MAX_LOG_RECORDS);

    // Oldest records should have been evicted — first record should be 100
    assert_eq!(log.records.front().unwrap().0, "record 100");
    assert_eq!(
      log.records.back().unwrap().0,
      format!("record {}", MAX_LOG_RECORDS + 99)
    );
  }

  #[test]
  fn test_logs_state_bounded_exactly_at_limit() {
    let mut log = LogsState::new("exact".into());

    // Add exactly MAX_LOG_RECORDS entries — no eviction should occur
    for i in 0..MAX_LOG_RECORDS {
      log.add_record(format!("record {}", i));
    }

    assert_eq!(log.records.len(), MAX_LOG_RECORDS);
    assert_eq!(log.records.front().unwrap().0, "record 0");
    assert_eq!(
      log.records.back().unwrap().0,
      format!("record {}", MAX_LOG_RECORDS - 1)
    );
  }

  #[test]
  fn test_logs_state_bounded_one_over() {
    let mut log = LogsState::new("one_over".into());

    for i in 0..MAX_LOG_RECORDS + 1 {
      log.add_record(format!("record {}", i));
    }

    assert_eq!(log.records.len(), MAX_LOG_RECORDS);
    // First record should be evicted
    assert_eq!(log.records.front().unwrap().0, "record 1");
    assert_eq!(
      log.records.back().unwrap().0,
      format!("record {}", MAX_LOG_RECORDS)
    );
  }

  #[test]
  fn test_logs_state_empty() {
    let log = LogsState::new("empty".into());
    assert_eq!(log.records.len(), 0);
    assert_eq!(log.get_plain_text(), "");
  }

  #[test]
  fn test_logs_state_plain_text_preserves_order() {
    let mut log = LogsState::new("text".into());
    log.add_record("first".into());
    log.add_record("second".into());
    log.add_record("third".into());

    let text = log.get_plain_text();
    assert_eq!(text, "\nfirst\nsecond\nthird");
  }

  #[test]
  fn test_logs_state_follow_tracks_last_wrapped_lines() {
    let mut log = LogsState::new("follow".into());
    let backend = TestBackend::new(12, 4);
    let mut terminal = Terminal::new(backend).unwrap();

    log.add_record("alpha".into());
    log.add_record("beta".into());
    log.add_record("gamma delta epsilon".into());

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), true))
      .unwrap();

    let expected_initial = Buffer::with_lines(vec![
      "alpha       ",
      "beta        ",
      "gamma delta ",
      "epsilon     ",
    ]);
    terminal.backend().assert_buffer(&expected_initial);

    log.add_record("zeta eta theta".into());

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), true))
      .unwrap();

    let expected_after_append = Buffer::with_lines(vec![
      "gamma delta ",
      "epsilon     ",
      "zeta eta    ",
      "theta       ",
    ]);
    terminal.backend().assert_buffer(&expected_after_append);
  }

  #[test]
  fn test_logs_state_freeze_follow_position_keeps_current_bottom_offset() {
    let mut log = LogsState::new("freeze".into());
    let backend = TestBackend::new(12, 4);
    let mut terminal = Terminal::new(backend).unwrap();

    log.add_record("alpha".into());
    log.add_record("beta".into());
    log.add_record("gamma delta epsilon".into());
    log.add_record("zeta eta theta".into());

    terminal
      .draw(|f| log.render_list(f, f.area(), Block::default(), Style::default(), true))
      .unwrap();

    log.freeze_follow_position();

    assert_eq!(log.state.selected(), Some(2));
  }
}