import { useEffect, useRef } from 'react';

/**
 * AutoReload component that polls the server health endpoint.
 * If the server's bootTime changes, it triggers a page reload.
 */
export function AutoReload() {
  const bootTimeRef = useRef<number | null>(null);
  const isInitialLoad = useRef(true);

  useEffect(() => {
    const checkServer = async () => {
      try {
        const response = await fetch('/api/health', {
          headers: { 'Cache-Control': 'no-cache' },
          credentials: 'include'
        });
        
        if (response.ok) {
          const data = await response.json();
          const currentBootTime = data.bootTime;

          if (isInitialLoad.current) {
            bootTimeRef.current = currentBootTime;
            isInitialLoad.current = false;
            return;
          }

          if (bootTimeRef.current !== null && currentBootTime !== bootTimeRef.current) {
            console.log('[AutoReload] Server restart detected, reloading...');
            window.location.reload();
          }
        }
      } catch (error) {
        // Ignore errors (server might be restarting)
      }
    };

    // Check every 3 seconds
    const interval = setInterval(checkServer, 3000);
    return () => clearInterval(interval);
  }, []);

  return null;
}
