ntomb 0.0.1

Network Tomb: Process-centric network visualization with Halloween theme
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
// Soul Inspector rendering module
//
// Renders the detail panel showing selected process/connection information,
// traffic sparkline, and socket list.
//
// The Soul Inspector displays real-time data about the currently selected
// target (process or connection) from AppState.

use crate::app::{AppState, GraveyardMode};
use crate::net::{Connection, ConnectionState};
use crate::theme::{
    get_refresh_color, get_status_text, BLOOD_RED, BONE_WHITE, NEON_PURPLE, PUMPKIN_ORANGE,
    TOXIC_GREEN,
};
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Paragraph, Sparkline},
    Frame,
};

// ============================================================================
// Soul Inspector View Model
// ============================================================================

/// View model for Soul Inspector panel
///
/// Contains all data needed to render the Soul Inspector, extracted from AppState.
/// This separates data extraction from rendering logic.
#[derive(Debug, Clone)]
pub struct SoulInspectorView {
    /// Target name to display (process name, connection endpoint, or "HOST")
    pub target_name: String,
    /// Target icon (⚰️ for process, 🔗 for connection, 🏠 for host)
    pub target_icon: String,
    /// Process ID if available
    pub pid: Option<i32>,
    /// Parent process ID (not available in current data model, reserved for future use)
    #[allow(dead_code)]
    pub ppid: Option<i32>,
    /// User name (not available in current data model, reserved for future use)
    #[allow(dead_code)]
    pub user: Option<String>,
    /// State icon (🟢, 🟡, 🔴)
    pub state_icon: String,
    /// State text (e.g., "ESTABLISHED (Alive)")
    pub state_text: String,
    /// State color for styling
    pub state_color: Color,
    /// Current UI refresh interval in milliseconds
    pub refresh_ms: u64,
    /// Number of connections for this target
    pub conn_count: usize,
    /// Number of server (LISTEN) connections
    pub server_count: usize,
    /// Number of client (ESTABLISHED) connections
    pub client_count: usize,
    /// Number of public/external connections
    pub public_count: usize,
    /// List of connections/sockets for this target
    pub sockets: Vec<SocketInfo>,
    /// Whether this target has suspicious activity
    pub suspicious: bool,
    /// Number of suspicious connections
    pub suspicious_count: usize,
    /// Suspicious reasons (e.g., "high-port", "non-standard")
    pub suspicious_reasons: Vec<String>,
    /// Tags for this target
    pub tags: Vec<String>,
    /// Whether a target is selected
    pub has_selection: bool,
}

/// Socket/connection info for display in the socket list
#[derive(Debug, Clone)]
pub struct SocketInfo {
    /// Display string (e.g., "tcp://127.0.0.1:8080")
    pub display: String,
    /// Remote endpoint if applicable
    pub remote: Option<String>,
    /// Connection state
    pub state: ConnectionState,
}

impl Default for SoulInspectorView {
    fn default() -> Self {
        Self {
            target_name: "No target selected".to_string(),
            target_icon: "👻".to_string(),
            pid: None,
            ppid: None,
            user: None,
            state_icon: "".to_string(),
            state_text: "Idle".to_string(),
            state_color: BONE_WHITE,
            refresh_ms: 500,
            conn_count: 0,
            server_count: 0,
            client_count: 0,
            public_count: 0,
            sockets: Vec::new(),
            suspicious: false,
            suspicious_count: 0,
            suspicious_reasons: Vec::new(),
            tags: Vec::new(),
            has_selection: false,
        }
    }
}

