import { jsx as _jsx } from "react/jsx-runtime";
import { useSafeLayoutEffect } from "@vertesia/ui/core";
//import { useSafeLayoutEffect } from "../core";
import { useMemo, useState } from "react";
import { RouteComponent } from "./RouteComponent";
import { ReactRouterContext, Router } from "./Router";
import { createRoute404 } from "./Route404";
export function RouterProvider({ routes, index, onChange, children }) {
    const [state, setState] = useState(undefined);
    const router = useMemo(() => {
        if (typeof window === 'undefined')
            return null;
        const router = new Router(routes, (match) => {
            if (match === null) {
                match = createRoute404();
            }
            setState({
                location: window.location,
                route: match.value,
                params: match.params,
                state: match.state,
                router: router,
                matchedRoutePath: '/' + match.matchedSegments.join('/'),
                remainingPath: match.remainingSegments ? '/' + match.remainingSegments.join('/') : undefined,
                navigate: (to, options) => {
                    return router.navigate(to, options);
                }
            });
        }).withObserver(onChange);
        router.index = index;
        return router;
    }, []);
    useSafeLayoutEffect(() => {
        router && router.start();
        return () => {
            router && router.stop();
        };
    }, []);
    return state && (_jsx(ReactRouterContext.Provider, { value: state, children: children ? children : _jsx(RouteComponent, {}) }));
}
//# sourceMappingURL=RouterProvider.js.map