import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { FixLinks } from "./FixLinks";
import { createRoute404 } from "./Route404";
import { RouteComponent } from "./RouteComponent";
import { NestedRouter, ReactRouterContext, useRouterContext } from "./Router";
export function NestedRouterProvider({ routes, index, children, fixLinks = false }) {
    const ctx = useRouterContext();
    const [nestedRouteMatch, setNestedRouteMatch] = useState(undefined);
    const nestedRouter = useMemo(() => {
        if (typeof window === 'undefined')
            return null;
        const basePath = ctx.matchedRoutePath;
        const nestedRouter = new NestedRouter(ctx.router, basePath, routes);
        nestedRouter.index = index;
        return nestedRouter;
    }, []);
    useEffect(() => {
        if (nestedRouter) {
            if (ctx.matchedRoutePath !== nestedRouter.basePath) {
                // the change doesn't belong to this nested router
                // it should be handled by the top level router which will change the page or the nested router
                return;
            }
            const route = nestedRouter.match(ctx.remainingPath || '/') || createRoute404();
            setNestedRouteMatch(route);
        }
    }, [nestedRouter, ctx.remainingPath]);
    const wrapWithFixLinks = fixLinks ?
        (elem) => _jsx(FixLinks, { basePath: ctx.matchedRoutePath, children: elem })
        : (elem) => elem;
    return nestedRouteMatch && (_jsx(ReactRouterContext.Provider, { value: {
            ...ctx,
            router: nestedRouter,
            route: nestedRouteMatch.value,
            params: nestedRouteMatch.params,
            matchedRoutePath: '/' + nestedRouteMatch.matchedSegments.join('/'),
            remainingPath: nestedRouteMatch.remainingSegments ? '/' + nestedRouteMatch.remainingSegments.join('/') : undefined,
            navigate: (to, options) => {
                return nestedRouter.navigate(to, options);
            }
        }, children: wrapWithFixLinks(children ? children : _jsx(RouteComponent, {})) }));
}
//# sourceMappingURL=NestedRouterProvider.js.map