import { useMemo, createElement, Fragment } from "react";
import { Component, useEnvironment, Field } from "@contember/binding";
import { RoutingLink } from "../RoutingLink.js";
import { RoutingParameter } from "../RoutingParameter.js";
import { targetToRequest } from "../useRoutingLink.js";
import { parseLinkTarget } from "./LinkLanguage.js";
import { useBindingLinkParametersResolver, ROUTING_BINDING_PARAMETER_PREFIX } from "./useBindingLinkParametersResolver.js";
const Link = Component(({ to, ...props }) => {
  const parametersResolver = useBindingLinkParametersResolver();
  const env = useEnvironment();
  const desugaredTo = useMemo(() => {
    return parseLinkTarget(to, env);
  }, [to, env]);
  return /* @__PURE__ */ createElement(RoutingLink, {
    parametersResolver,
    to: desugaredTo,
    ...props
  });
}, (props, env) => {
  const to = parseLinkTarget(props.to, env);
  return /* @__PURE__ */ createElement(Fragment, null, createFieldsFromTarget(to).map((it, index) => /* @__PURE__ */ createElement(Field, {
    key: `${index}-${it}`,
    field: it
  })), props.children);
});
Link.displayName = "Link";
const PageLink = Link;
const createFieldsFromTarget = (to) => {
  const dummyRequest = {
    dimensions: {},
    pageName: "",
    parameters: {}
  };
  const request = targetToRequest(to, dummyRequest);
  return collectDynamicParameters(request?.parameters ?? {}).filter((it) => it.startsWith(ROUTING_BINDING_PARAMETER_PREFIX)).map((it) => it.slice(ROUTING_BINDING_PARAMETER_PREFIX.length));
};
const collectDynamicParameters = (parameters) => {
  return Object.values(parameters).flatMap((it) => {
    if (it instanceof RoutingParameter) {
      return it.name;
    }
    if (typeof it === "object" && it !== null) {
      return collectDynamicParameters(it);
    }
    return null;
  }).filter((it) => it !== null);
};
export { Link, PageLink };
//# sourceMappingURL=Link.js.map
