memtui 0.1.1

An interactive TUI (Terminal User Interface) for browsing and inspecting key-value stores (Redis, Memcached, etc.)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
use super::Component;
use crate::action::Action;
use crate::formatter::{Formatter, JsonFormatter, TextFormatter};
use crate::types::{Value, ValueType};
use crossterm::event::KeyEvent;
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{
        Block, BorderType, Borders, Cell, Paragraph, Row, Scrollbar, ScrollbarOrientation,
        ScrollbarState, Table, TableState, Wrap,
    },
};

use serde_json::Value as JsonValue;
use std::sync::Arc;
use tracing::trace;
use unicode_width::UnicodeWidthChar;

pub struct ValueViewerProps<'a> {
    pub selected_value: Option<&'a Value>,
    pub selected_key_type: Option<ValueType>,
    pub error_message: Option<&'a String>,
    pub json_formatter: &'a JsonFormatter,
    pub text_formatter: &'a TextFormatter,
    pub is_active: bool,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum TextContentKind {
    Plain,
    Json,
}

struct TextCache {
    source_ptr: usize,
    source_len: usize,
    wrap_width: u16,
    kind: TextContentKind,
    // Store UNWRAPPED lines - wrap on-demand only for visible portion
    unwrapped_lines: Vec<Line<'static>>,
    paragraph_style: Style,
    // Cached total wrapped line count (calculated once)
    total_wrapped_lines: usize,
    // Cache wrapped line count per unwrapped line for fast lookups
    wrapped_counts: Vec<usize>,
    // Cache start index of wrapped lines for each unwrapped line (prefix sums)
    line_offsets: Vec<usize>,
    // Cache wrapped lines per unwrapped line to avoid re-wrapping on every render
    // Use Arc to avoid expensive cloning on every frame
    wrapped_cache: Vec<Option<Arc<Vec<Line<'static>>>>>,
}

impl TextCache {
    fn new(
        value: &Value,
        kind: TextContentKind,
        paragraph_style: Style,
        unwrapped_lines: Vec<Line<'static>>,
        wrap_width: u16,
    ) -> Self {
        let width = wrap_width.max(1) as usize;

        // Pre-calculate wrapped line count per unwrapped line using EXACT wrapping logic
        // This ensures scrollbar and render loop are perfectly synced
        let wrapped_counts: Vec<usize> = unwrapped_lines
            .iter()
            .map(|line| ValueViewer::count_wrapped_lines(line, width))
            .collect();

        let total_wrapped_lines: usize = wrapped_counts.iter().sum();

        let mut line_offsets = Vec::with_capacity(wrapped_counts.len());
        let mut current = 0;
        for &count in &wrapped_counts {
            line_offsets.push(current);
            current += count;
        }

        // Pre-allocate cache but don't wrap yet (lazy)
        let wrapped_cache = vec![None; unwrapped_lines.len()];

        Self {
            source_ptr: value.data.as_ptr() as usize,
            source_len: value.data.len(),
            wrap_width: wrap_width.max(1),
            kind,
            unwrapped_lines,
            paragraph_style,
            total_wrapped_lines,
            wrapped_counts,
            line_offsets,
            wrapped_cache,
        }
    }

