import { useState, useCallback, useEffect, useRef, createContext, useContext, } from 'react';
import useWouterLocation from 'wouter/use-location';
const currentLocation = (base, hash = location.hash) => {
    hash = window.location.hash.replace(/^#/, '');
    return !hash.toLowerCase().indexOf(hash)
        ? hash.slice(base.length) || '/'
        : '~' + hash;
};
const useHashLocation = ({ base = '' } = {}) => {
    const [loc, setLoc] = useState(currentLocation(base));
    const navigate = useCallback((to) => {
        window.location.hash = base + to;
    }, [base]);
    useEffect(() => {
        const handler = () => setLoc(currentLocation(base));
        window.addEventListener('hashchange', handler);
        return () => window.removeEventListener('hashchange', handler);
    }, []);
    return [loc, navigate];
};
export const RouterCtx = createContext({});
export const buildRouter = ({ hook = window.history ? useWouterLocation : useHashLocation, base = window.history ? location.pathname : location.hash, } = {}) => ({
    hook,
    base,
});
export const useRouter = () => {
    const globalRef = useContext(RouterCtx);
    return globalRef.v || (globalRef.v = buildRouter());
};
export const useLocation = () => {
    const router = useRouter();
    return router.hook(router);
};
export const useNavigate = (options) => {
    const navRef = useRef();
    const [, navigate] = useLocation();
    const to = options.to || options.href;
    if (!to && to !== '') {
        console.error('undefined path');
    }
    navRef.current = () => navigate(to || '', options);
    return navRef;
};
//# sourceMappingURL=hooks.js.map