import { useState, useEffect, useCallback } from 'react';

export function useOfflineMode() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  const [isServiceWorkerReady, setIsServiceWorkerReady] = useState(false);
  const [offlineMode, setOfflineMode] = useState(false);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  useEffect(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready
        .then((registration) => {
          setIsServiceWorkerReady(true);
          console.log('Service Worker ready:', registration.scope);
        })
        .catch((error) => {
          console.error('Service Worker not ready:', error);
        });
    }
  }, []);

  const toggleOfflineMode = useCallback(() => {
    setOfflineMode((prev) => !prev);
  }, []);

  const cacheUrls = useCallback(async (urls: string[]) => {
    if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
      navigator.serviceWorker.controller.postMessage({
        type: 'CACHE_URLS',
        urls,
      });
    }
  }, []);

  const updateServiceWorker = useCallback(() => {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready.then((registration) => {
        registration.update();
      });
    }
  }, []);

  return {
    isOnline,
    isOffline: !isOnline,
    isServiceWorkerReady,
    offlineMode,
    toggleOfflineMode,
    cacheUrls,
    updateServiceWorker,
  };
}
