import { useEffect } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';

// Check for SW updates every hour and on tab focus/visibility change
const UPDATE_INTERVAL_MS = 60 * 60 * 1000;

export function UpdatePrompt() {
  const {
    needRefresh: [needRefresh],
    updateServiceWorker,
  } = useRegisterSW({
    onRegisteredSW(_swUrl, registration) {
      if (!registration) return;

      const checkForUpdate = async () => {
        if (registration.installing || !navigator) return;
        if ('connection' in navigator && !navigator.onLine) return;
        try {
          await registration.update();
        } catch {
          // network error — ignore, will retry
        }
      };

      setInterval(checkForUpdate, UPDATE_INTERVAL_MS);

      const onVisible = () => {
        if (document.visibilityState === 'visible') checkForUpdate();
      };
      document.addEventListener('visibilitychange', onVisible);
      window.addEventListener('focus', checkForUpdate);
    },
  });

  useEffect(() => {
    if (needRefresh) {
      console.log('[PWA] New version detected, auto-updating...');
      updateServiceWorker(true);
    }
  }, [needRefresh, updateServiceWorker]);

  return null;
}