/// Build SoulInspectorView from AppState
///
/// Extracts relevant data based on current selection mode:
/// - Host mode: Shows overall host statistics
/// - Process mode: Shows selected process details and its connections
/// - Connection selected: Shows selected connection details
pub fn build_soul_inspector_view(app: &AppState) -> SoulInspectorView {
    let mut view = SoulInspectorView {
        refresh_ms: app.refresh_config.refresh_ms,
        ..Default::default()
    };

    match app.graveyard_mode {
        GraveyardMode::Host => {
            // Host mode - show overall statistics or selected connection
            if let Some(conn_idx) = app.selected_connection {
                // A connection is selected - show its details
                if let Some(conn) = app.connections.get(conn_idx) {
                    build_connection_view(&mut view, conn, &app.connections);
                }
            } else {
                // No selection - show host overview
                build_host_view(&mut view, &app.connections);
            }
        }
        GraveyardMode::Process => {
            // Process mode - show selected process details
            if let Some(pid) = app.selected_process_pid {
                build_process_view(&mut view, pid, &app.connections);
            } else {
                // Process mode but no PID (shouldn't happen normally)
                view.target_name = "No process selected".to_string();
                view.target_icon = "".to_string();
            }
        }
    }

    view
}

/// Build view for Host mode (no specific selection)
fn build_host_view(view: &mut SoulInspectorView, connections: &[Connection]) {
    view.target_name = "HOST".to_string();
    view.target_icon = "🏠".to_string();
    view.has_selection = true;

    // Count connection states
    let established = connections
        .iter()
        .filter(|c| c.state == ConnectionState::Established)
        .count();
    let listening = connections
        .iter()
        .filter(|c| c.state == ConnectionState::Listen)
        .count();
    let other = connections.len() - established - listening;

    // Count public/external connections (non-RFC1918, non-localhost)
    let public_count = connections
        .iter()
        .filter(|c| is_public_ip(&c.remote_addr))
        .count();

    view.conn_count = connections.len();
    view.server_count = listening;
    view.client_count = established;
    view.public_count = public_count;

    // Check for suspicious patterns across all connections
    let mut suspicious_count = 0;
    let mut suspicious_reasons: Vec<String> = Vec::new();

    for conn in connections {
        if conn.remote_port > 49152 && conn.local_port > 49152 {
            suspicious_count += 1;
            if !suspicious_reasons.contains(&"high-port".to_string()) {
                suspicious_reasons.push("high-port".to_string());
            }
        }
        // Check for non-standard ports on established connections
        let standard_ports = [
            80, 443, 22, 21, 25, 53, 110, 143, 993, 995, 3306, 5432, 6379, 27017,
        ];
        if conn.state == ConnectionState::Established
            && !standard_ports.contains(&conn.remote_port)
            && conn.remote_port > 1024
            && is_public_ip(&conn.remote_addr)
        {
            suspicious_count += 1;
            if !suspicious_reasons.contains(&"non-standard".to_string()) {
                suspicious_reasons.push("non-standard".to_string());
            }
        }
    }

    view.suspicious = suspicious_count > 0;
    view.suspicious_count = suspicious_count;
    view.suspicious_reasons = suspicious_reasons;

    // Determine overall state based on connection health
    if connections.is_empty() {
        view.state_icon = "".to_string();
        view.state_text = "No connections".to_string();
        view.state_color = BONE_WHITE;
    } else if established > 0 {
        view.state_icon = "🟢".to_string();
        view.state_text = format!("{} active, {} listening", established, listening);
        view.state_color = TOXIC_GREEN;
    } else if listening > 0 {
        view.state_icon = "🟡".to_string();
        view.state_text = format!("{} listening", listening);
        view.state_color = PUMPKIN_ORANGE;
    } else {
        view.state_icon = "🟠".to_string();
        view.state_text = format!("{} other states", other);
        view.state_color = PUMPKIN_ORANGE;
    }

    // Build socket list (show first few connections)
    view.sockets = connections
        .iter()
        .take(5)
        .map(connection_to_socket_info)
        .collect();

    // Add tags
    if listening > 0 {
        view.tags.push(format!("server ({})", listening));
    }
    if established > 0 {
        view.tags.push(format!("client ({})", established));
    }
}

