import { useEffect, useState } from 'react';

type UseNetworkStatusOptions = {
  onOnline?: () => void;
  onOffline?: () => void;
};

const useNetworkStatus = ({
  onOnline,
  onOffline,
}: UseNetworkStatusOptions = {}) => {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => {
      setIsOnline(true);
      onOnline?.();
    };

    const handleOffline = () => {
      setIsOnline(false);
      onOffline?.();
    };

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

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

  return { isOnline };
};

export default useNetworkStatus;
