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