import * as E from "fp-ts-esm/Either";
import { flow, identity, pipe } from "fp-ts-esm/function";
import { not } from "fp-ts-esm/Predicate";
import * as S from "fp-ts-esm/string";
import { Decoration_Type } from "./../../../../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { and, getMatches } from "../../../../fp-utils.js";
import { createLink } from "../../../node-utils.js";
import { getAttributes, hasParent, isRoot } from "../core/parse5-utils.js";
import { aToLink } from "../core/rules.js";
const parseNavigationData = flow(
  S.replace(/~#~/g, '"'),
  (d) => E.tryCatch(
    () => JSON.parse(d),
    () => ({ type: "pageLink", id: d })
  ),
  E.fold(identity, identity)
);
const toCustomData = flow(
  getMatches(/Wix\.(.+)\('(.+)'\)/),
  E.fromOption(() => "failed to parse custom link onclick"),
  E.map(([, , data]) => parseNavigationData(data)),
  E.map(JSON.stringify),
  E.fold(identity, identity)
);
const getData = (onclick) => onclick?.startsWith("Wix.") ? { customData: toCustomData(onclick) } : {};
const mergeData = (onclick) => (link) => ({ ...link, ...getData(onclick) });
const createCustomLink = ({ url, onclick, ...rest }) => pipe({ url, ...rest }, createLink, mergeData(onclick));
const aToCustomLink = [
  and([
    aToLink[0],
    not(hasParent(isRoot))
  ]),
  (context) => (node) => {
    const attrs = getAttributes(node);
    return context.addDecoration(
      Decoration_Type.LINK,
      { linkData: { link: createCustomLink({ ...attrs, url: attrs.href }) } },
      node
    );
  }
];
export {
  aToCustomLink
};
//# sourceMappingURL=a-to-custom-link.js.map