    /// Render lines directly from cache without intermediate Vec (zero-copy!)
    fn render_visible_lines(
        &mut self,
        buf: &mut ratatui::buffer::Buffer,
        start_wrapped_line: usize,
        end_wrapped_line: usize,
        area: Rect,
        paragraph_style: Style,
    ) {
        // Bounds check
        if start_wrapped_line >= end_wrapped_line || start_wrapped_line >= self.total_wrapped_lines
        {
            return;
        }

        let end_wrapped_line = end_wrapped_line.min(self.total_wrapped_lines);
        let mut screen_y = 0u16;

        // Find start index using binary search to avoid iterating all lines
        let start_idx = match self.line_offsets.binary_search(&start_wrapped_line) {
            Ok(i) => i,
            Err(i) => i.saturating_sub(1),
        };

        let mut current_wrapped_index = self.line_offsets.get(start_idx).copied().unwrap_or(0);

        // Find and render visible lines directly from cache
        for (idx, unwrapped) in self.unwrapped_lines.iter().enumerate().skip(start_idx) {
            let wrapped_count = self.wrapped_counts.get(idx).copied().unwrap_or(1);

            // Skip lines before visible range (only happens if binary search landed us early)
            if current_wrapped_index + wrapped_count <= start_wrapped_line {
                current_wrapped_index += wrapped_count;
                continue;
            }

            // Get wrapped lines from cache (or wrap and cache)
            let wrapped = if let Some(cached) = self.wrapped_cache.get(idx).and_then(|c| c.as_ref())
            {
                Arc::clone(cached)
            } else {
                let wrapped = Arc::new(ValueViewer::wrap_single_line(
                    unwrapped,
                    self.wrap_width as usize,
                ));
                if let Some(cache_slot) = self.wrapped_cache.get_mut(idx) {
                    *cache_slot = Some(Arc::clone(&wrapped));
                }
                wrapped
            };

            // Render each wrapped line
            for line in wrapped.iter() {
                if current_wrapped_index >= start_wrapped_line
                    && current_wrapped_index < end_wrapped_line
                {
                    let y = area.y.saturating_add(screen_y);

                    // Bounds check for buffer access
                    if y >= area.y + area.height || y >= buf.area().height {
                        return;
                    }

                    let mut x = area.x;
                    for span in &line.spans {
                        for ch in span.content.chars() {
                            // Bounds check before buffer access
                            if x >= area.x + area.width || x >= buf.area().width {
                                break;
                            }

                            // Safe buffer access with bounds check
                            if let Some(cell) = buf.cell_mut((x, y)) {
                                cell.set_char(ch);
                                cell.set_style(paragraph_style.patch(span.style));
                            }
                            x = x.saturating_add(1);
                        }
                    }

                    screen_y = screen_y.saturating_add(1);
                    if screen_y >= area.height {
                        return;
                    }
                }

                current_wrapped_index += 1;
                if current_wrapped_index >= end_wrapped_line {
                    return;
                }
            }
        }
    }

    fn matches(
        &self,
        value: &Value,
        kind: TextContentKind,
        width: u16,
        paragraph_style: Style,
    ) -> bool {
        self.source_ptr == value.data.as_ptr() as usize
            && self.source_len == value.data.len()
            && self.wrap_width == width.max(1)
            && self.kind == kind
            && self.paragraph_style == paragraph_style
    }
}

pub struct ValueViewer {
    pub table_state: TableState,
    pub scroll_offset: u16,
    pub total_rows: usize,
    pub viewport_height: u16,
    pub scrollbar_state: ScrollbarState,
    text_cache: Option<TextCache>,
}

impl ValueViewer {
    pub fn new() -> Self {
        Self {
            table_state: TableState::default(),
            scroll_offset: 0,
            total_rows: 0,
            viewport_height: 0,
            scrollbar_state: ScrollbarState::default(),
            text_cache: None,
        }
    }

    pub fn scroll_down(&mut self) {
        // Early return if there's nothing to scroll
        if self.total_rows == 0 || self.viewport_height == 0 {
            return;
        }

        if self.table_state.selected().is_some() {
            let i = self.table_state.selected().unwrap_or(0);
            if i < self.total_rows.saturating_sub(1) {
                self.table_state.select(Some(i.saturating_add(1)));
            }
        } else {
            // Safe calculation with proper bounds checking to prevent overflow
            let max_scroll = self
                .total_rows
                .saturating_sub(self.viewport_height as usize)
                .min(u16::MAX as usize) as u16;

            if self.scroll_offset < max_scroll {
                self.scroll_offset = self.scroll_offset.saturating_add(1);
            }
        }
    }

    pub fn scroll_up(&mut self) {
        // Early return if there's nothing to scroll
        if self.total_rows == 0 || self.viewport_height == 0 {
            return;
        }

        if self.table_state.selected().is_some() {
            let i = self.table_state.selected().unwrap_or(0);
            self.table_state.select(Some(i.saturating_sub(1)));
        } else {
            self.scroll_offset = self.scroll_offset.saturating_sub(1);
        }
    }

