import React, { useEffect, useState } from "react";
import './App.css';

function App() {
  const [computers, setComputers] = useState([]);
  const [filteredComputers, setFilteredComputers] = useState([]);
  const [stats, setStats] = useState(null);
  const [selectedComputer, setSelectedComputer] = useState(null);
  const [computerDetails, setComputerDetails] = useState(null);
  const [loadingDetails, setLoadingDetails] = useState(false);
  const [performanceData, setPerformanceData] = useState([]);
  const [eventDistribution, setEventDistribution] = useState([]);
  const [networkTraffic, setNetworkTraffic] = useState([]);
  const [topProcesses, setTopProcesses] = useState([]);
   // Бои за графикони
  const CHART_COLORS = {
    primary: '#2563eb',
    secondary: '#7c3aed',
    accentGreen: '#10b981',
    accentOrange: '#f59e0b',
    accentRed: '#ef4444',
    lightBlue: '#93c5fd',
    lightPurple: '#c4b5fd'
  };

  // Функција за вчитување на податоци за графикони
  const loadChartData = () => {
    // Перформанс податоци (симулирани, треба да ги земеш од API)
    const mockPerfData = Array.from({ length: 24 }, (_, i) => ({
      hour: `${i}:00`,
      cpu: 20 + Math.random() * 30,
      memory: 30 + Math.random() * 40,
      network: Math.random() * 100
    }));
    setPerformanceData(mockPerfData);

    // Дистрибуција на настани
    const mockEventDist = [
      { name: 'Process Create', value: 45, color: CHART_COLORS.primary },
      { name: 'Network', value: 25, color: CHART_COLORS.secondary },
      { name: 'File Create', value: 15, color: CHART_COLORS.accentGreen },
      { name: 'Registry', value: 10, color: CHART_COLORS.accentOrange },
      { name: 'Other', value: 5, color: CHART_COLORS.accentRed }
    ];
    setEventDistribution(mockEventDist);

    // Мрежен сообраќај
    const mockNetworkData = Array.from({ length: 12 }, (_, i) => ({
      time: `${i * 2}:00`,
      inbound: 50 + Math.random() * 200,
      outbound: 30 + Math.random() * 150
    }));
    setNetworkTraffic(mockNetworkData);

    // Топ процеси
    const mockTopProcesses = [
      { name: 'chrome.exe', cpu: 25, memory: 1200 },
      { name: 'python.exe', cpu: 18, memory: 800 },
      { name: 'explorer.exe', cpu: 12, memory: 300 },
      { name: 'svchost.exe', cpu: 8, memory: 200 },
      { name: 'node.exe', cpu: 6, memory: 500 }
    ];
    setTopProcesses(mockTopProcesses);
  };

  useEffect(() => {
    loadChartData();
    // Автоматско освежување на графикони
    const chartInterval = setInterval(loadChartData, 30000);
    return () => clearInterval(chartInterval);
  }, []);
  // Filter state
  const [filters, setFilters] = useState({
    status: "all",
    search: "",
    os: "all",
    minCpu: 0,
    minRam: 0
  });

  // AI chat state
  const [chatQuestion, setChatQuestion] = useState("");
  const [chatAnswer, setChatAnswer] = useState("");
  const [chatLoading, setChatLoading] = useState(false);
  const [chatComputer, setChatComputer] = useState("");
  const [chatHistory, setChatHistory] = useState([]);
  const [isChatOpen, setIsChatOpen] = useState(true);
  const [showWelcome, setShowWelcome] = useState(true);

  // Modal tabs state
  const [activeTab, setActiveTab] = useState('security');
  const [sysmonData, setSysmonData] = useState(null);
  const [networkData, setNetworkData] = useState(null);
  const [loadingSysmon, setLoadingSysmon] = useState(false);
  const [loadingNetwork, setLoadingNetwork] = useState(false);
  const [selectedSysmonProcess, setSelectedSysmonProcess] = useState(null);
  const [selectedNetworkItem, setSelectedNetworkItem] = useState(null);

  // Load main data
  useEffect(() => {
    loadComputers();
    loadStats();
    const interval = setInterval(() => {
      loadComputers();
      loadStats();
    }, 30000);
    return () => clearInterval(interval);
  }, []);

  // Apply filters
  useEffect(() => {
    let result = computers;
    if (filters.status !== "all") {
      result = result.filter(c => c.status === filters.status);
    }
    if (filters.os !== "all") {
      result = result.filter(c => c.os && c.os.toLowerCase().includes(filters.os.toLowerCase()));
    }
    if (filters.minCpu > 0) {
      result = result.filter(c => (c.avg_cpu || 0) >= filters.minCpu);
    }
    if (filters.minRam > 0) {
      result = result.filter(c => (c.avg_ram || 0) >= filters.minRam);
    }
    if (filters.search.trim()) {
      const searchTerm = filters.search.toLowerCase();
      result = result.filter(c =>
        c.name.toLowerCase().includes(searchTerm) ||
        (c.user && c.user.toLowerCase().includes(searchTerm)) ||
        (c.ip && c.ip.includes(searchTerm))
      );
    }
    setFilteredComputers(result);
  }, [computers, filters]);

  const loadComputers = () => {
    fetch("/api/computers")
      .then((r) => r.json())
      .then(data => setComputers(data))
      .catch((err) => console.error("API error:", err));
  };

  const loadStats = () => {
    fetch("/api/stats")
      .then((r) => r.json())
      .then(setStats)
      .catch((err) => console.error("API error:", err));
  };

  const openComputer = (name) => {
    setSelectedComputer(name);
    setLoadingDetails(true);
    setComputerDetails(null);
    setActiveTab('security');
    setSysmonData(null);
    setNetworkData(null);

    fetch(`/api/computer/${encodeURIComponent(name)}`)
      .then((r) => r.json())
      .then((data) => {
        setComputerDetails(data);
        setLoadingDetails(false);
      })
      .catch((err) => {
        console.error("API error:", err);
        setLoadingDetails(false);
      });
  };

  // Load Sysmon processes
const loadSysmonProcesses = () => {
  if (!selectedComputer) return;
  setLoadingSysmon(true);
  setSelectedSysmonProcess(null);

  // КОРИГИРАЈ ГО ОВА URL
  fetch(`/api/computer/${encodeURIComponent(selectedComputer)}/sysmon`)
    .then((r) => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    })
    .then((data) => {
      console.log("Sysmon data received:", data);

      // Ако data.processes е празна, пробај со детален endpoint
      if (!data.processes || data.processes.length === 0) {
        return fetch(`/api/computer/${encodeURIComponent(selectedComputer)}/detailed-sysmon`)
          .then(r => r.json())
          .then(detailedData => {
            setSysmonData(detailedData);
            setLoadingSysmon(false);
          });
      }

      setSysmonData(data);
      setLoadingSysmon(false);
    })
    .catch((err) => {
      console.error("Sysmon API error:", err);

      // Fallback - пробај да земеш Sysmon events од општиот endpoint
      fetch(`/api/computer/${encodeURIComponent(selectedComputer)}`)
        .then(r => r.json())
        .then(fullData => {
          if (fullData.sysmon_events) {
            // Конвертирај Sysmon events во процес формат
            const processes = fullData.sysmon_events.map((ev, idx) => ({
              process_id: ev.event_id,
              process_name: ev.event_type,
              timestamp: ev.timestamp,
              message: ev.message,
              details: ev.details || {}
            }));

            setSysmonData({
              computer_name: selectedComputer,
              processes: processes,
              count: processes.length
            });
          }
          setLoadingSysmon(false);
        })
        .catch(() => {
          setLoadingSysmon(false);
        });
    });
};
  // Load Network connections
