import { createContext, useContext, useState, useEffect, useCallback, createElement } 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__ */ createElement(CurrentRequestContext.Provider, {
    value: request
  }, /* @__PURE__ */ createElement(PushRequestContext.Provider, {
    value: pushRequest
  }, children));
};
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
