import { Component, useEnvironment, Field } from "@contember/binding";
import { useMemo } from "react";
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";
import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
var _jsxFileName = "/__w/interface/interface/packages/admin/src/routing/binding/Link.tsx";
const Link = Component(({
  to,
  ...props
}) => {
  const parametersResolver = useBindingLinkParametersResolver();
  const env = useEnvironment();
  const desugaredTo = useMemo(() => {
    return parseLinkTarget(to, env);
  }, [to, env]);
  return /* @__PURE__ */ jsxDEV(RoutingLink, {
    parametersResolver,
    to: desugaredTo,
    ...props
  }, void 0, false, {
    fileName: _jsxFileName,
    lineNumber: 20,
    columnNumber: 9
  }, void 0);
}, (props, env) => {
  const to = parseLinkTarget(props.to, env);
  return /* @__PURE__ */ jsxDEV(Fragment, {
    children: [createFieldsFromTarget(to).map((it, index) => /* @__PURE__ */ jsxDEV(Field, {
      field: it
    }, `${index}-${it}`, false, {
      fileName: _jsxFileName,
      lineNumber: 25,
      columnNumber: 50
    }, void 0)), props.children]
  }, void 0, true);
});
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
