'use client';

import { useEffect } from 'react';

const SW_PATH = '/sw.js';

export function ServiceWorkerProvider() {
  useEffect(() => {
    if (!('serviceWorker' in navigator)) {
      return;
    }

    const registerServiceWorker = async () => {
      try {
        const registration = await navigator.serviceWorker.register(SW_PATH, { scope: '/' });

        if (registration.waiting) {
          registration.waiting.postMessage('skipWaiting');
        }

        navigator.serviceWorker.addEventListener('controllerchange', () => {
          if (!document.hidden) {
            window.location.reload();
          }
        });
      } catch (error) {
        console.error('Service worker registration failed:', error);
      }
    };

    const isProduction = window.location.hostname === 'basetracker.lona-development.org';

    if (isProduction) {
      registerServiceWorker();
    } else {
      navigator.serviceWorker.getRegistration(SW_PATH).then((registration) => {
        registration?.unregister();
      });
    }
  }, []);

  return null;
}
