import React from 'react';
import { registerSW } from 'virtual:pwa-register';
import { pushGuestToast } from '../lib/toast';

export default function PwaManager() {
  const updatePromptedRef = React.useRef(false);

  React.useEffect(() => {
    if (!('serviceWorker' in navigator)) {
      return;
    }

    const updateSW = registerSW({
      immediate: true,
      onNeedRefresh() {
        if (updatePromptedRef.current) {
          return;
        }
        updatePromptedRef.current = true;
        pushGuestToast({
          text: 'Update available',
          type: 'info',
          durationMs: 0,
          action: {
            label: 'Reload',
            onClick: () => updateSW(true),
          },
        });
      },
      onOfflineReady() {
        pushGuestToast({
          text: 'Offline mode ready',
          type: 'success',
        });
      },
      onRegisterError(error) {
        console.warn('Guest v2 PWA registration failed', error);
      },
    });

    const runQueue = () => {
      void import('@/shared/guest/queue/queue')
        .then((module) => module.processQueue().catch(() => {}))
        .catch(() => {});
    };

    const handleMessage = (event: MessageEvent) => {
      if (event.data?.type === 'sync-queue') {
        runQueue();
      }
    };

    navigator.serviceWorker.addEventListener('message', handleMessage);
    window.addEventListener('online', runQueue);
    runQueue();

    return () => {
      navigator.serviceWorker.removeEventListener('message', handleMessage);
      window.removeEventListener('online', runQueue);
    };
  }, []);

  return null;
}
