import { useEffect, useState } from 'react'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip'; import { checkBackendHealth, type HealthStatus, type HealthCheckResult } from '@/services'; import { Circle, Loader2 } from 'lucide-react'; interface HealthIndicatorProps { /** How often to check health in milliseconds (default: 30000 = 30s) */ interval?: number; } function formatRelativeTime(isoString: string): string { const date = new Date(isoString); const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffMins = Math.floor(diffMs / 60000); const diffHours = Math.floor(diffMs / 3600000); const diffDays = Math.floor(diffMs / 86400000); if (diffMins < 1) return 'just now'; if (diffMins < 60) return `${diffMins}m ago`; if (diffHours < 24) return `${diffHours}h ago`; return `${diffDays}d ago`; } export function HealthIndicator({ interval = 30000 }: HealthIndicatorProps) { const [health, setHealth] = useState({ status: 'checking' }); useEffect(() => { // Initial check checkBackendHealth().then(setHealth); // Periodic checks const intervalId = setInterval(() => { checkBackendHealth().then(setHealth); }, interval); return () => clearInterval(intervalId); }, [interval]); const getStatusColor = (status: HealthStatus) => { switch (status) { case 'healthy': return 'text-green-500'; case 'unhealthy': return 'text-red-500'; case 'checking': return 'text-muted-foreground'; } }; const getStatusLabel = (status: HealthStatus) => { switch (status) { case 'healthy': return 'Connected'; case 'unhealthy': return 'Disconnected'; case 'checking': return 'Checking...'; } }; const getTooltipContent = () => { const lines: string[] = []; if (health.status === 'checking') { return 'Checking backend connection...'; } if (health.status === 'healthy') { lines.push(`Backend connected (${health.latencyMs}ms)`); if (health.lastUpdated) { const date = new Date(health.lastUpdated); lines.push(`Last update: ${date.toLocaleString()}`); } return lines.join('\n'); } return `Backend unavailable: ${health.error || 'Unknown error'}`; }; return (
{health.status === 'checking' ? ( ) : ( )} {health.status === 'healthy' && health.lastUpdated && ( ยท {formatRelativeTime(health.lastUpdated)} )}

{getTooltipContent()}

); }