grafatui 0.1.5

A Grafana-like TUI for Prometheus
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
/*
 * Copyright 2025 Federico D'Ambrosio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::prom;
use crate::theme::Theme;
use crate::ui;
use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyModifiers};
use futures::StreamExt;
use ratatui::{Terminal, style::Color};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::time::sleep;

/// Represents the state of a single dashboard panel.
#[derive(Debug, Clone)]
pub struct PanelState {
    /// Panel title.
    pub title: String,
    /// PromQL expressions to query.
    pub exprs: Vec<String>,
    /// Optional legend formats (e.g. "{{instance}}"). Parallel to exprs.
    pub legends: Vec<Option<String>>,
    /// Current time-series data for this panel.
    pub series: Vec<SeriesView>,
    /// Last error message, if any.
    pub last_error: Option<String>,
    /// Last query URL used (for debugging).
    pub last_url: Option<String>,
    /// Total number of samples in the current view.
    pub last_samples: usize,
    /// Grid layout position (if imported from Grafana).
    pub grid: Option<GridUnit>,
    /// Y-axis scaling mode.
    pub y_axis_mode: YAxisMode,
    /// Visualization type.
    pub panel_type: PanelType,
    /// Threshold configuration.
    pub thresholds: Option<Thresholds>,
    /// Optional minimum value for gauge and thresholds.
    pub min: Option<f64>,
    /// Optional maximum value for gauge and thresholds.
    pub max: Option<f64>,
}

/// Visualization types supported by Grafatui.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PanelType {
    Graph,
    Gauge,
    BarGauge,
    Table,
    Stat,
    Heatmap,
    Unknown,
}

/// Modes for Y-axis scaling.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum YAxisMode {
    /// Auto-scale based on min/max of data.
    Auto,
    /// Always include zero.
    ZeroBased,
}

/// Represents a single time-series line in a chart.
#[derive(Debug, Clone)]
pub struct SeriesView {
    /// Stable name of the series (used for coloring).
    pub name: String,
    /// Latest value of the series (used for display).
    pub value: Option<f64>,
    /// Data points (timestamp, value).
    pub points: Vec<(f64, f64)>,
    /// Whether the series is visible in the chart.
    pub visible: bool,
}

/// Grid positioning unit (Grafana style).
#[derive(Debug, Clone, Copy)]
pub struct GridUnit {
    pub x: i32,
    pub y: i32,
    pub w: i32,
    pub h: i32,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ThresholdMode {
    Absolute,
    Percentage,
}

#[derive(Debug, Clone)]
pub struct ThresholdStep {
    pub value: Option<f64>,
    pub color: Color,
}

#[derive(Debug, Clone)]
pub struct Thresholds {
    pub mode: ThresholdMode,
    pub steps: Vec<ThresholdStep>,
    pub style: Option<String>,
}

impl PanelState {
    pub fn get_color_for_value(&self, val: f64) -> Option<Color> {
        let thresholds = self.thresholds.as_ref()?;

        let mut matched_color = None;

        match thresholds.mode {
            ThresholdMode::Absolute => {
                for step in &thresholds.steps {
                    if let Some(step_val) = step.value {
                        if val >= step_val {
                            matched_color = Some(step.color);
                        }
                    } else {
                        // Null value represents the base step (lowest possible)
                        if matched_color.is_none() {
                            matched_color = Some(step.color);
                        }
                    }
                }
            }
            ThresholdMode::Percentage => {
                let min = self.min.unwrap_or(0.0);
                let max = self.max.unwrap_or(100.0);
                let range = max - min;

                let pct = if range > 0.0 {
                    (val - min) / range * 100.0
                } else {
                    0.0
                };

                for step in &thresholds.steps {
                    if let Some(step_val) = step.value {
                        if pct >= step_val {
                            matched_color = Some(step.color);
                        }
                    } else {
                        if matched_color.is_none() {
                            matched_color = Some(step.color);
                        }
                    }
                }
            }
        }
        matched_color
    }
}

/// Application mode.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AppMode {
    Normal,
    Search,
    Fullscreen,
    Inspect,
    FullscreenInspect,
}

/// Global application state.
#[derive(Debug)]
pub struct AppState {
    /// Prometheus client for making requests.
    pub prometheus: prom::PromClient,
    /// Current time range window.
    pub range: Duration,
    /// Query step resolution.
    pub step: Duration,
    /// How often to refresh data.
    pub refresh_every: Duration,
    /// List of panels.
    pub panels: Vec<PanelState>,
    /// Timestamp of the last successful refresh.
    pub last_refresh: Instant,
    /// Vertical scroll offset.
    pub vertical_scroll: usize,
    /// Dashboard title.
    pub title: String,
    /// Whether to show the debug bar.
    pub debug_bar: bool,
    /// Template variables (key -> value).
    pub vars: HashMap<String, String>,
    /// Count of panels skipped during import.
    pub skipped_panels: usize,
    /// Index of the currently selected panel.
    pub selected_panel: usize,
    /// UI Theme.
    pub theme: Theme,
    /// Time offset from "now" for panning backward in time (0 = live mode).
    pub time_offset: Duration,
    /// Current application mode.
    pub mode: AppMode,
    /// Search query string.
    pub search_query: String,
    /// Filtered panel indices based on search query.
    pub search_results: Vec<usize>,
    /// Cursor X position (timestamp) for inspection.
    pub cursor_x: Option<f64>,
    /// Global marker set for rendering thresholds
    pub threshold_marker: String,
}

impl AppState {
    /// Creates a new application state.
    ///
    /// # Arguments
    ///
    /// * `prometheus` - The Prometheus client.
    /// * `range` - The initial time range window.
    /// * `step` - The query resolution step.
    /// * `refresh_every` - The data refresh interval.
    /// * `title` - The dashboard title.
    /// * `panels` - The list of panels to display.
    /// * `skipped_panels` - The count of panels that were skipped during import.
    /// * `theme` - The UI theme to use.
    pub fn new(
        prometheus: prom::PromClient,
        range: Duration,
        step: Duration,
        refresh_every: Duration,
        title: String,
        panels: Vec<PanelState>,
        skipped_panels: usize,
        theme: Theme,
        threshold_marker: String,
    ) -> Self {
        Self {
            prometheus,
            range,
            step,
            refresh_every,
            panels,
            last_refresh: Instant::now() - refresh_every,
            vertical_scroll: 0,
            title,
            debug_bar: false,
            vars: HashMap::new(),
            skipped_panels,
            selected_panel: 0,
            theme,
            time_offset: Duration::from_secs(0),
            mode: AppMode::Normal,
            search_query: String::new(),
            search_results: Vec::new(),
            cursor_x: None,
            threshold_marker,
        }
    }

    /// Zoom in: halve the time range.
    pub fn zoom_in(&mut self) {
        self.range = self.range / 2;
        if self.range < Duration::from_secs(10) {
            self.range = Duration::from_secs(10);
        }
    }

    /// Zoom out: double the time range.
    pub fn zoom_out(&mut self) {
        self.range = self.range * 2;
        self.range = self.range.min(Duration::from_secs(7 * 24 * 3600));
    }

    /// Pan left: shift the time window backward.
    pub fn pan_left(&mut self) {
        // Shift by 25% of the current range
        let shift = self.range / 4;
        self.time_offset = self.time_offset.saturating_add(shift);
    }

    /// Automatically scroll to ensure the selected panel is visible.
    pub fn scroll_to_selected_panel(&mut self) {
        if let Some(panel) = self.panels.get(self.selected_panel) {
            if let Some(grid) = panel.grid {
                let py = grid.y;
                let ph = grid.h;
                let scroll_y = self.vertical_scroll as i32;
                let visible_height = 20;

                if py < scroll_y {
                    self.vertical_scroll = py as usize;
                } else if py + ph > scroll_y + visible_height {
                    self.vertical_scroll = (py + ph - visible_height).max(0) as usize;
                }
            }
        }
    }

    /// Pan right: shift the time window forward (toward "now").
    pub fn pan_right(&mut self) {
        // Shift by 25% of the current range
        let shift = self.range / 4;
        if self.time_offset > shift {
            self.time_offset = self.time_offset.saturating_sub(shift);
        } else {
            self.time_offset = Duration::from_secs(0); // Back to live mode
        }
    }

    /// Reset to live mode (time_offset = 0).
    pub fn reset_to_live(&mut self) {
        self.time_offset = Duration::from_secs(0);
    }

    /// Check if currently in live mode.
    pub fn is_live(&self) -> bool {
        self.time_offset.as_secs() == 0
    }

    /// Move cursor left/right by one step.
    pub fn move_cursor(&mut self, direction: i32) {
        let end_ts = (chrono::Utc::now().timestamp() - self.time_offset.as_secs() as i64) as f64;
        let start_ts = end_ts - self.range.as_secs_f64();

        if let Some(current_x) = self.cursor_x {
            let step_secs = self.step.as_secs_f64();
            let new_x = current_x + (direction as f64 * step_secs);
            self.cursor_x = Some(new_x.max(start_ts).min(end_ts));
        } else {
            self.cursor_x = Some((start_ts + end_ts) / 2.0);
        }
    }

    pub async fn refresh(&mut self) -> Result<()> {
        let prometheus = &self.prometheus;
        let range = self.range;
        let step = self.step;
        let vars = &self.vars;

        // Calculate end timestamp: "now" minus time_offset
        let end_ts = chrono::Utc::now().timestamp() - self.time_offset.as_secs() as i64;

        // Create a stream of futures for fetching panel data
        let mut futures = futures::stream::iter(self.panels.iter_mut())
            .map(|p| Self::fetch_single_panel_data(prometheus, p, range, step, vars, end_ts))
            .buffer_unordered(4); // Max 4 concurrent panel refreshes

        while let Some((p, results, url, err)) = futures.next().await {
            p.series = results;
            p.last_samples = p.series.iter().map(|s| s.points.len()).sum();
            if let Some(u) = url {
                p.last_url = Some(u);
            }
            p.last_error = err;
        }

        self.last_refresh = Instant::now();
        Ok(())
    }

    async fn fetch_single_panel_data<'a>(
        prometheus: &'a prom::PromClient,
        p: &'a mut PanelState,
        range: Duration,
        step: Duration,
        vars: &'a HashMap<String, String>,
        end_ts: i64,
    ) -> (
        &'a mut PanelState,
        Vec<SeriesView>,
        Option<String>,
        Option<String>,
    ) {
        let mut panel_results = Vec::new();
        let mut last_url = None;
        let mut error = None;

        for (i, expr) in p.exprs.iter().enumerate() {
            let expr_expanded = expand_expr(expr, step, vars);
            let legend_fmt = p.legends.get(i).and_then(|x| x.as_ref());

            // Calculate start/end for URL display purposes
            let start_ts = end_ts - (range.as_secs() as i64);

            let url = prometheus.build_query_range_url(&expr_expanded, start_ts, end_ts, step);
            last_url = Some(url);

            match prometheus
                .query_range(&expr_expanded, start_ts, end_ts, step)
                .await
            {
                Ok(res) => {
                    for s in res {
                        let latest_val = s.values.last().and_then(|(_, v)| v.parse::<f64>().ok());
                        let legend_base = if let Some(fmt) = legend_fmt {
                            format_legend(fmt, &s.metric)
                        } else if s.metric.is_empty() {
                            expr_expanded.clone()
                        } else {
                            let mut labels: Vec<_> = s
                                .metric
                                .iter()
                                .map(|(k, v)| format!("{}=\"{}\"", k, v))
                                .collect();
                            labels.sort();
                            format!("{} {{{}}}", expr_expanded, labels.join(", "))
                        };

                        let mut pts = Vec::with_capacity(s.values.len());
                        for (ts, val) in s.values {
                            if let Ok(y) = val.parse::<f64>() {
                                if y.is_finite() {
                                    pts.push((ts, y));
                                }
                            }
                        }
                        panel_results.push(SeriesView {
                            name: legend_base,
                            value: latest_val,
                            points: pts,
                            visible: true,
                        });
                        if let Some(last) = panel_results.last_mut() {
                            last.points = downsample(last.points.clone(), 200);
                        }
                    }
                }
                Err(e) => {
                    error = Some(format!("query_range failed for `{}`: {}", expr_expanded, e));
                }
            }
        }
        (p, panel_results, last_url, error)
    }
}

fn expand_expr(expr: &str, step: Duration, vars: &HashMap<String, String>) -> String {
    let mut s = expr.to_string();

    let interval_secs = std::cmp::max(step.as_secs() * 4, 60);
    let interval_param = format!("{}s", interval_secs);
    s = s.replace("$__rate_interval", &interval_param);

    for (k, v) in vars {
        s = s.replace(&format!("${{{}}}", k), v);
        s = s.replace(&format!("${}", k), v);
    }

    s
}

fn format_legend(fmt: &str, metric: &HashMap<String, String>) -> String {
    let mut out = fmt.to_string();
    for (k, v) in metric {
        out = out.replace(&format!("{{{{{}}}}}", k), v);
    }
    out
}

/// Downsamples data points to a maximum number of points using max-pooling.
/// This preserves peaks which is important for metrics.
fn downsample(points: Vec<(f64, f64)>, max_points: usize) -> Vec<(f64, f64)> {
    if points.len() <= max_points {
        return points;
    }

    let chunk_size = (points.len() as f64 / max_points as f64).ceil() as usize;
    if chunk_size <= 1 {
        return points;
    }

    points
        .chunks(chunk_size)
        .filter_map(|chunk| {
            chunk
                .iter()
                .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
                .cloned()
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_expand_expr_rate_interval() {
        let vars = HashMap::new();
        let step = Duration::from_secs(15);
        // heuristic: max(15*4, 60) = 60s
        let expr = "rate(http_requests_total[$__rate_interval])";
        let expanded = expand_expr(expr, step, &vars);
        assert_eq!(expanded, "rate(http_requests_total[60s])");

        let step = Duration::from_secs(30);
        // heuristic: max(30*4, 60) = 120s
        let expr = "rate(http_requests_total[$__rate_interval])";
        let expanded = expand_expr(expr, step, &vars);
        assert_eq!(expanded, "rate(http_requests_total[120s])");
    }

    #[test]
    fn test_expand_expr_vars() {
        let mut vars = HashMap::new();
        vars.insert("job".to_string(), "node-exporter".to_string());
        vars.insert("instance".to_string(), "localhost:9100".to_string());

        let step = Duration::from_secs(15);

        // Test $var
        let expr = "up{job=\"$job\"}";
        let expanded = expand_expr(expr, step, &vars);
        assert_eq!(expanded, "up{job=\"node-exporter\"}");

        // Test ${var}
        let expr = "up{instance=\"${instance}\"}";
        let expanded = expand_expr(expr, step, &vars);
        assert_eq!(expanded, "up{instance=\"localhost:9100\"}");

        // Test multiple vars
        let expr =
            "rate(http_requests_total{job=\"$job\", instance=\"$instance\"}[$__rate_interval])";
        let expanded = expand_expr(expr, step, &vars);
        assert_eq!(
            expanded,
            "rate(http_requests_total{job=\"node-exporter\", instance=\"localhost:9100\"}[60s])"
        );
    }

    #[test]
    fn test_format_legend() {
        let mut metric = HashMap::new();
        metric.insert("job".to_string(), "node".to_string());
        metric.insert("instance".to_string(), "localhost".to_string());

        let fmt = "Job: {{job}} - {{instance}}";
        assert_eq!(format_legend(fmt, &metric), "Job: node - localhost");

        let fmt2 = "Static Text";
        assert_eq!(format_legend(fmt2, &metric), "Static Text");
    }

    #[test]
    fn test_downsample() {
        let points: Vec<(f64, f64)> = (0..1000).map(|i| (i as f64, i as f64)).collect();
        let downsampled = downsample(points, 100);
        assert_eq!(downsampled.len(), 100);
        assert_eq!(downsampled.last().unwrap().1, 999.0);
    }

    #[tokio::test]
    async fn test_empty_panels() {
        let prom = prom::PromClient::new("http://localhost:9090".to_string());
        let mut app = AppState::new(
            prom,
            Duration::from_secs(3600),
            Duration::from_secs(60),
            Duration::from_millis(1000),
            "Test".to_string(),
            vec![], // Empty panels
            0,
            Theme::default(),
            "dashed".to_string(),
        );

        // Should not panic on refresh
        assert!(app.refresh().await.is_ok());

        // Check navigation safety
        app.scroll_to_selected_panel();
        assert_eq!(app.selected_panel, 0);

        // Check cursor movement
        app.move_cursor(1);
    }
}

pub fn default_queries(mut provided: Vec<String>) -> Vec<PanelState> {
    if provided.is_empty() {
        provided = vec![
            r#"sum(rate(http_requests_total{job!="prometheus"}[5m]))"#.to_string(),
            r#"sum by (instance) (process_cpu_seconds_total)"#.to_string(),
            r#"up"#.to_string(),
        ];
    }
    provided
        .into_iter()
        .map(|q| PanelState {
            title: q.clone(),
            exprs: vec![q],
            legends: vec![None],
            series: vec![],
            last_error: None,
            last_url: None,
            last_samples: 0,
            grid: None,
            y_axis_mode: YAxisMode::Auto,
            panel_type: PanelType::Graph,
            thresholds: None,
            min: None,
            max: None,
        })
        .collect()
}

pub fn parse_duration(s: &str) -> Result<Duration> {
    Ok(humantime::parse_duration(s)?)
}

pub async fn run_app<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    app: &mut AppState,
    tick_rate: Duration,
) -> Result<()>
where
    <B as ratatui::backend::Backend>::Error: Send + Sync + 'static,
{
    loop {
        terminal.draw(|f| ui::draw_ui(f, app))?;

        let timeout = tick_rate.saturating_sub(app.last_refresh.elapsed().min(tick_rate));
        let should_refresh = app.last_refresh.elapsed() >= app.refresh_every;

        if event::poll(timeout)? {
            match event::read()? {
                Event::Key(key) => {
                    if app.mode == AppMode::Search {
                        match key.code {
                            KeyCode::Esc => {
                                app.mode = AppMode::Normal;
                                app.search_query.clear();
                                app.search_results.clear();
                            }
                            KeyCode::Enter => {
                                if let Some(&idx) = app.search_results.first() {
                                    app.selected_panel = idx;
                                    app.mode = AppMode::Fullscreen; // Go to Fullscreen on selection
                                    app.search_query.clear();
                                    app.search_results.clear();
                                }
                            }
                            KeyCode::Backspace => {
                                app.search_query.pop();
                                if app.search_query.is_empty() {
                                    app.search_results.clear();
                                } else {
                                    app.search_results = app
                                        .panels
                                        .iter()
                                        .enumerate()
                                        .filter(|(_, p)| {
                                            p.title
                                                .to_lowercase()
                                                .contains(&app.search_query.to_lowercase())
                                        })
                                        .map(|(i, _)| i)
                                        .collect();
                                }
                            }
                            KeyCode::Char(c) => {
                                app.search_query.push(c);
                                app.search_results = app
                                    .panels
                                    .iter()
                                    .enumerate()
                                    .filter(|(_, p)| {
                                        p.title
                                            .to_lowercase()
                                            .contains(&app.search_query.to_lowercase())
                                    })
                                    .map(|(i, _)| i)
                                    .collect();
                            }
                            _ => {}
                        }
                    } else if app.mode == AppMode::Inspect {
                        match key.code {
                            KeyCode::Esc | KeyCode::Char('v') => {
                                app.mode = AppMode::Normal;
                                app.cursor_x = None;
                            }
                            KeyCode::Left => {
                                app.move_cursor(-1);
                            }
                            KeyCode::Right => {
                                app.move_cursor(1);
                            }
                            KeyCode::Char('q') => return Ok(()),
                            _ => {}
                        }
                    } else if app.mode == AppMode::Fullscreen {
                        match key.code {
                            KeyCode::Esc | KeyCode::Char('f') | KeyCode::Enter => {
                                app.mode = AppMode::Normal;
                            }
                            KeyCode::Char('v') => {
                                app.mode = AppMode::FullscreenInspect;
                                // Initialize cursor
                                let end_ts = (chrono::Utc::now().timestamp()
                                    - app.time_offset.as_secs() as i64)
                                    as f64;
                                let start_ts = end_ts - app.range.as_secs_f64();
                                app.cursor_x = Some((start_ts + end_ts) / 2.0);
                            }
                            KeyCode::Char('q') => return Ok(()),
                            KeyCode::Char('r') | KeyCode::Char('R') => {
                                app.refresh().await?;
                            }
                            // Allow some navigation/interaction in fullscreen too?
                            // For now, just basic ones.
                            KeyCode::Char('+') => {
                                app.zoom_out();
                                app.refresh().await?;
                            }
                            KeyCode::Char('-') => {
                                app.zoom_in();
                                app.refresh().await?;
                            }
                            KeyCode::Char('[') => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_left();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Left => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_left();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Char(']') => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_right();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Right => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_right();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Char('0') => {
                                app.reset_to_live();
                                app.refresh().await?;
                            }
                            KeyCode::Char('y') => {
                                if let Some(panel) = app.panels.get_mut(app.selected_panel) {
                                    panel.y_axis_mode = match panel.y_axis_mode {
                                        YAxisMode::Auto => YAxisMode::ZeroBased,
                                        YAxisMode::ZeroBased => YAxisMode::Auto,
                                    };
                                }
                            }
                            _ => {}
                        }
                    } else if app.mode == AppMode::FullscreenInspect {
                        match key.code {
                            KeyCode::Esc | KeyCode::Char('v') => {
                                app.mode = AppMode::Fullscreen;
                                app.cursor_x = None;
                            }
                            KeyCode::Left => {
                                app.move_cursor(-1);
                            }
                            KeyCode::Right => {
                                app.move_cursor(1);
                            }
                            KeyCode::Char('q') => return Ok(()),
                            _ => {}
                        }
                    } else {
                        // Normal Mode
                        match key.code {
                            KeyCode::Char('f') => {
                                app.mode = AppMode::Fullscreen;
                            }
                            KeyCode::Char('v') => {
                                app.mode = AppMode::Inspect;
                                let end_ts = (chrono::Utc::now().timestamp()
                                    - app.time_offset.as_secs() as i64)
                                    as f64;
                                let start_ts = end_ts - app.range.as_secs_f64();
                                app.cursor_x = Some((start_ts + end_ts) / 2.0);
                            }
                            KeyCode::Char('q') => return Ok(()),
                            KeyCode::Char('r') | KeyCode::Char('R') => {
                                app.refresh().await?;
                            }
                            KeyCode::Up | KeyCode::Char('k') => {
                                if app.selected_panel > 0 {
                                    app.selected_panel -= 1;
                                    // Auto-scroll to ensure selected panel is visible
                                    app.scroll_to_selected_panel();
                                }
                            }
                            KeyCode::Down | KeyCode::Char('j') => {
                                if app.selected_panel < app.panels.len().saturating_sub(1) {
                                    app.selected_panel += 1;
                                    // Auto-scroll to ensure selected panel is visible
                                    app.scroll_to_selected_panel();
                                }
                            }
                            KeyCode::PageUp => {
                                app.vertical_scroll = app.vertical_scroll.saturating_sub(10);
                            }
                            KeyCode::PageDown => {
                                app.vertical_scroll = app.vertical_scroll.saturating_add(10);
                            }
                            KeyCode::Char(c) if c.is_digit(10) => {
                                if let Some(digit) = c.to_digit(10) {
                                    if let Some(panel) = app.panels.get_mut(app.selected_panel) {
                                        if digit == 0 {
                                            // Show all
                                            for s in &mut panel.series {
                                                s.visible = true;
                                            }
                                        } else {
                                            // Toggle specific series (1-based index)
                                            let idx = (digit - 1) as usize;
                                            if let Some(series) = panel.series.get_mut(idx) {
                                                series.visible = !series.visible;
                                            }
                                        }
                                    }
                                }
                            }
                            KeyCode::Char('y') => {
                                if let Some(panel) = app.panels.get_mut(app.selected_panel) {
                                    panel.y_axis_mode = match panel.y_axis_mode {
                                        YAxisMode::Auto => YAxisMode::ZeroBased,
                                        YAxisMode::ZeroBased => YAxisMode::Auto,
                                    };
                                }
                            }
                            KeyCode::Home => {
                                app.vertical_scroll = 0;
                            }
                            KeyCode::End => {
                                app.vertical_scroll = usize::MAX; // Will be clamped by rendering logic usually, or we should track max height
                            }
                            KeyCode::Char('+') => {
                                app.zoom_out();
                                app.refresh().await?;
                            }
                            KeyCode::Char('-') => {
                                app.zoom_in();
                                app.refresh().await?;
                            }
                            KeyCode::Char('[') => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_left();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Left => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_left();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Char(']') => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_right();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Right => {
                                if key.modifiers.contains(KeyModifiers::SHIFT) {
                                    app.pan_right();
                                    app.refresh().await?;
                                }
                            }
                            KeyCode::Char('0') => {
                                app.reset_to_live();
                                app.refresh().await?;
                            }
                            KeyCode::Char('?') => {
                                app.debug_bar = !app.debug_bar;
                            }
                            KeyCode::Char('/') => {
                                app.mode = AppMode::Search;
                                app.search_query.clear();
                                app.search_results.clear();
                            }
                            _ => {}
                        }
                    }
                }
                Event::Mouse(mouse) => match mouse.kind {
                    crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left)
                    | crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left) =>
                    {
                        let size = terminal.size()?;
                        let rect = ratatui::layout::Rect::new(0, 0, size.width, size.height);
                        if let Some((idx, panel_rect)) =
                            ui::hit_test(app, rect, mouse.column, mouse.row)
                        {
                            app.selected_panel = idx;

                            // If in Fullscreen or FullscreenInspect, we are already focused on this panel (effectively)
                            // If in Normal/Inspect, we switch to Inspect mode if not already

                            match app.mode {
                                AppMode::Normal | AppMode::Inspect => {
                                    // In normal mode, mouse clicks only select the panel
                                    // Cursor mode must be activated with 'v' key
                                    // Don't transition to Inspect mode
                                }
                                AppMode::Fullscreen | AppMode::FullscreenInspect => {
                                    // In fullscreen, mouse clicks enable cursor
                                    app.mode = AppMode::FullscreenInspect;

                                    // Calculate cursor_x based on click position within panel_rect
                                    let chart_width = panel_rect.width.saturating_sub(2) as f64;
                                    if chart_width > 0.0 {
                                        let relative_x =
                                            (mouse.column.saturating_sub(panel_rect.x + 1)) as f64;
                                        let fraction = (relative_x / chart_width).clamp(0.0, 1.0);

                                        let end_ts = (chrono::Utc::now().timestamp()
                                            - app.time_offset.as_secs() as i64)
                                            as f64;
                                        let start_ts = end_ts - app.range.as_secs_f64();

                                        app.cursor_x =
                                            Some(start_ts + fraction * app.range.as_secs_f64());
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                    crossterm::event::MouseEventKind::ScrollDown => {
                        app.vertical_scroll = app.vertical_scroll.saturating_add(1);
                    }
                    crossterm::event::MouseEventKind::ScrollUp => {
                        app.vertical_scroll = app.vertical_scroll.saturating_sub(1);
                    }
                    _ => {}
                },
                _ => {}
            }
        }

        if should_refresh {
            app.refresh().await?;
        }

        sleep(Duration::from_millis(10)).await;
    }
}