const loadNetworkConnections = () => {
  if (!selectedComputer) return;
  setLoadingNetwork(true);
  setSelectedNetworkItem(null);

  // КОРИГИРАЈ ГО ОВА URL
  fetch(`/api/computer/${encodeURIComponent(selectedComputer)}/network`)
    .then((r) => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    })
    .then((data) => {
      console.log("Network data received:", data);

      setNetworkData(data);
      setLoadingNetwork(false);
    })
    .catch((err) => {
      console.error("Network API error:", err);

      // Fallback - пробај да земеш network од општиот endpoint
      fetch(`/api/computer/${encodeURIComponent(selectedComputer)}`)
        .then(r => r.json())
        .then(fullData => {
          if (fullData.network_connections) {
            const connections = fullData.network_connections.map((conn, idx) => ({
              pid: conn.pid,
              process_name: conn.process_name,
              local_address: conn.local_address,
              remote_address: conn.remote_address,
              status: conn.status,
              timestamp: conn.timestamp,
              // Додади ги овие полиња за да match-не со очекуваниот формат
              local_port: conn.local_address?.split(':')?.[1] || '',
              remote_port: conn.remote_address?.split(':')?.[1] || '',
              protocol: 'TCP'
            }));

            setNetworkData({
              computer_name: selectedComputer,
              connections: connections,
              count: connections.length
            });
          }
          setLoadingNetwork(false);
        })
        .catch(() => {
          setLoadingNetwork(false);
        });
    });
};
  const formatTime = (iso) => {
    if (!iso) return "-";
    const d = new Date(iso);
    return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  };

  const formatDate = (iso) => {
    if (!iso) return "-";
    const d = new Date(iso);
    return d.toLocaleDateString();
  };

  const askAssistant = async () => {
    if (!chatQuestion.trim()) return;
    const question = chatQuestion;
    setChatLoading(true);
    setChatQuestion("");
    setShowWelcome(false);

    const newHistory = [...chatHistory, {
      type: "question",
      content: question,
      computer: chatComputer,
      timestamp: new Date().toISOString()
    }];
    setChatHistory(newHistory);

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          question: question,
          computer_name: chatComputer || null,
        }),
      });

      const answer = await res.json();
      const finalAnswer = answer.answer || answer.error || "I couldn't process that request.";

      setChatHistory([...newHistory, {
        type: "answer",
        content: finalAnswer,
        timestamp: new Date().toISOString()
      }]);
    } catch (err) {
      setChatHistory([...newHistory, {
        type: "answer",
        content: "⚠️ Connection error. Please check the server.",
        timestamp: new Date().toISOString()
      }]);
    } finally {
      setChatLoading(false);
    }
  };

  const resetFilters = () => {
    setFilters({
      status: "all",
      search: "",
      os: "all",
      minCpu: 0,
      minRam: 0
    });
  };

  const clearChat = () => {
    setChatHistory([]);
    setChatAnswer("");
    setShowWelcome(true);
  };

  const closeModal = () => {
    setSelectedComputer(null);
    setComputerDetails(null);
    setSysmonData(null);
    setNetworkData(null);
    setSelectedSysmonProcess(null);
    setSelectedNetworkItem(null);
  };

  const quickQuestions = [
    "Show security alerts from yesterday",
    "Which devices have high CPU usage?",
    "List suspicious network connections",
    "Show recent Sysmon events",
    "Display offline devices"
  ];

  return (
    <div className="app-container">
      {/* Main Content */}
      <main className="main-content">
        {/* Top Navigation */}
        <nav className="top-nav">
          <div className="nav-left">
            <div className="logo">
              <div className="logo-icon">🛡️</div>
              <div className="logo-text">
                <h1>LAN Sentinel</h1>
                <span className="logo-subtitle">Enterprise Security Dashboard</span>
              </div>
            </div>
          </div>

          <div className="nav-center">
            <div className="search-bar">
              <input
                type="text"
                placeholder="Search devices..."
                value={filters.search}
                onChange={(e) => setFilters({...filters, search: e.target.value})}
              />
              <span className="search-icon">🔍</span>
            </div>
          </div>

          <div className="nav-right">
            <button
              className={`ai-toggle-btn ${isChatOpen ? 'active' : ''}`}
              onClick={() => setIsChatOpen(!isChatOpen)}
            >
              <span className="ai-icon">🤖</span>
              <span>AI Assistant</span>
            </button>
            <button className="refresh-btn" onClick={loadComputers}>
              <span className="refresh-icon">↻</span>
              Refresh
            </button>
            <div className="user-profile">
              <div className="profile-avatar">AD</div>
            </div>
          </div>
        </nav>

        {/* Stats Overview */}
        <section className="stats-overview">
          <div className="stats-header">
            <h2>Network Overview</h2>
            <div className="stats-time">
              Last updated: {new Date().toLocaleTimeString()}
            </div>
          </div>

          <div className="stats-grid">
            <div className="stat-card">
              <div className="stat-main">
                <span className="stat-number">{computers.length}</span>
                <span className="stat-label">Total Devices</span>
              </div>
              <div className="stat-icon">🖥️</div>
            </div>

            <div className="stat-card online">
              <div className="stat-main">
                <span className="stat-number">{computers.filter(c => c.status === 'online').length}</span>
                <span className="stat-label">Online</span>
              </div>
              <div className="stat-trend">
                <span className="trend-up">↑</span>
                <span>{computers.length > 0 ? Math.round((computers.filter(c => c.status === 'online').length/computers.length)*100) : 0}%</span>
              </div>
            </div>

            <div className="stat-card idle">
              <div className="stat-main">
                <span className="stat-number">{computers.filter(c => c.status === 'idle').length}</span>
                <span className="stat-label">Idle</span>
              </div>
              <div className="stat-icon">⏸️</div>
            </div>

            <div className="stat-card offline">
              <div className="stat-main">
                <span className="stat-number">{computers.filter(c => c.status === 'offline').length}</span>
                <span className="stat-label">Offline</span>
              </div>
              <div className="stat-icon">🔴</div>
            </div>

            <div className="stat-card security">
              <div className="stat-main">
                <span className="stat-number">
                  {stats ? stats.total_sysmon_events.toLocaleString() : "0"}
                </span>
                <span className="stat-label">Sysmon Events</span>
              </div>
              <div className="stat-badge">24h</div>
            </div>

            <div className="stat-card alerts">
              <div className="stat-main">
                <span className="stat-number">
                  {stats ? stats.security_alerts || 0 : "0"}
                </span>
                <span className="stat-label">Alerts</span>
              </div>
              <div className="stat-icon">🚨</div>
            </div>
          </div>
        </section>

        {/* Main Dashboard */}
        <div className="dashboard-grid">
          {/* Left Sidebar - Filters */}
          <aside className="filter-sidebar">
            <div className="filter-section">
              <h3>Filters</h3>
              <div className="filter-group">
                <label>Status</label>
                <div className="filter-tags">
                  {["all", "online", "idle", "offline"].map(status => (
                    <button
                      key={status}
                      className={`filter-tag ${filters.status === status ? 'active' : ''}`}
                      onClick={() => setFilters({...filters, status})}
                    >
                      {status === 'all' ? 'All' : status}
                    </button>
                  ))}
                </div>
              </div>

              <div className="filter-group">
                <label>Operating System</label>
                <select
                  value={filters.os}
                  onChange={(e) => setFilters({...filters, os: e.target.value})}
                  className="filter-select"
                >
                  <option value="all">All OS</option>
                  {[...new Set(computers.map(c => c.os).filter(Boolean))].map(os => (
                    <option key={os} value={os}>{os}</option>
                  ))}
                </select>
              </div>

              <div className="filter-group">
                <label>CPU Usage ≥ {filters.minCpu}%</label>
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={filters.minCpu}
                  onChange={(e) => setFilters({...filters, minCpu: parseInt(e.target.value)})}
                  className="range-slider"
                />
              </div>

              <div className="filter-group">
                <label>RAM Usage ≥ {filters.minRam}%</label>
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={filters.minRam}
                  onChange={(e) => setFilters({...filters, minRam: parseInt(e.target.value)})}
                  className="range-slider"
                />
              </div>

              <button onClick={resetFilters} className="reset-filters-btn">
                Reset Filters
              </button>
            </div>

            <div className="filter-section">
              <h3>Quick Actions</h3>
              <button className="action-btn" onClick={loadComputers}>
                <span className="action-icon">↻</span>
                Refresh Data
              </button>
              <button className="action-btn" onClick={() => setIsChatOpen(true)}>
                <span className="action-icon">🤖</span>
                Open AI Assistant
              </button>
            </div>
          </aside>

          {/* Main Content Area */}
          <div className="content-area">
            <div className="content-header">
              <div>
                <h2>Network Devices</h2>
                <p className="content-subtitle">{filteredComputers.length} devices found</p>
              </div>
              <div className="header-actions">
                <select className="sort-select">
                  <option>Last Seen</option>
                  <option>Name</option>
                  <option>CPU Usage</option>
                  <option>Status</option>
                </select>
              </div>
            </div>

            {/* Devices Grid */}
            <div className="devices-grid">
              {filteredComputers.map((c) => (
                <div
                  key={c.name}
                  className={`device-card ${c.status}`}
                  onClick={() => openComputer(c.name)}
                >
                  <div className="device-header">
                    <div className="device-title">
                      <div className="device-avatar">
                        {c.os?.includes("Windows") ? "🪟" :
                         c.os?.includes("Linux") ? "🐧" :
                         c.os?.includes("Mac") ? "🍎" : "💻"}
                      </div>
                      <div>
                        <h3>{c.name}</h3>
                        <p className="device-user">{c.user || "Unknown"}</p>
                      </div>
                    </div>
                    <div className={`status-indicator ${c.status}`}>
                      <div className="status-dot"></div>
                      {c.status}
                    </div>
                  </div>

                  <div className="device-info">
                    <div className="info-row">
                      <span className="info-label">IP</span>
                      <span className="info-value">{c.ip}</span>
                    </div>
                    <div className="info-row">
                      <span className="info-label">OS</span>
                      <span className="info-value">{c.os}</span>
                    </div>
                    <div className="info-row">
                      <span className="info-label">Last Active</span>
                      <span className="info-value">{formatTime(c.last_seen)}</span>
                    </div>
                  </div>

                  <div className="device-metrics">
                    <div className="metric">
                      <div className="metric-header">
                        <span>CPU</span>
                        <span className="metric-value">{c.avg_cpu || 0}%</span>
                      </div>
                      <div className="progress-bar">
                        <div
                          className="progress-fill cpu"
                          style={{ width: `${Math.min(c.avg_cpu || 0, 100)}%` }}
                        ></div>
                      </div>
                    </div>
                    <div className="metric">
                      <div className="metric-header">
                        <span>Memory</span>
                        <span className="metric-value">{c.avg_ram || 0}%</span>
                      </div>
                      <div className="progress-bar">
                        <div
                          className="progress-fill memory"
                          style={{ width: `${Math.min(c.avg_ram || 0, 100)}%` }}
                        ></div>
                      </div>
                    </div>
                  </div>

                  <div className="device-footer">
                    {c.sysmon_available && (
                      <div className="sysmon-badge">
                        <span className="sysmon-icon">🛡️</span>
                        {c.recent_sysmon || 0} events
                      </div>
                    )}
                  </div>
                </div>
              ))}

              {filteredComputers.length === 0 && (
                <div className="empty-state">
                  <div className="empty-icon">🔍</div>
                  <h3>No devices match your filters</h3>
                  <button onClick={resetFilters} className="empty-action-btn">
                    Reset All Filters
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </main>

      {/* AI Assistant Sidebar */}
      <div className={`ai-sidebar ${isChatOpen ? 'open' : ''}`}>
        <div className="ai-header">
          <div className="ai-title">
            <div className="ai-avatar">🤖</div>
            <div>
              <h3>Security AI Assistant</h3>
              <p className="ai-subtitle">Powered by LAN Sentinel</p>
            </div>
          </div>
          <button className="close-ai" onClick={() => setIsChatOpen(false)}>
            ✕
          </button>
        </div>

        <div className="ai-content">
          <div className="chat-container">
            <div className="chat-history">
              {showWelcome && (
                <div className="welcome-message">
                  <div className="welcome-avatar">🤖</div>
                  <div className="welcome-content">
                    <h4>Welcome to Security AI Assistant!</h4>
                    <p>I can help you analyze security events, monitor network activity, and investigate incidents.</p>
                    <div className="welcome-questions">
                      {quickQuestions.map((q, idx) => (
                        <button
                          key={idx}
                          className="quick-question"
                          onClick={() => {
                            setChatQuestion(q);
                            setTimeout(() => askAssistant(), 100);
                          }}
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {chatHistory.map((msg, idx) => (
                <div key={idx} className={`chat-message ${msg.type}`}>
                  <div className="message-avatar">
                    {msg.type === 'question' ? '👤' : '🤖'}
                  </div>
                  <div className="message-content">
                    <div className="message-header">
                      <span className="message-sender">
                        {msg.type === 'question' ? 'You' : 'Security AI'}
                      </span>
                      {msg.computer && (
                        <span className="message-context">
                          Computer: {msg.computer}
                        </span>
                      )}
                    </div>
                    <div className="message-text">
                      {msg.content}
                    </div>
                    <div className="message-time">
                      {new Date(msg.timestamp).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </div>
                </div>
              ))}

              {chatLoading && (
                <div className="chat-message answer">
                  <div className="message-avatar">🤖</div>
                  <div className="message-content">
                    <div className="typing-indicator">
                      <div></div>
                      <div></div>
                      <div></div>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="chat-input-area">
              <select
                value={chatComputer}
                onChange={(e) => setChatComputer(e.target.value)}
                className="chat-select"
              >
                <option value="">🌐 All Network</option>
                {computers.map((c) => (
                  <option key={c.name} value={c.name}>
                    {c.name}
                  </option>
                ))}
              </select>

              <div className="input-wrapper">
                <input
                  type="text"
                  placeholder="Ask about security events..."
                  value={chatQuestion}
                  onChange={(e) => setChatQuestion(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && askAssistant()}
                  className="chat-input"
                />
                <button
                  onClick={askAssistant}
                  disabled={chatLoading || !chatQuestion.trim()}
                  className="send-btn"
                >
                  {chatLoading ? '...' : '➤'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Enhanced Computer Details Modal */}
      {selectedComputer && (
        <div className="modal-overlay" onClick={closeModal}>
          <div className="modal large" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <div className="modal-title">
                <h2>{selectedComputer}</h2>
                <div className="modal-subtitle">
                  <span className="ip-badge">{computerDetails?.computer?.ip}</span>
                  <span className="os-badge">{computerDetails?.computer?.os}</span>
                  <span className={`status-badge ${computerDetails?.computer?.status}`}>
                    {computerDetails?.computer?.status}
                  </span>
                </div>
              </div>
              <div className="modal-actions">
                <button className="modal-btn">
                  <span className="btn-icon">📊</span>
                  Report
                </button>
                <button className="modal-close" onClick={closeModal}>
                  ✕
                </button>
              </div>
            </div>

            <div className="modal-content">
              {loadingDetails ? (
                <div className="loading-state">
                  <div className="loader"></div>
                  <p>Loading device details...</p>
                </div>
              ) : (
                <>
                  {/* Quick Stats */}
                  <div className="quick-stats">
                    <div className="quick-stat">
                      <div className="stat-icon">⚡</div>
                      <div className="stat-info">
                        <div className="stat-value">
                          {computerDetails?.current_metrics?.cpu_usage || 0}%
                        </div>
                        <div className="stat-label">CPU</div>
                      </div>
                    </div>
                    <div className="quick-stat">
                      <div className="stat-icon">💾</div>
                      <div className="stat-info">
                        <div className="stat-value">
                          {computerDetails?.current_metrics?.ram_usage || 0}%
                        </div>
                        <div className="stat-label">RAM</div>
                      </div>
                    </div>
                    <div className="quick-stat">
                      <div className="stat-icon">📡</div>
                      <div className="stat-info">
                        <div className="stat-value">
                          {computerDetails?.current_metrics?.network_usage || 0}%
                        </div>
                        <div className="stat-label">Network</div>
                      </div>
                    </div>
                    <div className="quick-stat">
                      <div className="stat-icon">🛡️</div>
                      <div className="stat-info">
                        <div className="stat-value">
                          {computerDetails?.recent_sysmon || 0}
                        </div>
                        <div className="stat-label">Sysmon Events</div>
                      </div>
                    </div>
                  </div>

                  {/* Tabs */}
                  <div className="modal-tabs">
                    <div className="tabs-header">
                      <button
                        className={`tab ${activeTab === 'security' ? 'active' : ''}`}
                        onClick={() => setActiveTab('security')}
                      >
                        Security Events
                      </button>
                      <button
                        className={`tab ${activeTab === 'sysmon' ? 'active' : ''}`}
                        onClick={() => {
                          setActiveTab('sysmon');
                          if (!sysmonData) loadSysmonProcesses();
                        }}
                      >
                        Sysmon Processes
                      </button>
                      <button
                        className={`tab ${activeTab === 'network' ? 'active' : ''}`}
                        onClick={() => {
                          setActiveTab('network');
                          if (!networkData) loadNetworkConnections();
                        }}
                      >
                        Network Connections
                      </button>
                      <button
                        className={`tab ${activeTab === 'details' ? 'active' : ''}`}
                        onClick={() => setActiveTab('details')}
                      >
                        System Details
                      </button>
                    </div>

                    <div className="tabs-content">
                      {/* Security Events Tab */}
                      {activeTab === 'security' && (
                        <div className="tab-pane active">
                          <div className="data-table-container">
                            <table className="data-table">
                              <thead>
                                <tr>
                                  <th>Time</th>
                                  <th>Event ID</th>
                                  <th>Type</th>
                                  <th>Description</th>
                                </tr>
                              </thead>
                              <tbody>
                                {(computerDetails?.sysmon_events || []).map((ev, idx) => (
                                  <tr key={idx}>
                                    <td>{formatTime(ev.timestamp)}</td>
                                    <td>
                                      <span className="event-id">#{ev.event_id}</span>
                                    </td>
                                    <td>
                                      <span className={`event-type ${ev.event_type?.toLowerCase()}`}>
                                        {ev.event_type}
                                      </span>
                                    </td>
                                    <td className="event-desc">
                                      {ev.message?.slice(0, 100) || 'No description'}
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      )}

                      {/* Sysmon Processes Tab */}
                      {activeTab === 'sysmon' && (
                        <div className="tab-pane active">
                          <div className="pane-header">
                            <h3>Sysmon Processes</h3>
                            <button
                              onClick={loadSysmonProcesses}
                              className="refresh-btn-small"
                              disabled={loadingSysmon}
                            >
                              {loadingSysmon ? 'Loading...' : '↻ Refresh'}
                            </button>
                          </div>

                          {loadingSysmon ? (
                            <div className="loading-state">
                              <div className="loader"></div>
                              <p>Loading Sysmon processes...</p>
                            </div>
                          ) : sysmonData ? (
                            <div className="data-grid">
                              <div className="grid-container">
                                {sysmonData.processes && sysmonData.processes.length > 0 ? (
                                  <>
                                    <div className="grid-sidebar">
                                      <div className="process-list">
                                        {sysmonData.processes.map((proc, idx) => (
                                          <div
                                            key={idx}
                                            className={`process-item ${selectedSysmonProcess === idx ? 'active' : ''}`}
                                            onClick={() => setSelectedSysmonProcess(idx)}
                                          >
                                            <div className="process-name">
                                              <strong>{proc.process_name || 'Unknown'}</strong>
                                            </div>
                                            <div className="process-pid">
                                              PID: {proc.process_id}
                                            </div>
                                            <div className="process-time">
                                              {formatTime(proc.timestamp)}
                                            </div>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                    <div className="grid-content">
                                      {selectedSysmonProcess !== null ? (
                                        <div className="json-viewer">
                                          <div className="json-header">
                                            <h4>Process Details (JSON)</h4>
                                            <button
                                              className="copy-json"
                                              onClick={() => navigator.clipboard.writeText(
                                                JSON.stringify(sysmonData.processes[selectedSysmonProcess], null, 2)
                                              )}
                                            >
                                              📋 Copy JSON
                                            </button>
                                          </div>
                                          <pre className="json-content">
                                            {JSON.stringify(sysmonData.processes[selectedSysmonProcess], null, 2)}
                                          </pre>
                                        </div>
                                      ) : (
                                        <div className="select-prompt">
                                          <div className="prompt-icon">👈</div>
                                          <p>Select a process from the list to view its JSON data</p>
                                        </div>
                                      )}
                                    </div>
                                  </>
                                ) : (
                                  <div className="empty-data">
                                    <div className="empty-icon">📄</div>
                                    <p>No Sysmon processes found</p>
                                  </div>
                                )}
                              </div>
                            </div>
                          ) : (
                            <div className="empty-data">
                              <p>Click refresh to load Sysmon processes</p>
                              <button onClick={loadSysmonProcesses} className="load-btn">
                                Load Sysmon Data
                              </button>
                            </div>
                          )}
                        </div>
                      )}

                      {/* Network Connections Tab */}
                      {activeTab === 'network' && (
                        <div className="tab-pane active">
                          <div className="pane-header">
                            <h3>Network Connections</h3>
                            <button
                              onClick={loadNetworkConnections}
                              className="refresh-btn-small"
                              disabled={loadingNetwork}
                            >
                              {loadingNetwork ? 'Loading...' : '↻ Refresh'}
                            </button>
                          </div>

                          {loadingNetwork ? (
                            <div className="loading-state">
                              <div className="loader"></div>
                              <p>Loading network connections...</p>
                            </div>
                          ) : networkData ? (
                            <div className="data-grid">
                              <div className="grid-container">
                                {networkData.connections && networkData.connections.length > 0 ? (
                                  <>
                                    <div className="grid-sidebar">
                                      <div className="network-list">
                                        {networkData.connections.map((conn, idx) => (
                                          <div
                                            key={idx}
                                            className={`network-item ${selectedNetworkItem === idx ? 'active' : ''}`}
                                            onClick={() => setSelectedNetworkItem(idx)}
                                          >
                                            <div className="network-address">
                                              <strong>{conn.local_address}:{conn.local_port}</strong>
                                              <div className="arrow">→</div>
                                              <strong>{conn.remote_address}:{conn.remote_port}</strong>
                                            </div>
                                            <div className="network-protocol">
                                              {conn.protocol} • {conn.state}
                                            </div>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                    <div className="grid-content">
                                      {selectedNetworkItem !== null ? (
                                        <div className="json-viewer">
                                          <div className="json-header">
                                            <h4>Connection Details (JSON)</h4>
                                            <button
                                              className="copy-json"
                                              onClick={() => navigator.clipboard.writeText(
                                                JSON.stringify(networkData.connections[selectedNetworkItem], null, 2)
                                              )}
                                            >
                                              📋 Copy JSON
                                            </button>
                                          </div>
                                          <pre className="json-content">
                                            {JSON.stringify(networkData.connections[selectedNetworkItem], null, 2)}
                                          </pre>
                                        </div>
                                      ) : (
                                        <div className="select-prompt">
                                          <div className="prompt-icon">👈</div>
                                          <p>Select a connection to view its JSON data</p>
                                        </div>
                                      )}
                                    </div>
                                  </>
                                ) : (
                                  <div className="empty-data">
                                    <div className="empty-icon">🌐</div>
                                    <p>No network connections found</p>
                                  </div>
                                )}
                              </div>
                            </div>
                          ) : (
                            <div className="empty-data">
                              <p>Click refresh to load network connections</p>
                              <button onClick={loadNetworkConnections} className="load-btn">
                                Load Network Data
                              </button>
                            </div>
                          )}
                        </div>
                      )}

                      {/* System Details Tab */}
                      {activeTab === 'details' && computerDetails && (
                        <div className="tab-pane active">
                          <div className="details-grid">
                            <div className="detail-group">
                              <h4>System Information</h4>
                              <div className="detail-item">
                                <span className="detail-label">Hostname:</span>
                                <span className="detail-value">{computerDetails.computer.name}</span>
                              </div>
                              <div className="detail-item">
                                <span className="detail-label">IP Address:</span>
                                <span className="detail-value">{computerDetails.computer.ip}</span>
                              </div>
                              <div className="detail-item">
                                <span className="detail-label">OS Version:</span>
                                <span className="detail-value">{computerDetails.computer.os}</span>
                              </div>
                              <div className="detail-item">
                                <span className="detail-label">Last Seen:</span>
                                <span className="detail-value">{formatTime(computerDetails.computer.last_seen)}</span>
                              </div>
                            </div>

                            <div className="detail-group">
                              <h4>Current Metrics</h4>
                              <div className="detail-item">
                                <span className="detail-label">CPU Usage:</span>
                                <span className="detail-value">{computerDetails.current_metrics?.cpu_usage || 0}%</span>
                              </div>
                              <div className="detail-item">
                                <span className="detail-label">Memory Usage:</span>
                                <span className="detail-value">{computerDetails.current_metrics?.ram_usage || 0}%</span>
                              </div>
                              <div className="detail-item">
                                <span className="detail-label">Disk Usage:</span>
                                <span className="detail-value">{computerDetails.current_metrics?.disk_usage || 0}%</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default App;