'use client';
import React, { useEffect, useState } from 'react';

interface PostStats {
  slug: string;
  cache_hits: number;
  cache_misses: number;
  last_interpret_time_ms: number;
  last_compile_time_ms: number;
}

interface HealthReport {
  posts_dir_exists: boolean;
  posts_count: number;
  cache_file_exists: boolean;
  cache_stats_file_exists: boolean;
  cache_readable: boolean;
  cache_stats_readable: boolean;
  cache_post_count?: number;
  cache_stats_count?: number;
  errors: string[];
}

interface LogEntry {
  timestamp: string;
  level: string;
  message: string;
  slug?: string;
  details?: string;
}

export default function RustStatusPage() {
  const [stats, setStats] = useState<PostStats[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [health, setHealth] = useState<HealthReport | null>(null);
  const [healthLoading, setHealthLoading] = useState(true);
  const [healthError, setHealthError] = useState<string | null>(null);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [logsLoading, setLogsLoading] = useState(true);
  const [logsError, setLogsError] = useState<string | null>(null);
  const [logFilter, setLogFilter] = useState<string>('all'); // 'all', 'info', 'warning', 'error'
  const [logSearch, setLogSearch] = useState<string>('');

  // Summary calculations
  const totalHits = stats.reduce((sum, s) => sum + s.cache_hits, 0);
  const totalMisses = stats.reduce((sum, s) => sum + s.cache_misses, 0);
  const avgInterpret = stats.length ? (stats.reduce((sum, s) => sum + s.last_interpret_time_ms, 0) / stats.length).toFixed(1) : 0;
  const avgCompile = stats.length ? (stats.reduce((sum, s) => sum + s.last_compile_time_ms, 0) / stats.length).toFixed(1) : 0;

  const fetchStats = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/admin/posts?rsparseinfo=1');
      if (!res.ok) throw new Error('Fehler beim Laden der Statistiken');
      const data = await res.json();
      setStats(data);
    } catch (e: any) {
      setError(e.message || 'Unbekannter Fehler');
    } finally {
      setLoading(false);
    }
  };

  const fetchHealth = async () => {
    setHealthLoading(true);
    setHealthError(null);
    try {
      const res = await fetch('/api/admin/posts?checkhealth=1');
      if (!res.ok) throw new Error('Fehler beim Laden des Health-Checks');
      const data = await res.json();
      setHealth(data);
    } catch (e: any) {
      setHealthError(e.message || 'Unbekannter Fehler');
    } finally {
      setHealthLoading(false);
    }
  };

  const fetchLogs = async () => {
    setLogsLoading(true);
    setLogsError(null);
    try {
      const res = await fetch('/api/admin/posts?logs=1');
      if (!res.ok) throw new Error('Fehler beim Laden der Logs');
      const data = await res.json();
      setLogs(data);
    } catch (e: any) {
      setLogsError(e.message || 'Unbekannter Fehler');
    } finally {
      setLogsLoading(false);
    }
  };

  const clearLogs = async () => {
    try {
      const res = await fetch('/api/admin/posts?clearLogs=1', { method: 'DELETE' });
      if (!res.ok) throw new Error('Fehler beim Löschen der Logs');
      await fetchLogs(); // Refresh logs after clearing
    } catch (e: any) {
      console.error('Error clearing logs:', e);
    }
  };

  useEffect(() => {
    fetchStats();
    fetchHealth();
    fetchLogs();
  }, []);

  // Filter logs based on level and search term
  const filteredLogs = logs.filter(log => {
    const matchesLevel = logFilter === 'all' || log.level === logFilter;
    const matchesSearch = !logSearch || 
      log.message.toLowerCase().includes(logSearch.toLowerCase()) ||
      (log.slug && log.slug.toLowerCase().includes(logSearch.toLowerCase())) ||
      (log.details && log.details.toLowerCase().includes(logSearch.toLowerCase()));
    return matchesLevel && matchesSearch;
  });

  const getLevelColor = (level: string) => {
    switch (level) {
      case 'error': return 'text-red-600 bg-red-50';
      case 'warning': return 'text-yellow-600 bg-yellow-50';
      case 'info': return 'text-blue-600 bg-blue-50';
      default: return 'text-gray-600 bg-gray-50';
    }
  };

  const getLevelIcon = (level: string) => {
    switch (level) {
      case 'error': 
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
          </svg>
        );
      case 'warning': 
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
          </svg>
        );
      case 'info': 
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
          </svg>
        );
      default: 
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M4 4a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2H4zm0 2h12v8H4V6zm2 2a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm0 3a1 1 0 011-1h4a1 1 0 110 2H7a1 1 0 01-1-1z" clipRule="evenodd" />
          </svg>
        );
    }
  };

  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4 sm:p-6">
      <div className="w-full max-w-6xl">
        {/* Header with title and action buttons */}
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-4">
          <div className="flex items-center gap-2">
            <div className="bg-white rounded-lg shadow-sm p-1.5 flex items-center justify-center">
              <img 
                className="w-8 h-8 sm:w-10 sm:h-10" 
                src="https://upload.wikimedia.org/wikipedia/commons/d/d5/Rust_programming_language_black_logo.svg" 
                alt="Rust Logo" 
              />
            </div>
            <h1 className="text-lg sm:text-xl font-bold">Rust-Parser Statistiken</h1>
          </div>
          
          <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
            {/* Back to Admin button */}
            <a
              href="/admin"
              className="p-1.5 sm:px-3 sm:py-1.5 bg-gray-200 hover:bg-gray-300 rounded-lg shadow-sm flex items-center gap-1 transition-colors text-sm"
              title="Zurück zur Admin-Panel"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              <span className="hidden sm:inline">Zurück</span>
            </a>
            
            {/* Refresh button */}
            <button
              onClick={() => {
                fetchStats();
                fetchHealth();
                fetchLogs();
              }}
              className="p-1.5 sm:px-3 sm:py-1.5 bg-blue-500 hover:bg-blue-600 text-white rounded-lg shadow-sm flex items-center gap-1 transition-colors text-sm"
              title="Aktualisieren"
              disabled={loading || healthLoading || logsLoading}
            >
              <svg
                className={`w-4 h-4 ${(loading || healthLoading || logsLoading) ? 'animate-spin' : ''}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              <span className="hidden sm:inline">Aktualisieren</span>
            </button>
          </div>
        </div>

        {/* Health Check Section */}
        <div className="mb-4">
          <h2 className="text-sm sm:text-base font-semibold mb-2 text-center">Health-Check</h2>
          {healthLoading && <div className="text-center py-3 text-sm">Lade Health-Check...</div>}
          {healthError && <div className="text-red-500 text-center text-sm">{healthError}</div>}
          {health && (
            <div className="bg-gradient-to-br from-gray-50 to-white rounded-lg shadow-sm border border-gray-200 p-4 flex flex-col gap-3 items-center">
              <div className="flex flex-wrap gap-4 justify-center">
                <div className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    health.posts_dir_exists ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'
                  }`}>
                    {health.posts_dir_exists ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Posts-Verzeichnis</span>
                </div>
                <div className="flex flex-col items-center">
                  <div className="w-8 h-8 rounded-full bg-blue-200 text-blue-700 flex items-center justify-center">
                    <span className="text-sm font-bold">{health.posts_count}</span>
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Posts</span>
                </div>
                <div className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    health.cache_file_exists ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'
                  }`}>
                    {health.cache_file_exists ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Cache-Datei</span>
                </div>
                <div className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    health.cache_stats_file_exists ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'
                  }`}>
                    {health.cache_stats_file_exists ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Cache-Stats</span>
                </div>
                <div className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    health.cache_readable ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'
                  }`}>
                    {health.cache_readable ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Cache lesbar</span>
                </div>
                <div className="flex flex-col items-center">
                  <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                    health.cache_stats_readable ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'
                  }`}>
                    {health.cache_stats_readable ? (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                  <span className="text-xs text-gray-600 mt-1 font-medium">Stats lesbar</span>
                </div>
                {typeof health.cache_post_count === 'number' && (
                  <div className="flex flex-col items-center">
                    <div className="w-8 h-8 rounded-full bg-blue-200 text-blue-700 flex items-center justify-center">
                      <span className="text-sm font-bold">{health.cache_post_count}</span>
                    </div>
                    <span className="text-xs text-gray-600 mt-1 font-medium">Cache-Posts</span>
                  </div>
                )}
                {typeof health.cache_stats_count === 'number' && (
                  <div className="flex flex-col items-center">
                    <div className="w-8 h-8 rounded-full bg-blue-200 text-blue-700 flex items-center justify-center">
                      <span className="text-sm font-bold">{health.cache_stats_count}</span>
                    </div>
                    <span className="text-xs text-gray-600 mt-1 font-medium">Stats-Einträge</span>
                  </div>
                )}
              </div>
              {health.errors.length > 0 && (
                <div className="mt-3 text-red-600 text-xs text-center bg-red-50 p-3 rounded-md border border-red-200">
                  <b>Fehler:</b>
                  <ul className="list-disc ml-5 inline-block text-left">
                    {health.errors.map((err, i) => <li key={i}>{err}</li>)}
                  </ul>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Summary Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-4">
          <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-3 flex flex-col items-center shadow-sm border border-green-200">
            <span className="text-lg sm:text-xl font-bold text-green-700">{totalHits}</span>
            <span className="text-xs sm:text-sm text-gray-700 mt-1 text-center font-medium">Cache-Treffer</span>
          </div>
          <div className="bg-gradient-to-br from-red-50 to-red-100 rounded-lg p-3 flex flex-col items-center shadow-sm border border-red-200">
            <span className="text-lg sm:text-xl font-bold text-red-700">{totalMisses}</span>
            <span className="text-xs sm:text-sm text-gray-700 mt-1 text-center font-medium">Cache-Fehlschläge</span>
          </div>
          <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-3 flex flex-col items-center shadow-sm border border-blue-200">
            <span className="text-lg sm:text-xl font-bold text-blue-700">{avgInterpret} ms</span>
            <span className="text-xs sm:text-sm text-gray-700 mt-1 text-center font-medium">Ø Interpretationszeit</span>
          </div>
          <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-3 flex flex-col items-center shadow-sm border border-purple-200">
            <span className="text-lg sm:text-xl font-bold text-purple-700">{avgCompile} ms</span>
            <span className="text-xs sm:text-sm text-gray-700 mt-1 text-center font-medium">Ø Kompilierzeit</span>
          </div>
        </div>

        {/* Parser Logs Section */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
            <h2 className="text-base font-semibold">Parser Logs</h2>
            <div className="flex flex-col sm:flex-row gap-2">
              <button
                onClick={clearLogs}
                className="px-2.5 py-1.5 bg-red-500 hover:bg-red-600 text-white rounded text-xs transition-colors"
                title="Clear all logs"
              >
                Clear Logs
              </button>
            </div>
          </div>

          {/* Log Filters */}
          <div className="flex flex-col sm:flex-row gap-3 mb-3">
            <div className="flex-1">
              <input
                type="text"
                placeholder="Search logs..."
                value={logSearch}
                onChange={(e) => setLogSearch(e.target.value)}
                className="w-full px-3 py-1.5 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
              />
            </div>
            <div className="flex gap-2">
              <select
                value={logFilter}
                onChange={(e) => setLogFilter(e.target.value)}
                className="px-3 py-1.5 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
              >
                <option value="all">All Levels</option>
                <option value="info">Info</option>
                <option value="warning">Warning</option>
                <option value="error">Error</option>
              </select>
            </div>
          </div>

          {/* Logs Display */}
          <div className="max-h-80 overflow-y-auto">
            {logsLoading && <div className="text-center py-3 text-sm">Loading logs...</div>}
            {logsError && <div className="text-red-500 text-center py-3 text-sm">{logsError}</div>}
            {!logsLoading && !logsError && (
              <div className="space-y-2">
                {filteredLogs.length === 0 ? (
                  <div className="text-center py-3 text-gray-500 text-sm">No logs found</div>
                ) : (
                  filteredLogs.map((log, index) => (
                    <div key={index} className={`p-3 rounded-lg border-l-4 shadow-sm ${
                      log.level === 'error' ? 'bg-gradient-to-r from-red-50 to-red-100 border-red-400' :
                      log.level === 'warning' ? 'bg-gradient-to-r from-yellow-50 to-yellow-100 border-yellow-400' :
                      'bg-gradient-to-r from-blue-50 to-blue-100 border-blue-400'
                    }`}>
                      <div className="flex items-start gap-2">
                        <div className={`flex-shrink-0 p-1 rounded-full ${
                          log.level === 'error' ? 'bg-red-200 text-red-700' :
                          log.level === 'warning' ? 'bg-yellow-200 text-yellow-700' :
                          'bg-blue-200 text-blue-700'
                        }`}>
                          {getLevelIcon(log.level)}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="text-xs font-mono text-gray-600 tracking-wide">
                              {new Date(log.timestamp).toLocaleString('en-US', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                                hour12: false
                              })}
                            </span>
                            <span className={`px-2 py-0.5 rounded-full text-xs font-semibold tracking-wide ${
                              log.level === 'error' ? 'bg-red-200 text-red-800' :
                              log.level === 'warning' ? 'bg-yellow-200 text-yellow-800' :
                              'bg-blue-200 text-blue-800'
                            }`}>
                              {log.level.toUpperCase()}
                            </span>
                            {log.slug && (
                              <span className="px-2 py-0.5 bg-gray-200 text-gray-700 rounded-full text-xs font-mono tracking-wide">
                                {log.slug}
                              </span>
                            )}
                          </div>
                          <div className="text-sm font-medium text-gray-900 leading-relaxed">{log.message}</div>
                          {log.details && (
                            <div className="text-xs text-gray-600 mt-1 font-mono bg-gray-50 p-2 rounded-md border border-gray-200 leading-relaxed">
                              {log.details}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </div>
            )}
          </div>
        </div>

        {/* Table */}
        <div className="bg-white rounded-lg shadow-sm p-3 sm:p-4 overflow-x-auto">
          <h2 className="text-sm sm:text-base font-semibold mb-2">Rohdaten</h2>
          {loading && <div className="text-center py-4 text-sm">Lade Statistiken...</div>}
          {error && <div className="text-red-500 text-center text-sm">{error}</div>}
          {!loading && !error && (
            <div className="overflow-x-auto">
              <table className="min-w-full border border-gray-200 bg-white rounded text-sm">
                <thead>
                  <tr className="bg-gray-100">
                    <th className="px-2 py-1.5 text-left text-xs">Slug</th>
                    <th className="px-2 py-1.5 text-right text-xs">Cache-Treffer</th>
                    <th className="px-2 py-1.5 text-right text-xs">Cache-Fehlschläge</th>
                    <th className="px-2 py-1.5 text-right text-xs">Interpret (ms)</th>
                    <th className="px-2 py-1.5 text-right text-xs">Kompilier (ms)</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.length === 0 ? (
                    <tr><td colSpan={5} className="text-center py-2 text-xs">Keine Statistiken verfügbar.</td></tr>
                  ) : (
                    stats.map(stat => (
                      <tr key={stat.slug} className="border-t border-gray-200">
                        <td className="px-2 py-1.5 font-mono text-xs">{stat.slug}</td>
                        <td className="px-2 py-1.5 text-right text-xs">{stat.cache_hits}</td>
                        <td className="px-2 py-1.5 text-right text-xs">{stat.cache_misses}</td>
                        <td className="px-2 py-1.5 text-right text-xs">{stat.last_interpret_time_ms}</td>
                        <td className="px-2 py-1.5 text-right text-xs">{stat.last_compile_time_ms}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}