"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxDevRuntime = require("react/jsx-dev-runtime");
const react = require("react");
const RoutingContext = require("./RoutingContext.cjs");
const urlMapper = require("./urlMapper.cjs");
const requestChangeFactory = (pageName, parameters) => (currentState) => ({
  pageName,
  parameters: parameters ?? {},
  dimensions: currentState?.dimensions || {}
});
const CurrentRequestContext = react.createContext(null);
CurrentRequestContext.displayName = "CurrentRequestContext";
const PushRequestContext = react.createContext(() => {
});
PushRequestContext.displayName = "PushRequestContext";
const useCurrentRequest = () => react.useContext(CurrentRequestContext);
const usePushRequest = () => react.useContext(PushRequestContext);
const RequestProvider = ({ children }) => {
  const routing = RoutingContext.useRouting();
  const [request, setRequest] = react.useState(() => populateRequest(routing, window.location));
  react.useEffect(
    () => {
      const onPopState = (e) => {
        e.preventDefault();
        setRequest(populateRequest(routing, window.location));
      };
      window.addEventListener("popstate", onPopState);
      return () => {
        window.removeEventListener("popstate", onPopState);
      };
    },
    [routing]
  );
  const pushRequest = react.useCallback(
    (request2) => {
      setRequest(request2);
      window.history.pushState({}, document.title, urlMapper.requestStateToPath(routing, request2));
    },
    [routing]
  );
  return /* @__PURE__ */ jsxDevRuntime.jsxDEV(CurrentRequestContext.Provider, { value: request, children: /* @__PURE__ */ jsxDevRuntime.jsxDEV(PushRequestContext.Provider, { value: pushRequest, children }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/routing/RequestContext.tsx",
    lineNumber: 54,
    columnNumber: 4
  }, void 0) }, void 0, false, {
    fileName: "/__w/interface/interface/packages/admin/src/routing/RequestContext.tsx",
    lineNumber: 53,
    columnNumber: 3
  }, void 0);
};
const populateRequest = (routing, location) => {
  const request = urlMapper.pathToRequestState(routing, location.pathname, location.search);
  if (request !== null) {
    const canonicalPath = urlMapper.requestStateToPath(routing, request);
    if (canonicalPath !== location.pathname + location.search) {
      window.history.replaceState({}, document.title, canonicalPath);
    }
  }
  return request;
};
exports.CurrentRequestContext = CurrentRequestContext;
exports.PushRequestContext = PushRequestContext;
exports.RequestProvider = RequestProvider;
exports.populateRequest = populateRequest;
exports.requestChangeFactory = requestChangeFactory;
exports.useCurrentRequest = useCurrentRequest;
exports.usePushRequest = usePushRequest;
//# sourceMappingURL=RequestContext.cjs.map
