// Real-Time System Status & Diagnostic Monitor Component
window.StatusPage = function StatusPage({ user, showToast }) {
  const [statusData, setStatusData] = React.useState(null);
  const [latency, setLatency] = React.useState(0);
  const [isAutoRefresh, setIsAutoRefresh] = React.useState(true);
  const [lastUpdated, setLastUpdated] = React.useState(null);
  const [loading, setLoading] = React.useState(false);

  const fetchStatus = async () => {
    const startTime = performance.now();
    try {
      const res = await fetch('/api/system/status', {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const endTime = performance.now();
      const roundTrip = Math.round(endTime - startTime);
      setLatency(roundTrip);

      const data = await res.json();
      if (data.success) {
        setStatusData(data);
        setLastUpdated(new Date());
      }
    } catch (err) {
      console.error('Status fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchStatus();
    if (!isAutoRefresh) return;
    const interval = setInterval(fetchStatus, 2000);
    return () => clearInterval(interval);
  }, [isAutoRefresh]);

  const formatUptime = (seconds) => {
    if (!seconds) return '0s';
    const d = Math.floor(seconds / (3600 * 24));
    const h = Math.floor((seconds % (3600 * 24)) / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = Math.floor(seconds % 60);
    const parts = [];
    if (d > 0) parts.push(`${d}d`);
    if (h > 0 || d > 0) parts.push(`${h}h`);
    if (m > 0 || h > 0 || d > 0) parts.push(`${m}m`);
    parts.push(`${s}s`);
    return parts.join(' ');
  };

  const s = statusData?.server || {};
  const p = statusData?.performance || {};
  const d = statusData?.database || {};
  const sec = statusData?.security || {};

  return (
    <div className="space-y-6 animate-card-in">
      {/* Top Header & Live Control Bar */}
      <div className="p-4 sm:p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div className="min-w-0">
          <div className="flex items-center gap-2.5">
            <span className="live-ping-dot"></span>
            <h2 className="text-xl font-bold text-white font-brand">
              RealTime System & Service Monitor
            </h2>
          </div>
          <p className="text-xs text-slate-400 mt-1 font-mono">
            สถานะเซิร์ฟเวอร์, ความหน่วงเครือข่าย, ปริมาณการใช้งาน RAM/CPU และฐานข้อมูลแบบเรียลไทม์
          </p>
        </div>

        <div className="flex items-center gap-2.5 w-full md:w-auto font-mono text-xs">
          {/* Latency badge */}
          <div className="flex items-center gap-1.5 px-3 py-1.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300">
            <i className="fa-solid fa-gauge-high text-cyan-400 text-xs"></i>
            <span>PING: <strong className={latency < 60 ? 'text-[#00FF9D]' : latency < 150 ? 'text-amber-400' : 'text-rose-400'}>{latency}ms</strong></span>
          </div>

          {/* Auto refresh toggle */}
          <button
            onClick={() => setIsAutoRefresh(!isAutoRefresh)}
            className={`px-3 py-1.5 rounded-none border transition flex items-center gap-1.5 ${
              isAutoRefresh
                ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                : 'bg-[#080C14] border-[#1E2D4A] text-slate-400'
            }`}
            title="Toggle 2-second Auto Refresh"
          >
            <i className={`fa-solid ${isAutoRefresh ? 'fa-bolt' : 'fa-pause'} text-xs`}></i>
            <span>{isAutoRefresh ? 'Auto 2s' : 'Paused'}</span>
          </button>

          {/* Manual refresh button */}
          <button
            onClick={() => { setLoading(true); fetchStatus(); }}
            className="p-2 rounded-none bg-[#131D31] hover:bg-[#18243D] border border-[#1E2D4A] text-slate-300 text-xs transition"
            title="Refresh now"
          >
            <i className={`fa-solid fa-rotate-right text-xs ${loading ? 'fa-spin text-cyan-400' : ''}`}></i>
          </button>
        </div>
      </div>

      {/* Row 1: Core Performance Meters */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3.5">
        {/* Node Memory (Heap) */}
        <div className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-2.5 shadow-xl">
          <div className="flex items-center justify-between text-xs font-mono text-slate-400">
            <span className="flex items-center gap-1.5 uppercase">
              <i className="fa-solid fa-memory text-cyan-400"></i>
              <span>NODE HEAP MEMORY</span>
            </span>
            <span className="text-white font-bold">{p.heap_used_mb || 0} MB</span>
          </div>
          <div className="w-full bg-[#080C14] h-2 border border-[#1E2D4A] overflow-hidden">
            <div
              className="bg-gradient-to-r from-blue-600 to-cyan-400 h-full transition-all duration-500"
              style={{ width: `${Math.min(100, Math.round(((p.heap_used_mb || 0) / (p.heap_total_mb || 100)) * 100))}%` }}
            ></div>
          </div>
          <div className="flex justify-between text-[11px] font-mono text-slate-500">
            <span>Allocated: {p.heap_total_mb || 0} MB</span>
            <span>RSS: {p.rss_mb || 0} MB</span>
          </div>
        </div>

        {/* System Total RAM */}
        <div className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-2.5 shadow-xl">
          <div className="flex items-center justify-between text-xs font-mono text-slate-400">
            <span className="flex items-center gap-1.5 uppercase">
              <i className="fa-solid fa-microchip text-purple-400"></i>
              <span>SYSTEM RAM USAGE</span>
            </span>
            <span className="text-white font-bold">{p.used_mem_percent || 0}%</span>
          </div>
          <div className="w-full bg-[#080C14] h-2 border border-[#1E2D4A] overflow-hidden">
            <div
              className={`h-full transition-all duration-500 ${
                (p.used_mem_percent || 0) > 85 ? 'bg-rose-500' : 'bg-purple-500'
              }`}
              style={{ width: `${p.used_mem_percent || 0}%` }}
            ></div>
          </div>
          <div className="flex justify-between text-[11px] font-mono text-slate-500">
            <span>Free: {p.free_mem_mb || 0} MB</span>
            <span>Total: {p.total_mem_mb || 0} MB</span>
          </div>
        </div>

        {/* Server Process Uptime */}
        <div className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-2.5 shadow-xl">
          <div className="flex items-center justify-between text-xs font-mono text-slate-400">
            <span className="flex items-center gap-1.5 uppercase">
              <i className="fa-solid fa-stopwatch text-emerald-400"></i>
              <span>PROCESS UPTIME</span>
            </span>
            <span className="text-[#00FF9D] font-bold">{formatUptime(s.uptime_seconds)}</span>
          </div>
          <div className="text-[11px] text-slate-400 font-mono">
            Host OS Uptime: <span className="text-slate-200">{formatUptime(s.system_uptime_seconds)}</span>
          </div>
          <div className="text-[10px] text-slate-500 font-mono truncate">
            Node {s.node_version} &bull; {s.platform} ({s.arch})
          </div>
        </div>

        {/* Request Throughput */}
        <div className="p-4 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-2.5 shadow-xl">
          <div className="flex items-center justify-between text-xs font-mono text-slate-400">
            <span className="flex items-center gap-1.5 uppercase">
              <i className="fa-solid fa-network-wired text-amber-400"></i>
              <span>THROUGHPUT</span>
            </span>
            <span className="text-amber-400 font-bold">{p.requests_per_minute || 0} req/m</span>
          </div>
          <div className="text-[11px] text-slate-400 font-mono">
            Total Handled: <span className="text-white font-bold">{p.total_requests || 0}</span>
          </div>
          <div className="text-[10px] text-slate-500 font-mono">
            Updated: {lastUpdated ? lastUpdated.toLocaleTimeString() : 'Ready'}
          </div>
        </div>
      </div>

      {/* Row 2: Database RealTime Breakdown */}
      <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-4 shadow-xl">
        <div className="flex items-center justify-between pb-3 border-b border-[#1E2D4A]">
          <div className="flex items-center gap-2 text-xs font-bold text-white font-mono uppercase">
            <i className="fa-solid fa-database text-cyan-400"></i>
            <span>DATABASE METRICS & REALTIME SESSIONS</span>
          </div>
          <span className="text-[11px] font-mono text-emerald-400 flex items-center gap-1.5">
            <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span>
            <span>STORAGE HEALTHY</span>
          </span>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">ONLINE NOW</div>
            <div className="text-xl font-bold text-[#00FF9D] font-brand mt-0.5">{d.online_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">Live heartbeat</div>
          </div>

          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">ACTIVE USERS</div>
            <div className="text-xl font-bold text-cyan-400 font-brand mt-0.5">{d.active_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">In subscription</div>
          </div>

          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">UNUSED KEYS</div>
            <div className="text-xl font-bold text-amber-400 font-brand mt-0.5">{d.unused_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">Ready to activate</div>
          </div>

          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">EXPIRED</div>
            <div className="text-xl font-bold text-slate-400 font-brand mt-0.5">{d.expired_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">Need renewal</div>
          </div>

          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">BANNED</div>
            <div className="text-xl font-bold text-rose-400 font-brand mt-0.5">{d.banned_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">Access revoked</div>
          </div>

          <div className="p-3 bg-[#080C14] border border-[#1E2D4A] text-center min-w-0">
            <div className="text-[10px] font-mono text-slate-400 uppercase">FROZEN</div>
            <div className="text-xl font-bold text-blue-400 font-brand mt-0.5">{d.frozen_users || 0}</div>
            <div className="text-[10px] font-mono text-slate-500">Time paused</div>
          </div>
        </div>
      </div>

      {/* Row 3: Security & Ecosystem Status */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Security Firewall Center */}
        <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-3.5 shadow-xl">
          <div className="flex items-center justify-between pb-3 border-b border-[#1E2D4A]">
            <div className="flex items-center gap-2 text-xs font-bold text-white font-mono uppercase">
              <i className="fa-solid fa-shield-halved text-purple-400"></i>
              <span>SECURITY DEFENSE MATRIX</span>
            </div>
            <span className="text-[10px] font-mono px-2 py-0.5 rounded-none bg-purple-500/10 text-purple-300 border border-purple-500/20">
              PROTECTED
            </span>
          </div>

          <div className="space-y-2 text-xs font-mono">
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">IP Firewall Shield:</span>
              <span className="text-emerald-400 font-bold">{sec.firewall_status || 'ACTIVE'}</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">API Rate Limiter:</span>
              <span className="text-cyan-400 font-bold">{sec.rate_limiter_status || 'ACTIVE'}</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Anti-Sniffing Protocol:</span>
              <span className="text-purple-400 font-bold">{sec.anti_sniffing || 'HMAC-SHA256'}</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Blacklisted Machine HWIDs:</span>
              <span className="text-rose-400 font-bold">{sec.banned_hwids_count || 0} เครื่อง</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Blacklisted IP Addresses:</span>
              <span className="text-rose-400 font-bold">{sec.banned_ips_count || 0} IPs</span>
            </div>
          </div>
        </div>

        {/* Server & Environment Information */}
        <div className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] space-y-3.5 shadow-xl">
          <div className="flex items-center justify-between pb-3 border-b border-[#1E2D4A]">
            <div className="flex items-center gap-2 text-xs font-bold text-white font-mono uppercase">
              <i className="fa-solid fa-server text-blue-400"></i>
              <span>HOST SERVER ARCHITECTURE</span>
            </div>
            <span className="text-[10px] font-mono text-slate-400">HOST: {s.hostname || 'localhost'}</span>
          </div>

          <div className="space-y-2 text-xs font-mono">
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">CPU Architecture:</span>
              <span className="text-white font-bold">{s.cpu_model || 'Standard CPU'} ({s.cpu_cores || 1} Cores)</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Node Runtime:</span>
              <span className="text-cyan-400 font-bold">{s.node_version || 'v24.x'}</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Owner ID (Master):</span>
              <span className="text-amber-400 font-bold font-brand tracking-wider">{s.owner_id || '84920183'}</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Active Applications:</span>
              <span className="text-emerald-400 font-bold">{d.total_apps || 0} แอปพลิเคชัน</span>
            </div>
            <div className="flex items-center justify-between p-2.5 bg-[#080C14] border border-[#1E2D4A]">
              <span className="text-slate-400">Reset HWID Links Active:</span>
              <span className="text-blue-400 font-bold">{d.active_hwid_links || 0} ลิงก์</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