    /// Scroll by a delta amount (positive = down, negative = up)
    /// Optimized for fast scrolling - minimal arithmetic
    #[tracing::instrument(skip(self), level = "trace")]
    pub fn scroll_by(&mut self, delta: isize) {
        if delta == 0 {
            trace!("No-op scroll request");
            return;
        }

        // Early return if there's nothing to scroll
        if self.total_rows == 0 || self.viewport_height == 0 {
            trace!(
                total_rows = self.total_rows,
                viewport_height = self.viewport_height,
                "No rows/viewport height available; ignoring scroll"
            );
            return;
        }

        if self.table_state.selected().is_some() {
            let i = self.table_state.selected().unwrap_or(0);
            let max_index = self.total_rows.saturating_sub(1);

            // Early return if already at boundary and trying to scroll further
            if delta > 0 && i >= max_index {
                trace!(index = i, max_index, "Already at bottom; ignoring scroll down");
                return;
            }
            if delta < 0 && i == 0 {
                trace!(index = i, "Already at top; ignoring scroll up");
                return;
            }

            if delta > 0 {
                let new_i = i
                    .saturating_add(delta as usize)
                    .min(max_index);
                trace!(old = i, new = new_i, "Scrolling table selection down");
                self.table_state.select(Some(new_i));
            } else {
                let new_i = i.saturating_sub((-delta) as usize);
                trace!(old = i, new = new_i, "Scrolling table selection up");
                self.table_state.select(Some(new_i));
            }
        } else {
            // Fast path: simple arithmetic, no clamping overhead
            let max_scroll = self
                .total_rows
                .saturating_sub(self.viewport_height as usize);

            // Early return if already at boundary and trying to scroll further
            if delta > 0 && self.scroll_offset >= max_scroll as u16 {
                trace!(
                    scroll_offset = self.scroll_offset,
                    max_scroll,
                    "Already at bottom; ignoring scroll down"
                );
                return;
            }
            if delta < 0 && self.scroll_offset == 0 {
                trace!(
                    scroll_offset = self.scroll_offset,
                    "Already at top; ignoring scroll up"
                );
                return;
            }

            // Fast path for typical scroll amounts (avoid 64-bit conversions)
            let new_offset = if delta > 0 {
                if delta < i16::MAX as isize {
                    // Fast: common case, small scroll
                    self.scroll_offset.saturating_add(delta as u16)
                } else {
                    // Rare: huge scroll, saturate to max
                    max_scroll as u16
                }
            } else {
                if delta > i16::MIN as isize {
                    // Fast: common case, small scroll
                    self.scroll_offset.saturating_sub((-delta) as u16)
                } else {
                    // Rare: huge scroll, clamp to 0
                    0
                }
            };

            // Clamp to valid range
            self.scroll_offset = new_offset.min(max_scroll as u16);
            trace!(
                scroll_offset = self.scroll_offset,
                max_scroll, delta, "Updated value viewer scroll offset"
            );
        }
    }

    pub fn reset_scroll(&mut self) {
        self.scroll_offset = 0;
        self.table_state.select(None);
        self.scrollbar_state = ScrollbarState::default();
    }

    /// Check if we're at a scroll boundary (top or bottom)
    /// Returns Some(true) if at bottom, Some(false) if at top, None if not at boundary
    pub fn is_at_boundary(&self, direction: isize) -> Option<bool> {
        if self.total_rows == 0 || self.viewport_height == 0 {
            return None;
        }

        if self.table_state.selected().is_some() {
            let i = self.table_state.selected().unwrap_or(0);
            let max_index = self.total_rows.saturating_sub(1);
            if direction > 0 && i >= max_index {
                return Some(true); // At bottom
            }
            if direction < 0 && i == 0 {
                return Some(false); // At top
            }
        } else {
            let max_scroll = self
                .total_rows
                .saturating_sub(self.viewport_height as usize);
            if direction > 0 && self.scroll_offset >= max_scroll as u16 {
                return Some(true); // At bottom
            }
            if direction < 0 && self.scroll_offset == 0 {
                return Some(false); // At top
            }
        }
        None // Not at boundary
    }

    fn clear_text_cache(&mut self) {
        self.text_cache = None;
    }

    fn viewer_block(is_active: bool, title: impl Into<String>) -> Block<'static> {
        let border_style = if is_active {
            Style::default().fg(Color::Cyan)
        } else {
            Style::default().fg(Color::DarkGray)
        };