/// Build view for a selected connection
fn build_connection_view(
    view: &mut SoulInspectorView,
    conn: &Connection,
    all_connections: &[Connection],
) {
    view.has_selection = true;
    view.target_icon = "🔗".to_string();

    // Target name: show remote endpoint or local if LISTEN
    if conn.state == ConnectionState::Listen {
        view.target_name = format!("{}:{}", conn.local_addr, conn.local_port);
    } else {
        view.target_name = format!("{}:{}", conn.remote_addr, conn.remote_port);
    }

    // Truncate if too long
    if view.target_name.len() > 20 {
        view.target_name = format!("{}...", &view.target_name[..17]);
    }

    // PID and process info
    view.pid = conn.pid;

    // State
    let (icon, text, color) = connection_state_display(conn.state);
    view.state_icon = icon;
    view.state_text = text;
    view.state_color = color;

    // Count connections to same remote
    if conn.state != ConnectionState::Listen {
        view.conn_count = all_connections
            .iter()
            .filter(|c| c.remote_addr == conn.remote_addr)
            .count();
    } else {
        view.conn_count = 1;
    }

    // Socket info
    view.sockets = vec![connection_to_socket_info(conn)];

    // Add process name as tag if available
    if let Some(ref name) = conn.process_name {
        view.tags.push(name.clone());
    }

    // Check for suspicious patterns
    check_suspicious_patterns(view, conn);
}

/// Build view for a selected process
fn build_process_view(view: &mut SoulInspectorView, pid: i32, connections: &[Connection]) {
    view.has_selection = true;
    view.target_icon = "⚰️".to_string();
    view.pid = Some(pid);

    // Find connections for this process
    let process_conns: Vec<&Connection> =
        connections.iter().filter(|c| c.pid == Some(pid)).collect();

    // Get process name from first connection
    let process_name = process_conns
        .iter()
        .find_map(|c| c.process_name.clone())
        .unwrap_or_else(|| format!("PID {}", pid));

    view.target_name = if process_name.len() > 15 {
        format!("{}...", &process_name[..12])
    } else {
        process_name.clone()
    };

    view.conn_count = process_conns.len();

    // Determine state based on connections
    let established = process_conns
        .iter()
        .filter(|c| c.state == ConnectionState::Established)
        .count();
    let listening = process_conns
        .iter()
        .filter(|c| c.state == ConnectionState::Listen)
        .count();
    let problematic = process_conns
        .iter()
        .filter(|c| {
            matches!(
                c.state,
                ConnectionState::CloseWait | ConnectionState::TimeWait | ConnectionState::Close
            )
        })
        .count();

    if process_conns.is_empty() {
        view.state_icon = "".to_string();
        view.state_text = "No connections".to_string();
        view.state_color = BONE_WHITE;
    } else if problematic > 0 {
        view.state_icon = "🟠".to_string();
        view.state_text = format!("{} problematic", problematic);
        view.state_color = PUMPKIN_ORANGE;
    } else if established > 0 {
        view.state_icon = "🟢".to_string();
        view.state_text = format!("{} established", established);
        view.state_color = TOXIC_GREEN;
    } else if listening > 0 {
        view.state_icon = "🟡".to_string();
        view.state_text = format!("{} listening", listening);
        view.state_color = PUMPKIN_ORANGE;
    } else {
        view.state_icon = "".to_string();
        view.state_text = "Idle".to_string();
        view.state_color = BONE_WHITE;
    }

    // Build socket list
    view.sockets = process_conns
        .iter()
        .take(5)
        .map(|c| connection_to_socket_info(c))
        .collect();

    // Tags
    view.tags.push(process_name);
    if listening > 0 {
        view.tags.push("server".to_string());
    }
    if established > 0 {
        view.tags.push("client".to_string());
    }
}

/// Convert Connection to SocketInfo for display
fn connection_to_socket_info(conn: &Connection) -> SocketInfo {
    let display = format!("tcp://{}:{}", conn.local_addr, conn.local_port);
    let remote = if conn.state == ConnectionState::Listen || conn.remote_addr == "0.0.0.0" {
        None
    } else {
        Some(format!("{}:{}", conn.remote_addr, conn.remote_port))
    };

    SocketInfo {
        display,
        remote,
        state: conn.state,
    }
}

