'use client';

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

const subscribe = (callback: () => void) => {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);
  return () => {
    window.removeEventListener('online', callback);
    window.removeEventListener('offline', callback);
  };
};

const getSnapshot = () => navigator.onLine;
const getServerSnapshot = () => true;

const OFFLINE_DEBOUNCE_MS = 500;

export const useOnlineStatus = () => {
  const isOnlineRaw = useSyncExternalStore(
    subscribe,
    getSnapshot,
    getServerSnapshot
  );
  const [isOnline, setIsOnline] = useState(isOnlineRaw);

  useEffect(() => {
    if (isOnlineRaw) {
      setIsOnline(true);
      return;
    }
    const timer = window.setTimeout(
      () => setIsOnline(false),
      OFFLINE_DEBOUNCE_MS
    );
    return () => window.clearTimeout(timer);
  }, [isOnlineRaw]);

  return isOnline;
};