        Block::default()
            .title(Line::from(title.into()))
            .title_alignment(Alignment::Left)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(border_style)
    }

    fn render_scrollbar_for_offset(&mut self, f: &mut Frame, area: Rect) {
        if self.total_rows <= self.viewport_height as usize {
            return;
        }

        let max_scroll = self.total_rows.saturating_sub(self.viewport_height as usize);
        let clamped_offset = self.scroll_offset.min(max_scroll as u16) as usize;

        let scrollbar_position = if max_scroll > 0 {
            let progress = clamped_offset as f64 / max_scroll as f64;
            (progress * (self.total_rows - 1) as f64) as usize
        } else {
            0
        };

        trace!(
            scroll_offset = self.scroll_offset,
            total_rows = self.total_rows,
            viewport_height = self.viewport_height,
            max_scroll,
            clamped_offset,
            scrollbar_position,
            "Rendering scrollbar for offset (wrapped lines)"
        );

        self.scrollbar_state = self
            .scrollbar_state
            .content_length(self.total_rows)
            .viewport_content_length(self.viewport_height as usize)
            .position(scrollbar_position);

        f.render_stateful_widget(
            Scrollbar::default()
                .orientation(ScrollbarOrientation::VerticalRight)
                .begin_symbol(Some("â–²"))
                .end_symbol(Some("â–¼")),
            area,
            &mut self.scrollbar_state,
        );
    }

    fn render_paragraph(
        &mut self,
        f: &mut Frame,
        area: Rect,
        is_active: bool,
        title: &str,
        lines: Vec<Line<'static>>,
        style: Style,
    ) {
        let block = Self::viewer_block(is_active, title);
        let inner = block.inner(area);

        // Update dimensions for scroll handling
        self.viewport_height = inner.height;
        let width = inner.width.max(1) as usize;

        if width > 0 {
            self.total_rows = lines
                .iter()
                .map(|line| {
                    let line_width = line.width();
                    if line_width == 0 {
                        1
                    } else {
                        line_width.div_ceil(width)
                    }
                })
                .sum();
        } else {
            self.total_rows = lines.len();
        }

        let widget = Paragraph::new(lines)
            .style(style)
            .block(block)
            .wrap(Wrap { trim: false })
            .scroll((self.scroll_offset, 0));

        f.render_widget(widget, area);

        self.render_scrollbar_for_offset(f, area);
    }

    fn render_plain_value(
        &mut self,
        f: &mut Frame,
        area: Rect,
        is_active: bool,
        title: &str,
        value: &Value,
        props: &ValueViewerProps<'_>,
    ) {
        let (text, paragraph_style) = ValueViewer::format_plain_text(value, props);
        self.render_text_value(
            f,
            area,
            is_active,
            title,
            value,
            TextContentKind::Plain,
            paragraph_style,
            move || ValueViewer::plain_text_to_lines(&text),
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn render_text_value<F>(
        &mut self,
        f: &mut Frame,
        area: Rect,
        is_active: bool,
        title: &str,
        value: &Value,
        kind: TextContentKind,
        paragraph_style: Style,
        lines_builder: F,
    ) where
        F: FnOnce() -> Vec<Line<'static>>,
    {
        let block = Self::viewer_block(is_active, title);
        let inner = block.inner(area);
        let content_width = inner.width.max(1);

        self.viewport_height = inner.height;
        self.ensure_text_cache(value, kind, content_width, paragraph_style, lines_builder);

        let Some(cache_mut) = self.text_cache.as_mut() else {
            return;
        };

        self.total_rows = cache_mut.total_wrapped_lines.max(1);

        // Only wrap visible lines (lazy wrapping)
        // This avoids cloning/wrapping thousands of lines
        let viewport_height = self.viewport_height as usize;
        let scroll_offset =
            self.scroll_offset
                .min(cache_mut.total_wrapped_lines.saturating_sub(1) as u16) as usize;

        // Calculate exact visible range - no buffer needed since we're not using .scroll()
        let start_wrapped_line = scroll_offset;
        let end_wrapped_line = (scroll_offset + viewport_height).min(cache_mut.total_wrapped_lines);

        // Get style before borrow
        let paragraph_style = cache_mut.paragraph_style;

        // Render block first
        let inner = block.inner(area);
        f.render_widget(block, area);

        // CRITICAL: Render directly from cache without intermediate Vec
        // This avoids cloning lines on every frame
        let buf = f.buffer_mut();
        cache_mut.render_visible_lines(
            buf,
            start_wrapped_line,
            end_wrapped_line,
            inner,
            paragraph_style,
        );

        self.render_scrollbar_for_offset(f, area);
    }

    fn ensure_text_cache<F>(
        &mut self,
        value: &Value,
        kind: TextContentKind,
        content_width: u16,
        paragraph_style: Style,
        lines_builder: F,
    ) where
        F: FnOnce() -> Vec<Line<'static>>,
    {
        let needs_rebuild = self
            .text_cache
            .as_ref()
            .map(|cache| !cache.matches(value, kind, content_width, paragraph_style))
            .unwrap_or(true);

        if needs_rebuild {
            let lines = lines_builder();
            self.text_cache = Some(TextCache::new(
                value,
                kind,
                paragraph_style,
                lines,
                content_width,
            ));
        }
    }

    fn try_render_json_value(
        &mut self,
        f: &mut Frame,
        area: Rect,
        is_active: bool,
        title: &str,
        value: &Value,
        props: &ValueViewerProps<'_>,
    ) -> bool {
        if !props.json_formatter.can_format(value) {
            return false;
        }

        match props.json_formatter.format_to_lines(value) {
            Ok(lines) => {
                self.render_text_value(
                    f,
                    area,
                    is_active,
                    title,
                    value,
                    TextContentKind::Json,
                    Style::default(),
                    move || lines,
                );
                true
            }
            Err(_) => {
                self.clear_text_cache();
                false
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn render_table(
        &mut self,
        f: &mut Frame,
        area: Rect,
        is_active: bool,
        base_title: &str,
        headers: Vec<&str>,
        rows_data: Vec<Vec<String>>,
        json_formatter: &JsonFormatter,
    ) {
        // Update total rows and viewport for scroll handling
        self.total_rows = rows_data.len();
        self.viewport_height = area.height.saturating_sub(2);

        let header_style = Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD);

        let entry_count = rows_data.len();
        let table_title = if entry_count == 1 {
            format!("{base_title} | 1 item")
        } else {
            format!("{base_title} | {} items", entry_count)
        };

        // Calculate widths
        let mut constraints = Vec::new();
        if headers.len() == 2 {
            // Key-Value style (Hash, ZSet)
            let key_width = rows_data
                .iter()
                .map(|row| row.first().map(|s| s.chars().count()).unwrap_or(0))
                .max()
                .unwrap_or(6)
                .clamp(8, 40) as u16;
            constraints.push(Constraint::Length(key_width));
            constraints.push(Constraint::Min(10));
        } else {
            // List/Set style (Single value)
            constraints.push(Constraint::Percentage(100));
        }

        let rows: Vec<Row> = rows_data
            .into_iter()
            .enumerate()
            .map(|(idx, cols)| {
                // Pre-calculate cell content to determine height correctly
                let mut formatted_cells = Vec::with_capacity(cols.len());
                for (i, c) in cols.iter().enumerate() {
                    let is_value_column = if headers.is_empty() {
                        true
                    } else {
                        i == headers.len() - 1
                    };

                    if is_value_column
                        && let Ok(json) = serde_json::from_str::<JsonValue>(c)
                        && let Ok(pretty) = serde_json::to_string_pretty(&json)
                    {
                        let colored_lines = json_formatter.colorize_json(&pretty);
                        formatted_cells.push(colored_lines);
                        continue;
                    }
                    formatted_cells.push(vec![Line::from(c.clone())]);
                }

                let height = formatted_cells
                    .iter()
                    .map(|lines| lines.len())
                    .max()
                    .unwrap_or(1) as u16;

                let cells: Vec<Cell> = formatted_cells
                    .into_iter()
                    .enumerate()
                    .map(|(i, lines)| {
                        let style = if i == 0 && headers.len() == 2 {
                            Style::default().fg(Color::Yellow)
                        } else {
                            Style::default()
                        };
                        Cell::from(lines).style(style)
                    })
                    .collect();

                // Alternate row colors, but don't highlight unless active
                let row_style = if idx % 2 == 0 {
                    Style::default()
                } else {
                    Style::default().bg(Color::Rgb(20, 20, 20))
                };

                Row::new(cells).style(row_style).height(height)
            })
            .collect();

        // Ensure we have a selection if we have data
        if !rows.is_empty() && self.table_state.selected().is_none() {
            self.table_state.select(Some(0));
        }
        // Ensure selection is valid
        if let Some(selected) = self.table_state.selected()
            && selected >= rows.len()
        {
            self.table_state.select(Some(rows.len().saturating_sub(1)));
        }

        let highlight_style = if is_active {
            Style::default()
                .bg(Color::Rgb(60, 60, 60))
                .fg(Color::White)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        let mut table = Table::new(rows, constraints)
            .column_spacing(2)
            .highlight_style(highlight_style)
            .block(Self::viewer_block(is_active, table_title));

        if !headers.is_empty() {
            let header_cells: Vec<Cell> = headers
                .iter()
                .map(|h| Cell::from(*h).style(header_style))
                .collect();
            table = table.header(Row::new(header_cells).bottom_margin(0));
        }

        f.render_stateful_widget(table, area, &mut self.table_state);

        if self.total_rows > self.viewport_height as usize {
            if let Some(selected) = self.table_state.selected() {
                self.scrollbar_state = self
                    .scrollbar_state
                    .content_length(self.total_rows)
                    .viewport_content_length(self.viewport_height as usize)
                    .position(selected);
            } else {
                self.scrollbar_state = self
                    .scrollbar_state
                    .content_length(self.total_rows)
                    .viewport_content_length(self.viewport_height as usize)
                    .position(0);
            }

            f.render_stateful_widget(
                Scrollbar::default()
                    .orientation(ScrollbarOrientation::VerticalRight)
                    .begin_symbol(Some("â–²"))
                    .end_symbol(Some("â–¼")),
                area,
                &mut self.scrollbar_state,
            );
        }
    }

    fn format_plain_text(value: &Value, props: &ValueViewerProps<'_>) -> (String, Style) {
        match props.text_formatter.format(value) {
            Ok(text) => (text, Style::default()),
            Err(_) => (
                "<formatting error>".to_string(),
                Style::default().fg(Color::Red),
            ),
        }
    }

    fn plain_text_to_lines(text: &str) -> Vec<Line<'static>> {
        if text.is_empty() {
            return vec![Line::from(String::new())];
        }

        text.split('\n')
            .map(|segment| Line::from(segment.to_string()))
            .collect()
    }

    fn wrap_single_line(line: &Line<'static>, width: usize) -> Vec<Line<'static>> {
        if width == 0 {
            return vec![Line::from(String::new())];
        }

        let mut result = Vec::new();
        let mut current_spans: Vec<Span<'static>> = Vec::new();
        let mut current_width = 0usize;
        let mut had_content = false;

        for span in &line.spans {
            if span.content.is_empty() {
                continue;
            }

            had_content = true;
            let content = span.content.clone().into_owned();
            let mut start = 0usize;

            while start < content.len() {
                if current_width >= width {
                    result.push(Self::line_from_spans(
                        std::mem::take(&mut current_spans),
                        line.alignment,
                    ));
                    current_width = 0;
                }

                let available = width.saturating_sub(current_width).max(1);
                let (advance, consumed_width) = Self::split_at_width(&content[start..], available);
                if advance == 0 {
                    break;
                }

                // Check for overflow: if char is wider than available and we have content, wrap first!
                if consumed_width > available && current_width > 0 {
                    result.push(Self::line_from_spans(
                        std::mem::take(&mut current_spans),
                        line.alignment,
                    ));
                    current_width = 0;
                    // Don't advance start, retry loop iteration on new line
                    continue;
                }

                let end = start + advance;
                let slice = content[start..end].to_string();
                if !slice.is_empty() {
                    current_spans.push(Span::styled(slice, span.style));
                    current_width += consumed_width;
                }
                start = end;
            }
        }

        if !current_spans.is_empty() {
            result.push(Self::line_from_spans(
                std::mem::take(&mut current_spans),
                line.alignment,
            ));
        } else if !had_content {
            result.push(Self::line_from_spans(Vec::new(), line.alignment));
        }

        result
    }

    fn count_wrapped_lines(line: &Line<'static>, width: usize) -> usize {
        if width == 0 {
            return 1;
        }

        let mut lines = 0;
        let mut current_width = 0usize;
        let mut had_content = false;
        let mut has_pending_spans = false;

        for span in &line.spans {
            if span.content.is_empty() {
                continue;
            }

            had_content = true;
            let content = &span.content;
            let mut start = 0usize;

            while start < content.len() {
                if current_width >= width {
                    lines += 1;
                    current_width = 0;
                    has_pending_spans = false;
                }

                let available = width.saturating_sub(current_width).max(1);
                let (advance, consumed_width) = Self::split_at_width(&content[start..], available);
                if advance == 0 {
                    break;
                }

                // Check for overflow matching wrap_single_line
                if consumed_width > available && current_width > 0 {
                    lines += 1;
                    current_width = 0;
                    has_pending_spans = false;
                    continue;
                }

                current_width += consumed_width;
                has_pending_spans = true;
                start += advance;
            }
        }

        if has_pending_spans {
            lines += 1;
        } else if !had_content {
            lines += 1;
        }

        lines
    }

    fn line_from_spans(spans: Vec<Span<'static>>, alignment: Option<Alignment>) -> Line<'static> {
        Line {
            spans,
            style: Style::default(),
            alignment,
        }
    }

    fn split_at_width(text: &str, max_width: usize) -> (usize, usize) {
        if text.is_empty() {
            return (0, 0);
        }

        let mut consumed_width = 0usize;
        let mut last_index = 0usize;

        for (idx, ch) in text.char_indices() {
            let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
            if consumed_width + ch_width > max_width && consumed_width != 0 {
                break;
            }

            consumed_width += ch_width;
            last_index = idx + ch.len_utf8();

            if consumed_width >= max_width {
                break;
            }
        }

        if last_index == 0 {
            if let Some(ch) = text.chars().next() {
                (ch.len_utf8(), UnicodeWidthChar::width(ch).unwrap_or(0))
            } else {
                (0, 0)
            }
        } else {
            (last_index, consumed_width)
        }
    }

    fn parse_json_data(value: &Value) -> Result<JsonValue, String> {
        let json_str = String::from_utf8(value.data.clone())
            .map_err(|_| "Invalid UTF-8 in value".to_string())?;
        serde_json::from_str(&json_str).map_err(|e| format!("Invalid payload: {e}"))
    }

    fn parse_hash_entries(value: &Value) -> Result<Vec<Vec<String>>, String> {
        let parsed = Self::parse_json_data(value)?;
        let obj = parsed
            .as_object()
            .ok_or_else(|| "Hash value is not an object".to_string())?;

        let mut entries: Vec<Vec<String>> = obj
            .iter()
            .map(|(field, value)| vec![field.clone(), Self::json_value_to_string(value)])
            .collect();

        entries.sort_by(|a, b| a[0].cmp(&b[0]));
        Ok(entries)
    }

    fn parse_list_entries(value: &Value) -> Result<Vec<Vec<String>>, String> {
        let parsed = Self::parse_json_data(value)?;
        let arr = parsed
            .as_array()
            .ok_or_else(|| "List value is not an array".to_string())?;

        let entries: Vec<Vec<String>> = arr
            .iter()
            .enumerate()
            .map(|(i, value)| vec![format!("{}", i + 1), Self::json_value_to_string(value)])
            .collect();
        Ok(entries)
    }

    fn parse_set_entries(value: &Value) -> Result<Vec<Vec<String>>, String> {
        let parsed = Self::parse_json_data(value)?;
        let arr = parsed
            .as_array()
            .ok_or_else(|| "Set value is not an array".to_string())?;

        let mut entries: Vec<Vec<String>> = arr
            .iter()
            .map(|value| vec![Self::json_value_to_string(value)])
            .collect();
        entries.sort_by(|a, b| a[0].cmp(&b[0]));
        Ok(entries)
    }

    fn parse_zset_entries(value: &Value) -> Result<Vec<Vec<String>>, String> {
        let parsed = Self::parse_json_data(value)?;
        let arr = parsed
            .as_array()
            .ok_or_else(|| "Sorted Set value is not an array".to_string())?;

        // ZSET is array of [member, score] tuples in JSON from backend
        let entries: Vec<Vec<String>> = arr
            .iter()
            .map(|item| {
                if let Some(tuple) = item.as_array()
                    && tuple.len() >= 2
                {
                    let member = Self::json_value_to_string(&tuple[0]);
                    let score = Self::json_value_to_string(&tuple[1]);
                    return vec![score, member]; // Score first for ZSet display usually? Or Member? Let's do Score | Member
                }
                vec!["?".to_string(), Self::json_value_to_string(item)]
            })
            .collect();

        Ok(entries)
    }

    fn json_value_to_string(value: &JsonValue) -> String {
        match value {
            JsonValue::String(s) => s.clone(),
            JsonValue::Number(n) => n.to_string(),
            JsonValue::Bool(b) => b.to_string(),
            JsonValue::Null => "null".to_string(),
            JsonValue::Array(_) | JsonValue::Object(_) => {
                // Keep complex objects as JSON string so we can pretty print them in the cell
                value.to_string()
            }
        }
    }

    fn title_for(value_type: Option<ValueType>) -> String {
        match value_type {
            Some(t) => format!("Value Viewer | {}", t),
            None => "Value Viewer".to_string(),
        }
    }
}

impl Default for ValueViewer {
    fn default() -> Self {
        Self::new()
    }
}

impl Component for ValueViewer {
    type Props<'a> = ValueViewerProps<'a>;
    type Msg = Action;

    fn render(&mut self, f: &mut Frame, area: Rect, props: Self::Props<'_>) {
        let base_title = ValueViewer::title_for(props.selected_key_type);

        if let Some(err) = props.error_message {
            self.clear_text_cache();
            self.render_paragraph(
                f,
                area,
                props.is_active,
                &base_title,
                vec![Line::from(format!("Error: {}", err))],
                Style::default().fg(Color::Red),
            );
            return;
        }

        if let Some(value) = props.selected_value {
            match props.selected_key_type {
                Some(ValueType::Hash) => {
                    self.clear_text_cache();
                    match ValueViewer::parse_hash_entries(value) {
                        Ok(rows) => {
                            self.render_table(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec!["Field", "Value"],
                                rows,
                                props.json_formatter,
                            );
                            return;
                        }
                        Err(e) => {
                            self.render_paragraph(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec![Line::from(format!("Parse error: {}", e))],
                                Style::default().fg(Color::Red),
                            );
                            return;
                        }
                    }
                }
                Some(ValueType::List) => {
                    self.clear_text_cache();
                    match ValueViewer::parse_list_entries(value) {
                        Ok(rows) => {
                            self.render_table(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec!["Index", "Value"],
                                rows,
                                props.json_formatter,
                            );
                            return;
                        }
                        Err(e) => {
                            self.render_paragraph(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec![Line::from(format!("Parse error: {}", e))],
                                Style::default().fg(Color::Red),
                            );
                            return;
                        }
                    }
                }
                Some(ValueType::Set) => {
                    self.clear_text_cache();
                    match ValueViewer::parse_set_entries(value) {
                        Ok(rows) => {
                            self.render_table(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec![],
                                rows,
                                props.json_formatter,
                            );
                            return;
                        }
                        Err(e) => {
                            self.render_paragraph(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec![Line::from(format!("Parse error: {}", e))],
                                Style::default().fg(Color::Red),
                            );
                            return;
                        }
                    }
                }
                Some(ValueType::SortedSet) => {
                    self.clear_text_cache();
                    match ValueViewer::parse_zset_entries(value) {
                        Ok(rows) => {
                            self.render_table(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec!["Score", "Member"],
                                rows,
                                props.json_formatter,
                            );
                            return;
                        }
                        Err(e) => {
                            self.render_paragraph(
                                f,
                                area,
                                props.is_active,
                                &base_title,
                                vec![Line::from(format!("Parse error: {}", e))],
                                Style::default().fg(Color::Red),
                            );
                            return;
                        }
                    }
                }
                _ => {
                    // Reset table state when viewing non-table data
                    self.table_state.select(None);

                    if self.try_render_json_value(
                        f,
                        area,
                        props.is_active,
                        &base_title,
                        value,
                        &props,
                    ) {
                        return;
                    }

                    self.render_plain_value(f, area, props.is_active, &base_title, value, &props);
                    return;
                }
            }
        }

        self.clear_text_cache();
        self.render_paragraph(
            f,
            area,
            props.is_active,
            &base_title,
            vec![Line::from("Select a key to view its value")],
            Style::default().fg(Color::DarkGray),
        );
    }

    fn handle_input(&mut self, _key: KeyEvent, _props: Self::Props<'_>) -> Option<Self::Msg> {
        None
    }
}