import { useNavigate, useLocation } from 'react-router';
import {useEffect, useMemo, useState} from "react";

export default function BackButton() {
    const navigate = useNavigate();
    const location = useLocation();
    const [canBack, setCanBack] = useState(window.history.length > 1);

    useEffect(() => {
        setCanBack(window.history.length > 1);
    }, [location.key]);

    const supportsNavigationAPI = useMemo(
        () =>
            typeof window !== "undefined" &&
            "navigation" in window &&
            "canGoBack"  in (window as any).navigation,
        []
    );

    return (
        <button
            disabled={!canBack}
            onClick={() => {
                if (supportsNavigationAPI) {
                    // @ts-ignore
                    if (!window.navigation.canGoBack) return
                }
                navigate(-1)
            }}
            style={{
                opacity: canBack ? 1 : 0.35,
                cursor : canBack ? "pointer" : "default",
                transition: "opacity .2s",
            }}
        >
            ←
        </button>
    );
}
