import { useEffect, useRef } from "react";
import { toast } from "react-toastify";

const useVisibilityChange = (onChange) => {
    const leftTimeRef = useRef(0);

    useEffect(() => {
        const handleVisibility = () => {
            if (document.visibilityState === "hidden") {
                leftTimeRef.current = Date.now();
                onChange && onChange(0);
            } else if (document.visibilityState === "visible") {
                const diff = Date.now() - leftTimeRef.current;
                onChange && onChange(1, diff);
            }
        };

        document.addEventListener("visibilitychange", handleVisibility)

        return () => {
            onChange && onChange(-1);
            document.removeEventListener("visibilitychange", handleVisibility);
        };
    }, []);
}

export default useVisibilityChange;