import { useEffect } from 'react';
import { IS_DESKTOP } from '../config/site';

/** 注册 SW：新版本 confirm + SKIP_WAITING；首次 controller 变化不强制刷新 */
export function useServiceWorker() {
  useEffect(() => {
    if (IS_DESKTOP) return;
    if (!('serviceWorker' in navigator)) return;

    const pageAlreadyControlled = Boolean(navigator.serviceWorker.controller);
    let hasRefreshing = false;

    function promptRefresh(worker: ServiceWorker) {
      const shouldRefresh = window.confirm('发现新版本，是否立即刷新？');
      if (shouldRefresh) worker.postMessage('SKIP_WAITING');
    }

    (async () => {
      try {
        const reg = await navigator.serviceWorker.register('/sw.js', { scope: '/' });

        if (reg.waiting) {
          promptRefresh(reg.waiting);
        }

        reg.addEventListener('updatefound', () => {
          const newWorker = reg.installing;
          if (!newWorker) return;
          newWorker.addEventListener('statechange', () => {
            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
              promptRefresh(newWorker);
            }
          });
        });

        navigator.serviceWorker.addEventListener('controllerchange', () => {
          if (hasRefreshing) return;
          if (!pageAlreadyControlled) return;
          hasRefreshing = true;
          window.location.reload();
        });
      } catch (e) {
        console.error('Service Worker 注册失败:', e);
      }
    })();
  }, []);
}
