import {useEffect, useState} from "@wordpress/element";
import {debounce} from "../../../../../../helpers";

export default function useOnlineStatus(delay = 3000) {
    const [isOnline, setIsOnline] = useState(navigator.onLine);

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

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

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

    return isOnline;
}