/// Get display info for connection state
fn connection_state_display(state: ConnectionState) -> (String, String, Color) {
    match state {
        ConnectionState::Established => (
            "🟢".to_string(),
            "ESTABLISHED (Alive)".to_string(),
            TOXIC_GREEN,
        ),
        ConnectionState::Listen => (
            "🟡".to_string(),
            "LISTEN (Waiting)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::TimeWait => (
            "🟠".to_string(),
            "TIME_WAIT (Closing)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::CloseWait => (
            "🟠".to_string(),
            "CLOSE_WAIT (Stale)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::Close => ("🔴".to_string(), "CLOSED (Dead)".to_string(), BLOOD_RED),
        ConnectionState::SynSent => (
            "🟡".to_string(),
            "SYN_SENT (Connecting)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::SynRecv => (
            "🟡".to_string(),
            "SYN_RECV (Handshake)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::FinWait1 | ConnectionState::FinWait2 => (
            "🟠".to_string(),
            "FIN_WAIT (Closing)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::LastAck => (
            "🟠".to_string(),
            "LAST_ACK (Closing)".to_string(),
            PUMPKIN_ORANGE,
        ),
        ConnectionState::Closing => ("🟠".to_string(), "CLOSING".to_string(), PUMPKIN_ORANGE),
        ConnectionState::Unknown => ("".to_string(), "UNKNOWN".to_string(), BONE_WHITE),
    }
}

/// Check for suspicious patterns in a connection
fn check_suspicious_patterns(view: &mut SoulInspectorView, conn: &Connection) {
    // High port to high port (potential C2)
    if conn.remote_port > 49152 && conn.local_port > 49152 {
        view.suspicious = true;
        view.tags.push("high-port".to_string());
    }

    // Connection to non-standard ports
    let standard_ports = [
        80, 443, 22, 21, 25, 53, 110, 143, 993, 995, 3306, 5432, 6379, 27017,
    ];
    if conn.state == ConnectionState::Established
        && !standard_ports.contains(&conn.remote_port)
        && conn.remote_port > 1024
    {
        view.tags.push("non-standard".to_string());
    }
}

/// Check if an IP address is public (not localhost, not RFC1918 private)
fn is_public_ip(addr: &str) -> bool {
    // Localhost
    if addr == "127.0.0.1" || addr == "::1" || addr == "0.0.0.0" || addr.starts_with("127.") {
        return false;
    }

    // RFC1918 private ranges
    if addr.starts_with("10.") || addr.starts_with("192.168.") {
        return false;
    }

    // 172.16.0.0 - 172.31.255.255
    if addr.starts_with("172.") {
        if let Some(second_octet) = addr.split('.').nth(1) {
            if let Ok(octet) = second_octet.parse::<u8>() {
                if (16..=31).contains(&octet) {
                    return false;
                }
            }
        }
    }

    // Link-local
    if addr.starts_with("169.254.") || addr.starts_with("fe80:") {
        return false;
    }

    true
}

pub fn render_soul_inspector(f: &mut Frame, area: Rect, app: &AppState) {
    // Build view model from app state
    let view = build_soul_inspector_view(app);

    // Split area for content and sparkline
    let inspector_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(11), // Top info with refresh rate
            Constraint::Length(5),  // Sparkline
            Constraint::Min(0),     // Socket list
        ])
        .split(area);

    // Check if refresh interval was recently changed
    let recently_changed = app
        .refresh_config
        .last_change
        .map(|last| last.elapsed() < crate::app::CHANGE_HIGHLIGHT_DURATION)
        .unwrap_or(false);

    // Get color for refresh interval based on its value
    let refresh_color = get_refresh_color(view.refresh_ms, 100, recently_changed);

    // Apply highlight style if recently changed
    let refresh_style = if recently_changed {
        Style::default()
            .fg(refresh_color)
            .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
    } else {
        Style::default().fg(refresh_color)
    };

    // Get status text based on overdrive mode
    let overdrive_enabled = app.graveyard_settings.overdrive_enabled;
    let overdrive_suffix = if overdrive_enabled {
        get_status_text(ConnectionState::Established, true).to_string()
    } else {
        "Active".to_string()
    };
    let status_display = format!(
        "{} {} ({})",
        view.state_icon,
        view.state_text
            .split(" (")
            .next()
            .unwrap_or(&view.state_text),
        overdrive_suffix
    );

    // Suspicious indicator
    let suspicious_indicator = if view.suspicious {
        Span::styled(
            " ⚠️",
            Style::default().fg(BLOOD_RED).add_modifier(Modifier::BOLD),
        )
    } else {
        Span::raw("")
    };

    // Top section with blockified layout for clear information hierarchy
    // Format: TARGET / ROLE / STATE / CONN / RISK / BPF
    let mut top_content = vec![
        // TARGET line
        Line::from(vec![
            Span::styled("  TARGET: ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("{} {}", view.target_icon, view.target_name),
                Style::default()
                    .fg(PUMPKIN_ORANGE)
                    .add_modifier(Modifier::BOLD),
            ),
            suspicious_indicator,
        ]),
        // ROLE line - server/client breakdown
        Line::from(vec![
            Span::styled("  ROLE:   ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("[server {}] ", view.server_count),
                Style::default().fg(NEON_PURPLE),
            ),
            Span::styled(
                format!("[client {}] ", view.client_count),
                Style::default().fg(TOXIC_GREEN),
            ),
            Span::styled(
                format!("[public {}]", view.public_count),
                Style::default().fg(PUMPKIN_ORANGE),
            ),
        ]),
        // STATE line
        Line::from(vec![
            Span::styled("  STATE:  ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                status_display,
                Style::default()
                    .fg(view.state_color)
                    .add_modifier(Modifier::BOLD),
            ),
        ]),
        // CONN line
        Line::from(vec![
            Span::styled("  CONN:   ", Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("{} total", view.conn_count),
                Style::default().fg(BONE_WHITE),
            ),
            if let Some(pid) = view.pid {
                Span::styled(
                    format!("  (PID: {})", pid),
                    Style::default().fg(Color::Cyan),
                )
            } else {
                Span::raw("")
            },
        ]),
    ];

    // RISK line - only show if suspicious activity detected
    if view.suspicious {
        let reasons = if view.suspicious_reasons.is_empty() {
            "unknown".to_string()
        } else {
            view.suspicious_reasons.join(", ")
        };
        top_content.push(Line::from(vec![
            Span::styled("  RISK:   ", Style::default().fg(Color::DarkGray)),
            Span::styled("🩸 ", Style::default().fg(BLOOD_RED)),
            Span::styled(
                format!("{} suspicious ({})", view.suspicious_count, reasons),
                Style::default().fg(BLOOD_RED).add_modifier(Modifier::BOLD),
            ),
        ]));
    }

    // BPF line - refresh rate
    top_content.push(Line::from(vec![
        Span::styled("  BPF:    ", Style::default().fg(Color::DarkGray)),
        Span::styled("ACTIVE ", Style::default().fg(TOXIC_GREEN)),
        Span::styled("(", Style::default().fg(Color::DarkGray)),
        Span::styled(format!("{}ms", view.refresh_ms), refresh_style),
        Span::styled(")", Style::default().fg(Color::DarkGray)),
    ]));

    // Title with suspicious warning if applicable
    let title_spans = if view.suspicious {
        vec![
            Span::styled(
                "━ 🔮 Soul Inspector ",
                Style::default()
                    .fg(NEON_PURPLE)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "⚠️ ",
                Style::default().fg(BLOOD_RED).add_modifier(Modifier::BOLD),
            ),
            Span::styled("━━━━", Style::default().fg(NEON_PURPLE)),
        ]
    } else {
        vec![
            Span::styled(
                "━ 🔮 Soul Inspector (Detail) ",
                Style::default()
                    .fg(NEON_PURPLE)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled("━━━━━━", Style::default().fg(NEON_PURPLE)),
        ]
    };

    let top_paragraph = Paragraph::new(top_content).block(
        Block::default()
            .title(title_spans)
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(if view.suspicious {
                BLOOD_RED
            } else {
                NEON_PURPLE
            })),
    );

    f.render_widget(top_paragraph, inspector_chunks[0]);

    // Calculate traffic history statistics
    let traffic_avg = if app.traffic_history.is_empty() {
        0.0
    } else {
        app.traffic_history.iter().sum::<u64>() as f64 / app.traffic_history.len() as f64
    };
    let traffic_peak = app.traffic_history.iter().max().copied().unwrap_or(0);

    // Sparkline for traffic history with Avg/Peak stats in title
    let sparkline = Sparkline::default()
        .block(
            Block::default()
                .title(vec![
                    Span::styled(
                        " 📊 Activity ",
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(
                        format!("Avg:{:.0} ", traffic_avg),
                        Style::default().fg(BONE_WHITE),
                    ),
                    Span::styled(
                        format!("Peak:{} ", traffic_peak),
                        Style::default().fg(PUMPKIN_ORANGE),
                    ),
                ])
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(NEON_PURPLE)),
        )
        .data(&app.traffic_history)
        .style(Style::default().fg(TOXIC_GREEN))
        .max(100);

    f.render_widget(sparkline, inspector_chunks[1]);

    // Bottom section with socket list - now using real data
    let mut socket_lines = vec![Line::from("")];

    if view.sockets.is_empty() {
        socket_lines.push(Line::from(vec![Span::styled(
            "  (no sockets)",
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::ITALIC),
        )]));
    } else {
        for socket in &view.sockets {
            let state_color = match socket.state {
                ConnectionState::Established => TOXIC_GREEN,
                ConnectionState::Listen => PUMPKIN_ORANGE,
                ConnectionState::TimeWait | ConnectionState::CloseWait => PUMPKIN_ORANGE,
                ConnectionState::Close => BLOOD_RED,
                _ => BONE_WHITE,
            };

            let state_str = match socket.state {
                ConnectionState::Established => "ESTABLISHED",
                ConnectionState::Listen => "LISTEN",
                ConnectionState::TimeWait => "TIME_WAIT",
                ConnectionState::CloseWait => "CLOSE_WAIT",
                ConnectionState::Close => "CLOSED",
                ConnectionState::SynSent => "SYN_SENT",
                _ => "OTHER",
            };

            if let Some(ref remote) = socket.remote {
                socket_lines.push(Line::from(vec![
                    Span::raw("  > "),
                    Span::styled(&socket.display, Style::default().fg(Color::Cyan)),
                    Span::raw(""),
                    Span::styled(remote, Style::default().fg(Color::Blue)),
                ]));
            } else {
                socket_lines.push(Line::from(vec![
                    Span::raw("  > "),
                    Span::styled(&socket.display, Style::default().fg(Color::Cyan)),
                    Span::styled(
                        format!(" ({})", state_str),
                        Style::default().fg(state_color),
                    ),
                ]));
            }
        }

        // Show "and N more" if there are more sockets
        if view.conn_count > view.sockets.len() {
            socket_lines.push(Line::from(vec![Span::styled(
                format!("  ... and {} more", view.conn_count - view.sockets.len()),
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC),
            )]));
        }
    }

    let socket_paragraph = Paragraph::new(socket_lines).block(
        Block::default()
            .title(vec![Span::styled(
                format!(" 📜 Open Sockets ({}) ", view.sockets.len()),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )])
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(NEON_PURPLE)),
    );

    f.render_widget(socket_paragraph, inspector_chunks[2]);
}