import { createElement, Fragment, useMemo, useCallback } from "react";
import { Component, Field, useDerivedField, useEnvironment } from "@contember/binding";
import { SlugInput } from "@contember/ui";
import slugify from "@sindresorhus/slugify";
import { useFieldControl } from "./useFieldControl.js";
import { SimpleRelativeSingleField } from "../auxiliary/SimpleRelativeSingleField/SimpleRelativeSingleField.js";
const useNormalizedPrefix = (value) => {
  const environment = useEnvironment();
  return useMemo(() => typeof value === "function" ? value(environment) : value ?? "", [value, environment]);
};
const SlugField = Component((props) => /* @__PURE__ */ createElement(SlugFieldInner, {
  ...props
}), (props) => /* @__PURE__ */ createElement(Fragment, null, /* @__PURE__ */ createElement(Field, {
  field: props.derivedFrom
}), /* @__PURE__ */ createElement(SlugFieldInner, {
  ...props
})));
const SlugFieldInner = SimpleRelativeSingleField((fieldMetadata, {
  label,
  unpersistedHardPrefix,
  persistedHardPrefix,
  persistedSoftPrefix,
  linkToExternalUrl,
  derivedFrom,
  field,
  ...props
}) => {
  const normalizedUnpersistedHardPrefix = useNormalizedPrefix(unpersistedHardPrefix);
  const normalizedPersistedHardPrefix = useNormalizedPrefix(persistedHardPrefix);
  const normalizedPersistedSoftPrefix = useNormalizedPrefix(persistedSoftPrefix);
  const inputProps = useFieldControl({
    ...props,
    fieldMetadata,
    parse: (val, field2) => {
      const parsedValue = val ?? null;
      return parsedValue !== null ? `${normalizedPersistedHardPrefix}${parsedValue}` : null;
    },
    format: (value) => typeof value === "string" ? value.substring(normalizedPersistedHardPrefix.length) : ""
  });
  const transform = useCallback((driverFieldValue) => {
    if (driverFieldValue === null) {
      return null;
    }
    const slugValue = slugify(driverFieldValue);
    return `${normalizedPersistedHardPrefix}${normalizedPersistedSoftPrefix}${slugValue}`;
  }, [normalizedPersistedHardPrefix, normalizedPersistedSoftPrefix]);
  useDerivedField(derivedFrom, field, transform);
  const hardPrefix = normalizedUnpersistedHardPrefix + normalizedPersistedHardPrefix;
  const fullValue = hardPrefix + inputProps.value;
  return /* @__PURE__ */ createElement(SlugInput, {
    ...inputProps,
    prefix: hardPrefix,
    link: linkToExternalUrl ? fullValue : void 0
  });
}, "SlugField");
export { SlugField, SlugFieldInner };
//# sourceMappingURL=SlugField.js.map
