;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "accd929f-e7a6-4aee-92ea-57a225e9a848", e._sentryDebugIdIdentifier = "sentry-dbid-accd929f-e7a6-4aee-92ea-57a225e9a848");
  } catch (e) {
  }
}
;
import { ac as entriesOf, a6 as objectsDeepEqual, ak as reverseMapping, o as LegalEntityTypes, j as TaskTypes, a0 as CountryCodes, au as hasText, am as matchesRegex, an as NO_ALPHABET_REGEX, ao as EMOJI_REGEX, ap as hasRepeatedCharacters, b0 as isValidMinLength, aq as isInvalidName, bk as OTHER_ENTITIES_VALID_CHAR_REGEX, u as useTranslation, v as useExperimentsContext, z as Typography, bA as getCountrySpecificTrustTypeOptions, bB as trustComponentsKeyMapping, bC as trustApiKeyMapping, b as useApiContext, p as useAnalyticsContext, bD as trustDocumentMapping, ab as cloneObject, g as getLegalEntityCountry, ai as isEmpty$1, aH as drop, ae as getOwnEntityAssociations, c as useLegalEntity, a as addResourceBundles, L as Loader, R as ROOT_LE, aD as keysOf, a8 as EntityTypes, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsx, Fragment, jsxs } from "preact/jsx-runtime";
import { skipToken } from "@tanstack/preact-query";
import { u as useCapabilityProblems, g as getProblemsForEntity } from "./getProblemsForEntity-C1PgQbDM.js";
import { l as COUNTRIES_THAT_USE_TAX_ID_INSTEAD_OF_VAT, d as TAX_INFORMATION_FIELD, t as taxInformationDefaultFieldMetadata, a as taxInformationDefaultFieldConfig, x as exemptedFromTaxDefaultFieldMetadata, y as exemptedFromTaxDefaultFieldConfig, T as TaxInformationField, g as getFieldsWithExistingData, m as getCompanyRegistrationNumberOptions, n as countryToTaxInfoTypeMap, u as useCapabilities } from "./TaxInformationField-Cd1at8Ld.js";
import { useMemo, useCallback, useEffect, useState, useRef } from "preact/hooks";
import { u as useCreateLegalEntity } from "./useCreateLegalEntity-swV6s65R.js";
import { u as useUpdateLegalEntity } from "./useUpdateLegalEntity-CcNBhTXa.js";
import { u as useGlobalDataSlice, c as useStateContext } from "./useGlobalData-ewWkzI4Y.js";
import { u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { g as getPropsFromConfigurations, a as augmentWithCountryConfigs, c as composePerScenarioFormConfigurations } from "./process-field-configurations-DMce565i.js";
import { g as getRequiredForms, a as addValidityToForms, u as useFormComposer } from "./dropinUtils-G5Ua27s3.js";
import { m as mapExistingFile, g as getPageName, b as useScenarioConfiguration } from "./mapExistingFile-DOPjFNWj.js";
import { o as operationalAddressIsSameIds, D as DBA_NAME_FIELD, B as BUSINESS_REGISTRATION_NUMBER_FIELD, V as VAT_NUMBER_FIELD, f as doingBusinessAsAbsentFieldMetadata, e as doingBusinessAsFieldMetadata, b as registrationNumberDefaultFieldMetadata, k as getDefaultRegistrationNumberType, c as registrationNumberDefaultFieldConfig, n as exemptFromRegistrationNumberDefaultFieldMetadata, p as exemptFromRegistrationNumberDefaultFieldConfig, d as defaultFieldMetadata, l as getDefaultVatNumberType, a as defaultFieldConfig, g as DBANameField, h as BusinessRegistrationNumberField, i as getRegistrationNumberHelperText, j as VatNumberField, r as registrationAddressFields, R as RegistrationAddress, M as MemoizedConstitutionalDocument, m as inferCompanyRegistrationNumberType, q as operationalAddressIsSameItems } from "./ConstitutionalDocument-BF6Et_CM.js";
import { m as mapAddressLabels } from "./utils-DmjdHPet.js";
import { F as FormWrapper } from "./FormWrapper-CZOHIV6t.js";
import { i as isValidationError, p as processValidationErrors, a as isMaintenanceModeError } from "./validationError-BjtmNNIE.js";
import { a as getDocument, c as createDocumentRequest, d as documentApiUtils } from "./validate-CtroZEiR.js";
import { a as datasetUtilities } from "./datasetUtil-BHQp0-xL.js";
import { r as resolveFieldMetadata } from "./fieldConfigurations-BUT9DTUH.js";
import { f as formatObject, g as getProp } from "./utils-DNSfZiio.js";
import { c as createFormRules } from "./form-rules-DhbF2mY4.js";
import { U as UNINCORPORATED_PARTNERSHIP_COUNTRIES_VAT_NUMBER_OPTIONAL, a as UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_REQUIRED, b as UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_OPTIONAL, c as UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_REQUIRED, d as UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_OPTIONAL, A as ALLOWED_UNINCORPORATED_PARTNERSHIP_COUNTRIES } from "./types-BSx67xBd.js";
import { a as getFormProps, b as getNestedOuterFormPropsFromOuterFormProps } from "./getProps-Cc3J2-z9.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { a as Alert } from "./Alert-CpDg47bv.js";
import { E as ErrorPanel } from "./ErrorPanel-D-VMcBB9.js";
import { I as InputText } from "./InputText-DRSK56ma.js";
import { C as CountryField, a as COUNTRY_FIELD } from "./CountryField-DDFphSWX.js";
import { m as mergeFieldMetadataIntoProps, c as createFormUtils } from "./formUtils-CwOJPw6N.js";
import { i as isEmpty } from "./isEmpty-vwqWRDI4.js";
import { a as validateNotEmptyOnBlur } from "./patternValidators-Bv0Mmhgd.js";
import { u as useFormContext, F as FormContextProvider, a as FormFlow } from "./useFormContext-LfOXbOKX.js";
import { u as useMultiForm } from "./useMultiForm-XT1CUuQs.js";
import "preact";
import "classnames";
import "named-slots";
import { R as RadioGroup } from "./RadioGroup-jkgDMvvX.js";
import "./Radio-BMtxBpnn.js";
import { A as Address } from "./Address-DMDTO9vd.js";
import "@preact/signals";
import "./useDataset-DgIHjoGg.js";
import { C as ContextGuidance } from "./ContextGuidance-BESxqmbz.js";
const hasDataChanged = (initialData, currentData) => entriesOf(currentData ?? {}).some(([key, value]) => {
  if (typeof value === "object") {
    return !objectsDeepEqual(value, initialData?.[key]);
  }
  return value !== initialData?.[key];
});
const mapApiDocumentToTrustDocument = (entityId) => {
  const constitutionalDocument = getDocument(entityId, "constitutionalDocument") || null;
  return {
    trustConstitutionalDocument: constitutionalDocument ? { constitutionalDocument: [mapExistingFile(getPageName(constitutionalDocument))] } : void 0
  };
};
const unincorporatedPartnershipBaseMapping = {
  "trustRegistrationDetails.trustType": "unincorporatedPartnership.type",
  "trustRegistrationDetails.legalName": "unincorporatedPartnership.name",
  "trustRegistrationDetails.doingBusinessAs": "unincorporatedPartnership.doingBusinessAs",
  "trustRegistrationDetails.hasDoingBusinessAs": "unincorporatedPartnership.doingBusinessAsAbsent",
  "trustRegistrationDetails.country": "unincorporatedPartnership.countryOfGoverningLaw",
  "trustRegistrationDetails.registrationNumber": "unincorporatedPartnership.registrationNumber",
  "trustRegistrationDetails.taxInformation": "unincorporatedPartnership.taxInformation",
  "trustRegistrationDetails.vatNumber": "unincorporatedPartnership.vatNumber",
  "trustRegistrationAddress.registrationAddress.city": "unincorporatedPartnership.registeredAddress.city",
  "trustRegistrationAddress.registrationAddress.country": "unincorporatedPartnership.registeredAddress.country",
  "trustRegistrationAddress.registrationAddress.postalCode": "unincorporatedPartnership.registeredAddress.postalCode",
  "trustRegistrationAddress.registrationAddress.stateOrProvince": "unincorporatedPartnership.registeredAddress.stateOrProvince",
  "trustRegistrationAddress.registrationAddress.address": "unincorporatedPartnership.registeredAddress.street",
  "trustRegistrationAddress.registrationAddress.otherAddressInformation": "unincorporatedPartnership.registeredAddress.street2",
  "trustRegistrationAddress.operationalAddress.city": "unincorporatedPartnership.principalPlaceOfBusiness.city",
  "trustRegistrationAddress.operationalAddress.country": "unincorporatedPartnership.principalPlaceOfBusiness.country",
  "trustRegistrationAddress.operationalAddress.postalCode": "unincorporatedPartnership.principalPlaceOfBusiness.postalCode",
  "trustRegistrationAddress.operationalAddress.stateOrProvince": "unincorporatedPartnership.principalPlaceOfBusiness.stateOrProvince",
  "trustRegistrationAddress.operationalAddress.address": "unincorporatedPartnership.principalPlaceOfBusiness.street",
  "trustRegistrationAddress.operationalAddress.otherAddressInformation": "unincorporatedPartnership.principalPlaceOfBusiness.street2"
};
const unincorporatedPartnershipComponentsKeyMapping = {
  "trustRegistrationDetails.exemptedFromVat": "unincorporatedPartnership.vatAbsenceReason",
  ...unincorporatedPartnershipBaseMapping
};
const unincorporatedPartnershipApiKeyMapping = {
  ...reverseMapping(unincorporatedPartnershipBaseMapping)
};
const mapLegalEntityToUnincorporatedPartnership = (legalEntity, isExperimentEnabled) => {
  if (!legalEntity.unincorporatedPartnership)
    throw new Error("LE missing unincorporatedPartnership field");
  let trustCompData = formatObject(
    legalEntity,
    unincorporatedPartnershipComponentsKeyMapping
  );
  if (!trustCompData?.trustRegistrationDetails) return {};
  trustCompData.trustRegistrationDetails.country = legalEntity.unincorporatedPartnership.countryOfGoverningLaw;
  if (legalEntity.unincorporatedPartnership.description) {
    trustCompData.trustRegistrationDetails.objectOfTrust = legalEntity.unincorporatedPartnership.description;
  }
  if (legalEntity.unincorporatedPartnership.principalPlaceOfBusiness) {
    trustCompData.trustRegistrationAddress.operationalAddressIsSame = operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_NOT_SAME;
  } else {
    if (!trustCompData.trustRegistrationAddress) {
      trustCompData.trustRegistrationAddress = {};
    }
    trustCompData.trustRegistrationAddress.operationalAddressIsSame = operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_SAME;
  }
  if (legalEntity.unincorporatedPartnership.taxInformation?.length) {
    const { country } = legalEntity.unincorporatedPartnership.registeredAddress;
    const countryTaxInformation = legalEntity.unincorporatedPartnership.taxInformation.find(
      (info) => info.country === country
    );
    if (countryTaxInformation?.type === "UEN") {
      trustCompData.trustRegistrationDetails.isUen = true;
    }
    if (countryTaxInformation?.type === "GST") {
      trustCompData.trustRegistrationDetails.isUen = false;
    }
    const taxNumberAbsent = countryTaxInformation?.numberAbsent;
    if (taxNumberAbsent !== void 0) {
      trustCompData.trustRegistrationDetails.exemptedFromTax = taxNumberAbsent;
    }
  }
  if (legalEntity.documentDetails?.length) {
    trustCompData = {
      ...trustCompData,
      ...mapApiDocumentToTrustDocument(legalEntity?.id)
    };
  }
  if (isExperimentEnabled("EnableDoingBusinessAsNameV4")) {
    if (typeof trustCompData.trustRegistrationDetails?.hasDoingBusinessAs === "boolean") {
      trustCompData.trustRegistrationDetails.hasDoingBusinessAs = !legalEntity.unincorporatedPartnership.doingBusinessAsAbsent;
      if (!trustCompData.trustRegistrationDetails.hasDoingBusinessAs)
        delete legalEntity.unincorporatedPartnership.doingBusinessAs;
    }
  } else {
    trustCompData.trustRegistrationDetails.hasDoingBusinessAs = legalEntity.unincorporatedPartnership.doingBusinessAs ? legalEntity.unincorporatedPartnership.doingBusinessAs !== legalEntity.unincorporatedPartnership.name : void 0;
    trustCompData.trustRegistrationDetails.doingBusinessAs = legalEntity.unincorporatedPartnership.doingBusinessAs;
  }
  return trustCompData;
};
const mapUnincorporatedPartnershipToLegalEntity = (data, isExperimentEnabled) => {
  const requestObj = {
    ...formatObject(data, unincorporatedPartnershipApiKeyMapping)
  };
  if (!requestObj.unincorporatedPartnership) return requestObj;
  if (requestObj.unincorporatedPartnership?.taxInformation?.[0]?.type === "GST") {
    requestObj.unincorporatedPartnership.taxInformation[0].type = "UEN";
  }
  if (isExperimentEnabled("EnableDoingBusinessAsNameV4")) {
    if (typeof data.trustRegistrationDetails?.hasDoingBusinessAs !== "undefined") {
      requestObj.unincorporatedPartnership.doingBusinessAsAbsent = !data.trustRegistrationDetails?.hasDoingBusinessAs;
    }
  } else {
    requestObj.unincorporatedPartnership.doingBusinessAs = data.trustRegistrationDetails?.doingBusinessAs || data.trustRegistrationDetails?.legalName || "";
    delete requestObj.unincorporatedPartnership.doingBusinessAsAbsent;
  }
  requestObj.type = LegalEntityTypes.UNINCORPORATED_PARTNERSHIP;
  return requestObj;
};
const COUNTRIES_THAT_USE_REGISTRATION_NUMBER = [CountryCodes.NewZealand];
const rules = ({
  data,
  country,
  isExperimentEnabled,
  taskType
}) => createFormRules({
  countryUsesTaxId: () => {
    if (taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP) {
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_REQUIRED.includes(country)) {
        return "REQUIRED";
      }
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_OPTIONAL.includes(country)) {
        return "OPTIONAL";
      }
    }
    if (country !== CountryCodes.NewZealand && COUNTRIES_THAT_USE_TAX_ID_INSTEAD_OF_VAT.includes(country)) {
      return "REQUIRED";
    }
  },
  countryRequiresRegistrationNumberForTrust: () => {
    if (taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP) {
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_REQUIRED.includes(country)) {
        return "REQUIRED";
      }
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_OPTIONAL.includes(country)) {
        return "OPTIONAL";
      }
    }
    if (COUNTRIES_THAT_USE_REGISTRATION_NUMBER.includes(country)) {
      return "REQUIRED";
    }
  },
  registrationNumberType: () => {
    if (taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP) {
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_REQUIRED.includes(country)) {
        return "OPTIONAL";
      }
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_OPTIONAL.includes(country)) {
        return "OPTIONAL";
      }
    }
    if (COUNTRIES_THAT_USE_REGISTRATION_NUMBER.includes(country)) {
      return "OPTIONAL";
    }
  },
  countryUsesVatNumber: () => {
    if (taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP) {
      if (UNINCORPORATED_PARTNERSHIP_COUNTRIES_VAT_NUMBER_OPTIONAL.includes(country)) {
        return "OPTIONAL";
      }
    }
  },
  trustTypeHasDescription: () => {
    if (data?.trustRegistrationDetails?.trustType === "charitableTrust") {
      return "REQUIRED";
    }
  },
  hasDoingBusinessAs: () => {
    if (isExperimentEnabled?.("EnableDoingBusinessAsNameV4")) {
      return "REQUIRED";
    }
  }
});
const trustRegistrationDetailsValidations = {
  trustType: {
    modes: ["blur"],
    validate: (trustType) => !!trustType,
    errorMessage: "fieldIsRequired"
  },
  country: {
    modes: ["blur"],
    validate: (country) => !!country,
    errorMessage: "fieldIsRequired"
  },
  legalName: {
    modes: ["blur"],
    validate: (legalName) => !!legalName,
    errorMessage: "fieldIsRequired"
  },
  objectOfTrust: {
    modes: ["blur"],
    validate: (objectOfTrust) => !!objectOfTrust,
    errorMessage: "fieldIsRequired"
  },
  hasDoingBusinessAs: validateNotEmptyOnBlur,
  doingBusinessAs: validateNotEmptyOnBlur
};
const trustRegistrationDetailsValidationsV4 = {
  trustType: {
    modes: ["blur"],
    validate: (trustType) => !!trustType,
    errorMessage: "fieldIsRequired"
  },
  country: {
    modes: ["blur"],
    validate: (country) => !!country,
    errorMessage: "fieldIsRequired"
  },
  legalName: [
    {
      modes: ["blur"],
      validate: hasText,
      errorMessage: "fieldIsRequired"
    },
    {
      modes: ["blur"],
      validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input),
      errorMessage: "nameMustContainLetters"
    },
    {
      modes: ["blur"],
      validate: (input) => !matchesRegex(EMOJI_REGEX, input) && !hasRepeatedCharacters(input) && isValidMinLength(input, 3) && !isInvalidName(input) && matchesRegex(OTHER_ENTITIES_VALID_CHAR_REGEX, input),
      errorMessage: "checkForTypos"
    }
  ],
  objectOfTrust: {
    modes: ["blur"],
    validate: (objectOfTrust) => !!objectOfTrust,
    errorMessage: "fieldIsRequired"
  },
  hasDoingBusinessAs: validateNotEmptyOnBlur,
  doingBusinessAs: validateNotEmptyOnBlur
};
const trustRegistrationDetailsFields = [
  "legalName",
  ...DBA_NAME_FIELD,
  "country",
  "trustType",
  "objectOfTrust",
  ...TAX_INFORMATION_FIELD,
  ...BUSINESS_REGISTRATION_NUMBER_FIELD,
  ...VAT_NUMBER_FIELD
];
const ALLOWED_TRUST_COUNTRIES$1 = [CountryCodes.Australia, CountryCodes.NewZealand];
function TrustRegistrationDetails(props) {
  let mergedProps = props;
  const TRUST_REGISTRATION_DETAILS2 = mergedProps.id || trustForms$1.trustRegistrationDetails.formId;
  const { t: commonT } = useTranslation("common");
  const { t: trustT } = useTranslation("trust");
  const { isExperimentEnabled } = useExperimentsContext();
  const { updateStateSlice, sliceData } = useGlobalDataSlice(TRUST_REGISTRATION_DETAILS2);
  const isStrictNameAndAddressValidationEnabled = isExperimentEnabled(
    "StrictNameAndAddressValidationV4"
  );
  const { taskType } = props;
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  const country = sliceData?.country ?? mergedProps.country;
  const defaultData = useMemo(
    () => ({ ...mergedProps.data, country }),
    [country, mergedProps.data]
  );
  const requiredFields = isEmpty(mergedProps.requiredFields) ? trustRegistrationDetailsFields : mergedProps.requiredFields;
  mergedProps = mergeFieldMetadataIntoProps(
    "hasDoingBusinessAs",
    doingBusinessAsAbsentFieldMetadata,
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "doingBusinessAs",
    doingBusinessAsFieldMetadata,
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "taxInformation",
    resolveFieldMetadata(
      taxInformationDefaultFieldConfig[country],
      {
        taxIdNumberType: sliceData?.taxInformation?.find((taxId) => taxId.country === country)?.type,
        companyType: LegalEntityTypes.TRUST
      },
      taxInformationDefaultFieldMetadata
    ),
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "exemptedFromTax",
    resolveFieldMetadata(
      exemptedFromTaxDefaultFieldConfig[country],
      {},
      exemptedFromTaxDefaultFieldMetadata
    ),
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "registrationNumber",
    resolveFieldMetadata(
      registrationNumberDefaultFieldConfig[country],
      {
        companyType: LegalEntityTypes.TRUST,
        registrationNumberType: sliceData?.registrationNumberType ?? getDefaultRegistrationNumberType(sliceData?.registrationNumber, country, "trust"),
        isExperimentEnabled
      },
      registrationNumberDefaultFieldMetadata
    ),
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "exemptedFromRegistrationNumber",
    resolveFieldMetadata(
      exemptFromRegistrationNumberDefaultFieldConfig[country],
      {},
      exemptFromRegistrationNumberDefaultFieldMetadata
    ),
    mergedProps
  );
  mergedProps = mergeFieldMetadataIntoProps(
    "vatNumber",
    resolveFieldMetadata(
      defaultFieldConfig[country],
      {
        vatNumberType: sliceData?.vatNumberType ?? getDefaultVatNumberType(sliceData?.vatNumber, country)
      },
      defaultFieldMetadata
    ),
    mergedProps
  );
  mergedProps.validators = {
    ...mergedProps.validators,
    legalName: isStrictNameAndAddressValidationEnabled ? trustRegistrationDetailsValidationsV4.legalName : trustRegistrationDetailsValidations.legalName
  };
  const getFormSchema = useCallback(
    (currentData) => {
      const fieldsToRemove = [];
      if (!currentData.hasDoingBusinessAs) {
        fieldsToRemove.push("doingBusinessAs");
      }
      return requiredFields.filter((field) => !fieldsToRemove.includes(field));
    },
    [requiredFields]
  );
  const { handleChangeFor, data, valid, errors, setData, fieldProblems, schema } = useForm({
    ...mergedProps,
    schema: getFormSchema,
    defaultData,
    rules: mergedProps.validators || (isStrictNameAndAddressValidationEnabled ? trustRegistrationDetailsValidationsV4 : trustRegistrationDetailsValidations),
    fieldProblems: mergedProps.fieldValidationErrors
  });
  const formUtils = createFormUtils(
    {
      ...mergedProps,
      requiredFields,
      fieldValidationErrors: mergedProps.fieldValidationErrors,
      formVerificationErrors: mergedProps.formVerificationErrors
    },
    commonT
  );
  useEffect(() => {
    updateStateSlice({
      schema,
      data,
      errors,
      valid,
      fieldProblems
    });
  }, [data, errors, fieldProblems, schema, updateStateSlice, valid]);
  const changeTrustType = (e) => {
    handleChangeFor("trustType", "blur")(e);
    if (e.target.value !== "charitableTrust") {
      setData("objectOfTrust", void 0);
    }
  };
  const trustTypeOptions = getCountrySpecificTrustTypeOptions(country) ?? [];
  const showField = (field) => formUtils.isRequiredField(field) || formUtils.isOptionalField(field);
  return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs("form", { id: TRUST_REGISTRATION_DETAILS2, className: "adyen-kyc-trust__registration-details", children: [
    mergedProps.heading && /* @__PURE__ */ jsx(Header, { title: mergedProps.heading }),
    /* @__PURE__ */ jsx(
      ErrorPanel,
      {
        verificationErrors: mergedProps.formVerificationErrors,
        validationErrors: mergedProps.fieldValidationErrors,
        formUtils,
        id: "ariaErrorField"
      }
    ),
    !isUnincorporatedPartnership && /* @__PURE__ */ jsx(
      Alert,
      {
        variant: "info",
        title: /* @__PURE__ */ jsx(Typography, { variant: "caption", color: "secondary", children: trustT(($) => $["makeSureToHaveYourTrustDeed"]) }),
        className: "adyen-kyc-u-margin-bottom-16"
      }
    ),
    formUtils.isRequiredField("country") && /* @__PURE__ */ jsx(
      CountryField,
      {
        data: formUtils.getFieldData(data, COUNTRY_FIELD),
        valid: formUtils.getFieldValid(valid, COUNTRY_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldProblems, COUNTRY_FIELD),
        labels: formUtils.getFieldLabels(COUNTRY_FIELD, {
          country: "countryRegionOfEstablishment"
        }),
        readonly: formUtils.isReadOnly("country"),
        allowedCountries: isUnincorporatedPartnership ? ALLOWED_UNINCORPORATED_PARTNERSHIP_COUNTRIES : ALLOWED_TRUST_COUNTRIES$1,
        handleChangeFor: () => (e) => {
          handleChangeFor("country", "input")(e);
          if (mergedProps.onCountryChange) mergedProps.onCountryChange(e);
        }
      }
    ),
    formUtils.isRequiredField("legalName") && /* @__PURE__ */ jsx(
      Field,
      {
        name: "legalName",
        label: formUtils.getLabel(
          !isUnincorporatedPartnership ? "nameOfTrustAgreement" : "legalName"
        ),
        errorMessage: formUtils.getErrorMessage("legalName", errors, fieldProblems),
        isValid: valid.legalName,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputText,
          {
            ...childProps,
            name: "legalName",
            value: data.legalName,
            readonly: formUtils.isReadOnly("legalName"),
            onInput: handleChangeFor("legalName", "input"),
            onBlur: handleChangeFor("legalName", "blur"),
            "aria-required": true,
            "aria-invalid": !valid.legalName
          }
        )
      }
    ),
    formUtils.isRequiredField("hasDoingBusinessAs") && /* @__PURE__ */ jsx(
      DBANameField,
      {
        data: formUtils.getFieldData(data, DBA_NAME_FIELD),
        valid: formUtils.getFieldValid(valid, DBA_NAME_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldProblems, DBA_NAME_FIELD),
        labels: formUtils.getFieldLabels(DBA_NAME_FIELD, {
          hasDoingBusinessAs: "hasDba"
        }),
        readonly: formUtils.isReadOnly("doingBusinessAs"),
        handleChangeFor
      }
    ),
    formUtils.isRequiredField("trustType") && !isUnincorporatedPartnership && /* @__PURE__ */ jsx(
      Field,
      {
        name: "trustType",
        label: formUtils.getLabel("trustType", "typeOfTrustAgreement"),
        errorMessage: formUtils.getErrorMessage("trustType", errors, fieldProblems),
        isValid: valid.trustType,
        dataTestId: "trust-type",
        children: (childProps) => /* @__PURE__ */ jsx(
          Select,
          {
            ...childProps,
            name: "trustType",
            onChange: changeTrustType,
            selected: data.trustType,
            items: trustTypeOptions.map((trust) => ({
              id: trust,
              name: trustT(($) => $[trust])
            })),
            placeholder: trustT(($) => $["trustType"])
          }
        )
      }
    ),
    formUtils.isRequiredField("objectOfTrust") && /* @__PURE__ */ jsx(
      Field,
      {
        name: "objectOfTrust",
        label: formUtils.getLabel("objectOfCharitableTrust"),
        helper: formUtils.getLabel("pleaseProvideThePurposeOfCharitableTrust"),
        errorMessage: formUtils.getErrorMessage("objectOfTrust", errors, fieldProblems),
        isValid: valid.objectOfTrust,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputText,
          {
            ...childProps,
            name: "objectOfTrust",
            value: data.objectOfTrust,
            readonly: formUtils.isReadOnly("objectOfTrust"),
            onInput: handleChangeFor("objectOfTrust", "input"),
            onBlur: handleChangeFor("objectOfTrust", "blur"),
            "aria-required": true,
            "aria-invalid": !valid.objectOfTrust
          }
        )
      }
    ),
    showField("taxInformation") && /* @__PURE__ */ jsx(
      TaxInformationField,
      {
        data: formUtils.getFieldData(data, TAX_INFORMATION_FIELD),
        valid: formUtils.getFieldValid(valid, TAX_INFORMATION_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldProblems, TAX_INFORMATION_FIELD),
        labels: formUtils.getFieldLabels(TAX_INFORMATION_FIELD, {
          exemptedFromTax: "iDontHaveATaxId"
        }),
        mask: formUtils.getMask("taxInformation"),
        guidanceText: formUtils.getFieldGuidanceText(TAX_INFORMATION_FIELD),
        readonly: formUtils.isReadOnly("taxInformation"),
        shouldValidate: mergedProps.shouldValidate,
        handleChangeFor,
        optional: formUtils.isOptionalField("taxInformation"),
        canExempt: formUtils.isRequiredField("exemptedFromTax"),
        country,
        entityType: LegalEntityTypes.TRUST,
        defaultData: mergedProps.data?.taxInformation,
        registrationNumber: data.registrationNumber
      }
    ),
    showField("registrationNumber") && /* @__PURE__ */ jsx(
      BusinessRegistrationNumberField,
      {
        data: formUtils.getFieldData(data, BUSINESS_REGISTRATION_NUMBER_FIELD),
        valid: formUtils.getFieldValid(valid, BUSINESS_REGISTRATION_NUMBER_FIELD),
        errors: formUtils.getFieldErrors(
          errors,
          fieldProblems,
          BUSINESS_REGISTRATION_NUMBER_FIELD
        ),
        labels: formUtils.getFieldLabels(BUSINESS_REGISTRATION_NUMBER_FIELD, {
          exemptedFromRegistrationNumber: "iDontHaveARegistrationNumber"
        }),
        mask: formUtils.getMask("registrationNumber"),
        guidanceText: formUtils.getFieldGuidanceText(BUSINESS_REGISTRATION_NUMBER_FIELD),
        helperText: getRegistrationNumberHelperText(trustT, {
          country,
          companyType: LegalEntityTypes.TRUST
        }),
        readonly: formUtils.isReadOnly("registrationNumber"),
        optional: formUtils.isOptionalField("registrationNumber"),
        shouldValidate: mergedProps.shouldValidate,
        handleChangeFor,
        country,
        canExempt: formUtils.isRequiredField("exemptedFromRegistrationNumber"),
        companyType: LegalEntityTypes.TRUST
      }
    ),
    showField("vatNumber") && /* @__PURE__ */ jsx(
      VatNumberField,
      {
        data: formUtils.getFieldData(data, VAT_NUMBER_FIELD),
        valid: formUtils.getFieldValid(valid, VAT_NUMBER_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldProblems, VAT_NUMBER_FIELD),
        labels: formUtils.getFieldLabels(VAT_NUMBER_FIELD, {
          exemptedFromVat: "iDontHaveAVatNumber"
        }),
        guidanceText: formUtils.getFieldGuidanceText(VAT_NUMBER_FIELD),
        optional: formUtils.isOptionalField("vatNumber"),
        readonly: formUtils.isReadOnly("vatNumber"),
        handleChangeFor,
        country,
        canExempt: formUtils.isRequiredField("exemptedFromVat"),
        shouldValidate: mergedProps.shouldValidate
      }
    )
  ] }) });
}
const trustForms$1 = {
  trustRegistrationDetails: {
    formId: "trustRegistrationDetails",
    formName: "registrationDetails",
    fields: [...trustRegistrationDetailsFields]
  },
  trustRegistrationAddress: {
    formId: "trustRegistrationAddress",
    formName: "addressDetails",
    fields: registrationAddressFields
  },
  trustConstitutionalDocument: {
    formId: "trustConstitutionalDocument",
    formName: "constitutionalDocument",
    fields: ["constitutionalDocument"]
  }
};
const trustRegistrationAddressFormId$1 = trustForms$1.trustRegistrationAddress.formId;
const trustRegistrationDetailsFormId$1 = trustForms$1.trustRegistrationDetails.formId;
const trustConstitutionalDocumentFormId$1 = trustForms$1.trustConstitutionalDocument.formId;
function Trust(props) {
  const { t } = useTranslation(["common", "trust"]);
  const { country, activeForm, taskType } = props;
  const trustRegistrationDetailsFormProps = getFormProps(props, trustRegistrationDetailsFormId$1);
  const trustRegistrationAddressFormProps = getNestedOuterFormPropsFromOuterFormProps(props, trustRegistrationAddressFormId$1);
  const trustDocumentFormProps = getFormProps(props, trustConstitutionalDocumentFormId$1);
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  const renderActiveForm = (activeForm2) => /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-trust", children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: activeForm2.formId !== trustRegistrationDetailsFormId$1 ? "adyen-kyc-form-wrapper adyen-kyc-form-wrapper--hidden" : "adyen-kyc-form-wrapper",
        children: /* @__PURE__ */ jsx(
          TrustRegistrationDetails,
          {
            ...trustRegistrationDetailsFormProps,
            heading: t(($) => $["registrationDetails"]),
            id: trustRegistrationDetailsFormId$1,
            country,
            taskType
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: activeForm2.formId !== trustRegistrationAddressFormId$1 ? "adyen-kyc-form-wrapper adyen-kyc-form-wrapper--hidden" : "adyen-kyc-form-wrapper",
        children: /* @__PURE__ */ jsx(
          RegistrationAddress,
          {
            ...trustRegistrationAddressFormProps,
            heading: t(($) => $["addressDetails"]),
            description: !isUnincorporatedPartnership ? t(($) => $["registeredAddressTrustHeaderDescription"], { ns: "trust" }) : t(($) => $["registeredAddressUnincorporatedPartnershipHeaderDescription"], {
              ns: "trust"
            }),
            id: trustRegistrationAddressFormId$1,
            country,
            problems: props?.problems,
            labels: {
              operationalAddressIsSame: !isUnincorporatedPartnership ? "isTrustOperationAddressSame" : "isPartnershipOperationAddressSame"
            }
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: activeForm2.formId !== trustConstitutionalDocumentFormId$1 ? "adyen-kyc-form-wrapper adyen-kyc-form-wrapper--hidden" : "adyen-kyc-form-wrapper",
        children: /* @__PURE__ */ jsx(
          MemoizedConstitutionalDocument,
          {
            ...trustDocumentFormProps,
            id: trustConstitutionalDocumentFormId$1,
            legalEntityType: isUnincorporatedPartnership ? LegalEntityTypes.UNINCORPORATED_PARTNERSHIP : LegalEntityTypes.TRUST,
            country
          }
        )
      }
    )
  ] });
  return /* @__PURE__ */ jsx("div", { className: "adyen-kyc-trust", children: renderActiveForm(activeForm || trustForms$1.trustRegistrationDetails) });
}
const mapLegalEntityToTrust = (legalEntity, isExperimentEnabled) => {
  if (!legalEntity.trust) throw new Error("LE missing trust field");
  let trustCompData = formatObject(legalEntity, trustComponentsKeyMapping);
  if (!trustCompData?.trustRegistrationDetails) return {};
  trustCompData.trustRegistrationDetails.vatNumberType = getDefaultVatNumberType(
    legalEntity.trust.vatNumber,
    legalEntity.trust.countryOfGoverningLaw
  );
  trustCompData.trustRegistrationDetails.registrationNumberType = getDefaultRegistrationNumberType(
    legalEntity.trust.registrationNumber,
    legalEntity.trust.countryOfGoverningLaw,
    LegalEntityTypes.TRUST
  );
  trustCompData.trustRegistrationDetails.country = legalEntity.trust.countryOfGoverningLaw;
  if (legalEntity.trust.description) {
    trustCompData.trustRegistrationDetails.objectOfTrust = legalEntity.trust.description;
  }
  if (legalEntity.trust.principalPlaceOfBusiness) {
    trustCompData.trustRegistrationAddress.operationalAddressIsSame = operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_NOT_SAME;
  } else {
    if (!trustCompData.trustRegistrationAddress) {
      trustCompData.trustRegistrationAddress = {};
    }
    trustCompData.trustRegistrationAddress.operationalAddressIsSame = operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_SAME;
  }
  if (legalEntity.trust.taxInformation?.length) {
    const { country } = legalEntity.trust.registeredAddress;
    const countryTaxInformation = legalEntity.trust.taxInformation.find(
      (info) => info.country === country
    );
    if (countryTaxInformation?.type === "UEN") {
      trustCompData.trustRegistrationDetails.isUen = true;
    }
    if (countryTaxInformation?.type === "GST") {
      trustCompData.trustRegistrationDetails.isUen = false;
    }
    const taxNumberAbsent = countryTaxInformation?.numberAbsent;
    if (taxNumberAbsent !== void 0) {
      trustCompData.trustRegistrationDetails.exemptedFromTax = taxNumberAbsent;
    }
  }
  if (legalEntity.documentDetails?.length) {
    trustCompData = {
      ...trustCompData,
      ...mapApiDocumentToTrustDocument(legalEntity?.id)
    };
  }
  if (isExperimentEnabled("EnableDoingBusinessAsNameV4")) {
    if (typeof trustCompData.trustRegistrationDetails?.hasDoingBusinessAs === "boolean") {
      trustCompData.trustRegistrationDetails.hasDoingBusinessAs = !legalEntity.trust.doingBusinessAsAbsent;
      if (!trustCompData.trustRegistrationDetails.hasDoingBusinessAs)
        delete legalEntity.trust?.doingBusinessAs;
    }
  } else {
    trustCompData.trustRegistrationDetails.hasDoingBusinessAs = legalEntity.trust.doingBusinessAs ? legalEntity.trust.doingBusinessAs !== legalEntity.trust.name : void 0;
    trustCompData.trustRegistrationDetails.doingBusinessAs = legalEntity.trust.doingBusinessAs;
  }
  return trustCompData;
};
const mapTrustDocumentToApiDocument = async (data, entityId) => {
  const constitutionalDocument = data?.trustConstitutionalDocument?.constitutionalDocument;
  if (!constitutionalDocument) {
    throw new Error("Constitutional document missing");
  }
  const page1 = constitutionalDocument[0];
  if (!page1) {
    throw new Error("Document needs at least one page");
  }
  const existingDocument = getDocument(entityId, "constitutionalDocument");
  return await createDocumentRequest({
    entityId,
    entityType: "legalEntity",
    documentType: "constitutionalDocument",
    page1,
    existingDocument
  });
};
const mapTrustToLegalEntity = (data, isExperimentEnabled) => {
  const requestObj = {
    ...formatObject(data, trustApiKeyMapping)
  };
  if (!requestObj.trust) return requestObj;
  if (data.trustRegistrationDetails?.objectOfTrust) {
    requestObj.trust.description = data.trustRegistrationDetails.objectOfTrust;
  }
  if (isExperimentEnabled("EnableDoingBusinessAsNameV4")) {
    requestObj.trust.doingBusinessAsAbsent = typeof data.trustRegistrationDetails?.hasDoingBusinessAs !== "undefined" ? !data.trustRegistrationDetails?.hasDoingBusinessAs : void 0;
    if (requestObj.trust.doingBusinessAsAbsent) {
      requestObj.trust.doingBusinessAs = "";
    }
  } else {
    delete requestObj.trust?.doingBusinessAsAbsent;
    requestObj.trust.doingBusinessAs = data.trustRegistrationDetails?.doingBusinessAs || data.trustRegistrationDetails?.legalName;
  }
  requestObj.type = LegalEntityTypes.TRUST;
  return requestObj;
};
const MANDATORY_FIELDS_TRUST = [
  "trustRegistrationDetails.legalName",
  "trustRegistrationDetails.country"
];
const trustBase = {
  trustType: {
    rule: "REQUIRED"
  },
  objectOfTrust: {
    rule: "trustTypeHasDescription"
  },
  legalName: {
    rule: "REQUIRED"
  },
  hasDoingBusinessAs: {
    rule: "hasDoingBusinessAs"
  },
  doingBusinessAs: {
    rule: "hasDoingBusinessAs"
  },
  country: {
    rule: "REQUIRED"
  },
  taxInformation: {
    rule: "countryUsesTaxId"
  },
  registrationAddress: {
    rule: "REQUIRED"
  },
  operationalAddress: {
    rule: "OPTIONAL"
  },
  constitutionalDocument: {
    rule: "REQUIRED"
  },
  registrationNumber: { rule: "countryRequiresRegistrationNumberForTrust" },
  registrationNumberType: { rule: "registrationNumberType" },
  vatNumber: { rule: "countryUsesVatNumber" },
  vatNumberType: { rule: "countryUsesVatNumber" },
  operationalAddressIsSame: {
    rule: "REQUIRED"
  }
};
const trustFieldsPerScenario = {
  L0: {
    ...trustBase
  },
  L1: {
    ...trustBase
  },
  L: {
    ...trustBase
  }
};
const trustCountryConfig = {};
const parseTrustScenarios$1 = (scenarios, country) => augmentWithCountryConfigs(
  trustCountryConfig[country],
  composePerScenarioFormConfigurations(scenarios, trustFieldsPerScenario)
);
const parseConfiguration$1 = ({ scenarios, country }) => parseTrustScenarios$1(scenarios, country);
function TrustDropin({
  parentLegalEntity,
  capabilities,
  country: countryProp,
  existingTrust,
  taskType,
  problems: problemsProp,
  onSubmit: externalOnSubmit,
  onChange,
  hideSidebar,
  handleHomeClick
}) {
  const {
    state: { currentState }
  } = useStateContext();
  const formValidity = currentState.validityByForm;
  useEffect(() => {
    onChange?.(currentState);
  }, [currentState, onChange]);
  const { baseUrl, rootLegalEntityId } = useApiContext();
  const { t, i18n } = useTranslation(["common", "trust"]);
  const userEvents = useAnalyticsContext();
  const [validationErrors, setValidationErrors] = useState();
  const datasetUtils = datasetUtilities(i18n.language);
  const { isExperimentEnabled } = useExperimentsContext();
  const { showToast } = useToastContext();
  const [loadingStatus, setLoadingStatus] = useState("success");
  const formRef = useRef(null);
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  const problems = useMemo(
    () => ({
      ...problemsProp,
      validationErrors
    }),
    [problemsProp, validationErrors]
  );
  const trustData = useMemo(() => {
    if (!existingTrust) return {};
    return isUnincorporatedPartnership ? mapLegalEntityToUnincorporatedPartnership(existingTrust, isExperimentEnabled) : mapLegalEntityToTrust(existingTrust, isExperimentEnabled);
  }, [isExperimentEnabled, existingTrust, isUnincorporatedPartnership]);
  const currentCountry = useMemo(
    () => currentState.data.trustRegistrationDetails?.country ?? countryProp,
    [countryProp, currentState.data.trustRegistrationDetails?.country]
  );
  const [initialData, setInitialData] = useState(trustData);
  useEffect(() => {
    userEvents.updateBaseTrackingPayload({ task: taskType });
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
    if (!existingTrust?.documentDetails?.length) return;
    try {
      documentUtils.fetchDocuments(existingTrust.documentDetails, existingTrust.id).then(() => {
        const mappedDocuments = mapApiDocumentToTrustDocument(existingTrust.id);
        setInitialData({
          ...initialData,
          ...mappedDocuments
        });
      }).catch(() => {
        showToast({ label: t(($) => $["failedToFetchRelevantDocuments"]), variant: "error" });
      });
    } catch {
      showToast({ label: t(($) => $["failedToFetchRelevantDocuments"]), variant: "error" });
    }
  }, []);
  const { fieldConfigurations, requiredFields } = useScenarioConfiguration({
    parseConfiguration: parseConfiguration$1,
    legalEntityType: LegalEntityTypes.TRUST,
    setLoadingStatus,
    country: currentCountry
  });
  const fieldsFromCustomRules = useMemo(
    () => rules({
      data: currentState.data,
      country: currentCountry,
      taskType,
      isExperimentEnabled
    }),
    [currentCountry, currentState.data, taskType, requiredFields, isExperimentEnabled]
  );
  const derivedProps = useMemo(
    () => getPropsFromConfigurations({
      scenarioConfiguration: fieldConfigurations,
      forms: trustForms$1,
      remediationActions: problems?.remediationActions ? Object.values(problems?.remediationActions) : [],
      dataMissingErrors: problems?.missingData ?? [],
      fieldsWithExistingData: existingTrust ? getFieldsWithExistingData(existingTrust, trustApiKeyMapping, trustDocumentMapping) : [],
      customRules: fieldsFromCustomRules,
      legalEntityType: existingTrust?.type
    }),
    [
      fieldConfigurations,
      problems?.remediationActions,
      problems?.missingData,
      existingTrust,
      fieldsFromCustomRules
    ]
  );
  const forms = useMemo(() => {
    const requiredForms = getRequiredForms(
      trustForms$1,
      derivedProps?.requiredFields,
      derivedProps?.optionalFields
    );
    return addValidityToForms(requiredForms, formValidity, problems);
  }, [derivedProps, formValidity, problems]);
  const onSubmitTrust = async () => {
    setLoadingStatus("loading");
    const trustDetails = mapTrustToLegalEntity(currentState.data, isExperimentEnabled);
    try {
      const updatedTrust = await submitTrustDetails(trustDetails);
      await submitDocuments({ forms, legalEntity: updatedTrust, dataSubmitted: currentState.data });
      await attachTrustToParentLegalEntity(updatedTrust);
      setLoadingStatus("success");
      showToast({ label: t(($) => $["successfullyUpdatedDetails"]), variant: "success" });
      externalOnSubmit?.(currentState.data);
    } catch (e) {
      showToast({ label: t(($) => $["failedToUpdateDetails"]), variant: "error" });
      if (isValidationError(e)) {
        setValidationErrors(processValidationErrors(e, taskType));
      } else if (isMaintenanceModeError(e)) {
        showToast({
          label: t(($) => $["maintenanceModeMessage"]),
          variant: "error",
          duration: "indefinite"
        });
      }
      setLoadingStatus("success");
    }
  };
  const onSubmitUnincorporatedPartnership = async () => {
    setLoadingStatus("loading");
    const unincorporatedPartnershipDetails = mapUnincorporatedPartnershipToLegalEntity(
      currentState.data,
      isExperimentEnabled
    );
    try {
      const updatedUnincorporatedPartnershipDetails = await submitTrustDetails(
        unincorporatedPartnershipDetails
      );
      await submitDocuments({
        forms,
        legalEntity: updatedUnincorporatedPartnershipDetails,
        dataSubmitted: currentState.data
      });
      await attachTrustToParentLegalEntity(updatedUnincorporatedPartnershipDetails);
      setLoadingStatus("success");
      showToast({ label: t(($) => $["successfullyUpdatedDetails"]), variant: "success" });
      externalOnSubmit?.(currentState.data);
    } catch (e) {
      showToast({ label: t(($) => $["failedToUpdateDetails"]), variant: "error" });
      if (isValidationError(e)) {
        setValidationErrors(processValidationErrors(e, taskType));
      } else if (isMaintenanceModeError(e)) {
        showToast({
          label: t(($) => $["maintenanceModeMessage"]),
          variant: "error",
          duration: "indefinite"
        });
      }
      setLoadingStatus("success");
    }
  };
  const { mutateAsync: createLegalEntity } = useCreateLegalEntity();
  const { mutateAsync: updateLegalEntity } = useUpdateLegalEntity();
  const submitTrustDetails = async (legalEntity) => {
    if (!existingTrust) {
      return await createLegalEntity(legalEntity);
    } else {
      return await updateLegalEntity({
        ...drop("type").from(legalEntity),
        id: existingTrust.id
      });
    }
  };
  const documentUtils = documentApiUtils({
    baseUrl: baseUrl.value,
    rootLegalEntityId: rootLegalEntityId.value
  });
  const submitDocuments = async ({
    forms: forms2,
    legalEntity,
    dataSubmitted
  }) => {
    if (isDocumentsRequired(forms2)) {
      const formattedDocument = await mapTrustDocumentToApiDocument(dataSubmitted, legalEntity.id);
      if (formattedDocument) {
        await documentUtils.uploadDocuments([formattedDocument], legalEntity.id);
      }
    }
  };
  const isDocumentsRequired = (forms2) => forms2.some((form) => form.formId === trustForms$1.trustConstitutionalDocument.formId);
  const attachTrustToParentLegalEntity = async (trust) => {
    if (existingTrust?.id) {
      return;
    }
    const existingEntityAssociations = getOwnEntityAssociations(parentLegalEntity);
    const updatedParentLegalEntity = {
      entityAssociations: [
        {
          type: trust.type,
          legalEntityId: trust.id
        },
        ...existingEntityAssociations
      ]
    };
    await updateLegalEntity({ ...updatedParentLegalEntity, id: parentLegalEntity.id });
  };
  const formatDataForSummary = (formData, forms2) => {
    let summaryData = cloneObject(formData) || {};
    const country = formData.trustRegistrationDetails?.country ?? (existingTrust ? getLegalEntityCountry(existingTrust) : getLegalEntityCountry(parentLegalEntity));
    if (formData.trustRegistrationDetails) {
      const trustCountry = formData.trustRegistrationDetails.country && datasetUtils.getCountryName(formData.trustRegistrationDetails.country);
      const trustType = formData.trustRegistrationDetails.trustType && t(($) => $[formData.trustRegistrationDetails.trustType], { ns: "trust" });
      const registrationNumberLabel = resolveFieldMetadata(
        registrationNumberDefaultFieldConfig[country],
        {
          companyType: LegalEntityTypes.TRUST,
          registrationNumberType: formData.trustRegistrationDetails.registrationNumber ? inferCompanyRegistrationNumberType(
            formData.trustRegistrationDetails.registrationNumber,
            country,
            LegalEntityTypes.TRUST
          ) : getCompanyRegistrationNumberOptions(country, LegalEntityTypes.TRUST)?.[0]?.id
        },
        registrationNumberDefaultFieldMetadata
      ).label;
      const taxIdLabel = resolveFieldMetadata(
        taxInformationDefaultFieldConfig[country],
        {
          companyType: LegalEntityTypes.TRUST,
          taxIdNumberType: countryToTaxInfoTypeMap[country]
        },
        taxInformationDefaultFieldMetadata
      ).label;
      summaryData.trustRegistrationDetails = {
        [isUnincorporatedPartnership ? "legalName" : "nameOfTrustAgreement"]: formData.trustRegistrationDetails?.legalName,
        doingBusinessAs: formData.trustRegistrationDetails?.doingBusinessAs,
        countryRegionOfEstablishment: trustCountry,
        typeOfTrustAgreement: isUnincorporatedPartnership ? void 0 : trustType,
        objectOfTrust: formData.trustRegistrationDetails?.objectOfTrust,
        [taxIdLabel]: formData.trustRegistrationDetails?.taxInformation?.find(
          (taxId) => country === taxId.country
        )?.number,
        [registrationNumberLabel]: formData.trustRegistrationDetails.registrationNumber
      };
    }
    if (formData.trustRegistrationAddress?.registrationAddress) {
      summaryData.trustRegistrationAddress.hasInnerForms = true;
      summaryData.trustRegistrationAddress.registrationAddress = mapAddressLabels(
        formData.trustRegistrationAddress.registrationAddress,
        datasetUtils
      );
    }
    if (formData.trustRegistrationAddress?.operationalAddress) {
      summaryData.trustRegistrationAddress.operationalAddress = mapAddressLabels(
        formData.trustRegistrationAddress.operationalAddress,
        datasetUtils
      );
    }
    if (isDocumentsRequired(forms2)) {
      summaryData = {
        ...summaryData,
        ...formatFileSummaryData(formData.trustConstitutionalDocument)
      };
    } else {
      delete summaryData[trustConstitutionalDocumentFormId$1];
    }
    return summaryData;
  };
  const formatFileSummaryData = (trustConstitutionalDocument) => {
    const constitutionalDocument = trustConstitutionalDocument?.constitutionalDocument?.[0];
    return {
      ...constitutionalDocument && {
        trustConstitutionalDocument: {
          fileName: constitutionalDocument.name
        }
      }
    };
  };
  const canSubmit = (formData) => MANDATORY_FIELDS_TRUST.every((detail) => {
    const value = getProp(formData, detail);
    return !isEmpty$1(value);
  });
  const {
    handleNextClick,
    handleBackClick,
    activeForm,
    shouldValidate,
    setShouldValidate,
    gotoFormByFormIndex,
    steps
  } = useFormComposer({
    problems,
    forms,
    onSubmit: isUnincorporatedPartnership ? onSubmitUnincorporatedPartnership : onSubmitTrust
  });
  return /* @__PURE__ */ jsx(
    FormWrapper,
    {
      taskName: isUnincorporatedPartnership ? "unincorporatedDetails" : "trustDetails",
      handleNextClick,
      handleBackClick,
      gotoFormByFormIndex,
      loadingStatus,
      forms,
      activeForm,
      onSubmit: isUnincorporatedPartnership ? onSubmitUnincorporatedPartnership : onSubmitTrust,
      hideSidebar,
      handleHomeClick,
      validateForm: () => setShouldValidate(true),
      canSubmit: canSubmit(currentState.data) && hasDataChanged(initialData, currentState.data),
      problems,
      summary: {
        data: formatDataForSummary(currentState.data, forms),
        omitted: {
          keys: ["operationalAddressIsSame"]
        }
      },
      steps,
      children: /* @__PURE__ */ jsx(
        Trust,
        {
          ...derivedProps,
          activeForm,
          capabilities,
          data: initialData,
          country: currentCountry,
          problems,
          shouldValidate,
          ref: formRef,
          taskType
        }
      )
    }
  );
}
const registrationAddressForms = {
  registrationAddress: {
    formId: "registrationAddress"
  }
};
const registrationAddressFormID = registrationAddressForms.registrationAddress.formId;
function RegistrationAddressMultiform(props) {
  const { t } = useTranslation("common");
  const { id, heading, description, country, problems } = props;
  const { form } = useFormContext();
  const data = form.data.trustRegistrationAddress;
  const {
    requiredFields: registrationAddressRequiredFields,
    optionalFields: registrationAddressOptionalFields,
    readOnlyFields: registrationAddressReadOnlyFields,
    obscuredFields: registrationAddressObscuredFields,
    verifyFields: registrationAddressVerifyFields,
    trustedFields: registrationAddressTrustedFields
  } = getFormProps(props, registrationAddressFormID);
  const mergedProps = {
    ...props,
    requiredFields: registrationAddressRequiredFields,
    optionalFields: registrationAddressOptionalFields,
    readOnlyFields: registrationAddressReadOnlyFields,
    obscuredFields: registrationAddressObscuredFields,
    trustedFields: registrationAddressTrustedFields
  };
  const formUtils = createFormUtils(mergedProps, t);
  const isOperationAddressNotSame = () => data?.operationalAddressIsSame === operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_NOT_SAME;
  const handleChangeFor = useCallback(
    (fieldName, mode) => form.handleChangeFor(fieldName, "trustRegistrationAddress", mode),
    [form]
  );
  const handleRegistrationAddressChange = (state) => {
    handleChangeFor("registrationAddress")(state.data);
    form.setValid("registrationAddress", Boolean(state.isValid), "trustRegistrationAddress");
  };
  const handleOperationalAddressChange = (state) => {
    handleChangeFor("operationalAddress")(state.data);
    form.setValid("operationalAddress", Boolean(state.isValid), "trustRegistrationAddress");
  };
  const handleOperationalAddressIsSameChange = (value) => {
    handleChangeFor("operationalAddressIsSame")(value);
    if (value === "OperationAddressAnswerYes") {
      form.setValid("operationalAddress", true, "trustRegistrationAddress");
    }
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    heading && /* @__PURE__ */ jsx(Header, { title: heading, description }),
    /* @__PURE__ */ jsx(
      ErrorPanel,
      {
        verificationErrors: id ? problems?.verificationErrors?.[id] : void 0,
        validationErrors: id ? problems?.validationErrors?.[id] : void 0,
        formUtils,
        id: "ariaErrorField"
      }
    ),
    /* @__PURE__ */ jsx(
      ContextGuidance,
      {
        titleId: "whyDoINeedToFillInThisInformation",
        contentId: "reasonForFillingCompanyAddressDetails",
        title: t(($) => $["whyDoINeedToFillInThisInformation"]),
        content: t(($) => $["reasonForFillingCompanyAddressDetails"])
      }
    ),
    /* @__PURE__ */ jsx(
      Address,
      {
        data: { ...form.data?.trustRegistrationAddress?.registrationAddress, country },
        hideCountry: true,
        id,
        addressType: "registrationAddress",
        optionalFields: ["otherAddressInformation"],
        onChange: handleRegistrationAddressChange
      }
    ),
    /* @__PURE__ */ jsx(Header, { title: t(($) => $["operationalAddressHeader"]), secondary: true }),
    /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "operationalAddressIsSame",
        label: formUtils.getLabel("operationalAddressIsSame"),
        errorMessage: form.errors.trustRegistrationAddress?.operationalAddressIsSame?.errorMessage,
        children: (childProps) => /* @__PURE__ */ jsx(
          RadioGroup,
          {
            ...childProps,
            name: "operationalAddressIsSame",
            items: operationalAddressIsSameItems,
            value: data?.operationalAddressIsSame,
            disabled: formUtils.isReadOnly("operationalAddressIsSame"),
            onChange: handleOperationalAddressIsSameChange,
            "aria-required": true,
            "aria-invalid": !form.valid.trustRegistrationAddress?.operationalAddressIsSame
          }
        )
      }
    ),
    isOperationAddressNotSame() && /* @__PURE__ */ jsx(
      Address,
      {
        data: { ...form.data?.trustRegistrationAddress?.operationalAddress, country },
        hideCountry: true,
        id,
        optionalFields: ["otherAddressInformation"],
        addressType: "operationalAddress",
        onChange: handleOperationalAddressChange
      },
      "operationalAddress"
    )
  ] });
}
const ALLOWED_TRUST_COUNTRIES = [CountryCodes.Australia, CountryCodes.NewZealand];
const TRUST_REGISTRATION_DETAILS = trustForms$1.trustRegistrationDetails.formId;
function TrustRegistrationDetailsMultiform({
  fieldValidationErrors = {},
  formVerificationErrors = {},
  heading,
  shouldValidate,
  taskType,
  country: parentLegalEntityCountry
}) {
  const { t: trustT } = useTranslation("trust");
  const { t: CommonT } = useTranslation("common");
  const { form } = useFormContext();
  const { isExperimentEnabled } = useExperimentsContext();
  const {
    data,
    valid,
    errors,
    allFields,
    trustedFields,
    obscuredFields,
    optionalFields,
    requiredFields
  } = useMemo(() => {
    return {
      data: form.data.trustRegistrationDetails ?? {},
      valid: form.valid.trustRegistrationDetails ?? {},
      errors: form.errors.trustRegistrationDetails ?? {},
      allFields: form.allFields?.trustRegistrationDetails ?? [],
      trustedFields: form.trustedFields?.trustRegistrationDetails ?? [],
      obscuredFields: form.obscuredFields?.trustRegistrationDetails ?? [],
      optionalFields: form.optionalFields?.trustRegistrationDetails ?? [],
      requiredFields: form.requiredFields?.trustRegistrationDetails ?? []
    };
  }, [form]);
  const country = data?.country ?? parentLegalEntityCountry;
  const trustTypeOptions = getCountrySpecificTrustTypeOptions(country) ?? [];
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  const handleChange = (fieldName, mode) => form.handleChangeFor(fieldName, "trustRegistrationDetails", mode);
  const changeTrustType = (e) => {
    handleChange("trustType", "blur")(e);
    if (e.target.value !== "charitableTrust") {
      form.setData("objectOfTrust", void 0, TRUST_REGISTRATION_DETAILS);
    }
  };
  const formUtils = useMemo(() => {
    const initialProps = {
      data,
      valid,
      errors,
      fieldValidationErrors,
      formVerificationErrors,
      allFields,
      trustedFields,
      obscuredFields,
      optionalFields,
      requiredFields
    };
    const formUtilProps = initialProps?.allFields?.reduce((acc, field) => {
      switch (field) {
        case "hasDoingBusinessAs":
          return mergeFieldMetadataIntoProps(
            "hasDoingBusinessAs",
            doingBusinessAsAbsentFieldMetadata,
            acc
          );
        case "doingBusinessAs":
          return mergeFieldMetadataIntoProps(
            "doingBusinessAs",
            doingBusinessAsFieldMetadata,
            acc
          );
        case "taxInformation":
          return mergeFieldMetadataIntoProps(
            "taxInformation",
            resolveFieldMetadata(
              taxInformationDefaultFieldConfig[country],
              {
                taxIdNumberType: data.taxInformation?.find(
                  (taxId) => taxId.country === country
                )?.type,
                companyType: LegalEntityTypes.TRUST
              },
              taxInformationDefaultFieldMetadata
            ),
            acc
          );
        case "exemptedFromTax":
          return mergeFieldMetadataIntoProps(
            "exemptedFromTax",
            resolveFieldMetadata(
              exemptedFromTaxDefaultFieldConfig[country],
              {},
              exemptedFromTaxDefaultFieldMetadata
            ),
            acc
          );
        case "registrationNumber":
          return mergeFieldMetadataIntoProps(
            "registrationNumber",
            resolveFieldMetadata(
              registrationNumberDefaultFieldConfig[country],
              {
                companyType: LegalEntityTypes.TRUST,
                registrationNumberType: data.registrationNumberType,
                isExperimentEnabled
              },
              registrationNumberDefaultFieldMetadata
            ),
            acc
          );
        case "exemptedFromRegistrationNumber":
          return mergeFieldMetadataIntoProps(
            "exemptedFromRegistrationNumber",
            resolveFieldMetadata(
              exemptFromRegistrationNumberDefaultFieldConfig[country],
              {},
              exemptFromRegistrationNumberDefaultFieldMetadata
            ),
            acc
          );
        case "vatNumber":
          return mergeFieldMetadataIntoProps(
            "vatNumber",
            resolveFieldMetadata(
              defaultFieldConfig[country],
              { vatNumberType: data?.vatNumberType },
              defaultFieldMetadata
            ),
            acc
          );
        default:
          return acc;
      }
    }, initialProps);
    return createFormUtils(formUtilProps ?? initialProps, CommonT);
  }, [
    CommonT,
    allFields,
    country,
    data,
    errors,
    fieldValidationErrors,
    formVerificationErrors,
    isExperimentEnabled,
    obscuredFields,
    optionalFields,
    requiredFields,
    trustedFields,
    valid
  ]);
  const showField = (fieldName) => formUtils.isRequiredField(fieldName) || formUtils.isOptionalField(fieldName);
  return /* @__PURE__ */ jsxs("form", { id: TRUST_REGISTRATION_DETAILS, className: "adyen-kyc-trust__registration-details", children: [
    heading && /* @__PURE__ */ jsx(Header, { title: heading }),
    /* @__PURE__ */ jsx(
      ErrorPanel,
      {
        verificationErrors: formVerificationErrors,
        validationErrors: fieldValidationErrors,
        formUtils,
        id: "ariaErrorField"
      }
    ),
    !isUnincorporatedPartnership && /* @__PURE__ */ jsx(
      Alert,
      {
        variant: "info",
        title: /* @__PURE__ */ jsx(Typography, { variant: "caption", color: "secondary", children: trustT(($) => $["makeSureToHaveYourTrustDeed"]) }),
        className: "adyen-kyc-u-margin-bottom-16"
      }
    ),
    formUtils.isRequiredField("country") && /* @__PURE__ */ jsx(
      CountryField,
      {
        data: formUtils.getFieldData(data, COUNTRY_FIELD),
        valid: formUtils.getFieldValid(valid, COUNTRY_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldValidationErrors, COUNTRY_FIELD),
        labels: formUtils.getFieldLabels(COUNTRY_FIELD, {
          country: "countryRegionOfEstablishment"
        }),
        readonly: formUtils.isReadOnly("country"),
        allowedCountries: isUnincorporatedPartnership ? ALLOWED_UNINCORPORATED_PARTNERSHIP_COUNTRIES : ALLOWED_TRUST_COUNTRIES,
        handleChangeFor: () => (e) => {
          handleChange("country", "input")(e);
        }
      }
    ),
    formUtils.isRequiredField("legalName") && /* @__PURE__ */ jsx(
      Field,
      {
        name: "legalName",
        label: formUtils.getLabel(
          isUnincorporatedPartnership ? "legalName" : "nameOfTrustAgreement"
        ),
        errorMessage: formUtils.getErrorMessage("legalName", errors, fieldValidationErrors),
        isValid: valid?.legalName,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputText,
          {
            ...childProps,
            name: "legalName",
            value: data?.legalName,
            readonly: formUtils.isReadOnly("legalName"),
            onInput: handleChange("legalName", "input"),
            onBlur: handleChange("legalName", "blur"),
            "aria-required": true,
            "aria-invalid": !valid?.legalName
          }
        )
      }
    ),
    formUtils.isRequiredField("hasDoingBusinessAs") && /* @__PURE__ */ jsx(
      DBANameField,
      {
        data: formUtils.getFieldData(data, DBA_NAME_FIELD),
        valid: formUtils.getFieldValid(valid, DBA_NAME_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldValidationErrors, DBA_NAME_FIELD),
        labels: formUtils.getFieldLabels(DBA_NAME_FIELD, {
          hasDoingBusinessAs: "hasDba"
        }),
        readonly: formUtils.isReadOnly("doingBusinessAs"),
        handleChangeFor: handleChange
      }
    ),
    formUtils.isRequiredField("trustType") && !isUnincorporatedPartnership && /* @__PURE__ */ jsx(
      Field,
      {
        name: "trustType",
        label: formUtils.getLabel("trustType", "typeOfTrustAgreement"),
        errorMessage: formUtils.getErrorMessage("trustType", errors, fieldValidationErrors),
        isValid: valid?.trustType,
        dataTestId: "trust-type",
        children: (childProps) => /* @__PURE__ */ jsx(
          Select,
          {
            ...childProps,
            name: "trustType",
            onChange: changeTrustType,
            selected: data?.trustType,
            items: trustTypeOptions.map((trust) => ({
              id: trust,
              name: trustT(($) => $[trust])
            })),
            placeholder: trustT(($) => $["trustType"])
          }
        )
      }
    ),
    formUtils.isRequiredField("objectOfTrust") && /* @__PURE__ */ jsx(
      Field,
      {
        name: "objectOfTrust",
        label: formUtils.getLabel("objectOfCharitableTrust"),
        helper: formUtils.getLabel("pleaseProvideThePurposeOfCharitableTrust"),
        errorMessage: formUtils.getErrorMessage("objectOfTrust", errors, fieldValidationErrors),
        isValid: valid?.objectOfTrust,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputText,
          {
            ...childProps,
            name: "objectOfTrust",
            value: data?.objectOfTrust,
            readonly: formUtils.isReadOnly("objectOfTrust"),
            onInput: handleChange("objectOfTrust", "input"),
            onBlur: handleChange("objectOfTrust", "blur"),
            "aria-required": true,
            "aria-invalid": !valid?.objectOfTrust
          }
        )
      }
    ),
    showField("taxInformation") && /* @__PURE__ */ jsx(
      TaxInformationField,
      {
        data: formUtils.getFieldData(data, TAX_INFORMATION_FIELD),
        valid: formUtils.getFieldValid(valid, TAX_INFORMATION_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldValidationErrors, TAX_INFORMATION_FIELD),
        labels: formUtils.getFieldLabels(TAX_INFORMATION_FIELD, {
          exemptedFromTax: "iDontHaveATaxId"
        }),
        mask: formUtils.getMask("taxInformation"),
        guidanceText: formUtils.getFieldGuidanceText(TAX_INFORMATION_FIELD),
        readonly: formUtils.isReadOnly("taxInformation"),
        shouldValidate,
        handleChangeFor: handleChange,
        optional: formUtils.isOptionalField("taxInformation"),
        canExempt: formUtils.isRequiredField("exemptedFromTax"),
        country: data?.country,
        entityType: LegalEntityTypes.TRUST,
        defaultData: data?.taxInformation,
        registrationNumber: data.registrationNumber
      }
    ),
    showField("registrationNumber") && /* @__PURE__ */ jsx(
      BusinessRegistrationNumberField,
      {
        data: formUtils.getFieldData(data, BUSINESS_REGISTRATION_NUMBER_FIELD),
        valid: formUtils.getFieldValid(valid, BUSINESS_REGISTRATION_NUMBER_FIELD),
        errors: formUtils.getFieldErrors(
          errors,
          fieldValidationErrors,
          BUSINESS_REGISTRATION_NUMBER_FIELD
        ),
        labels: formUtils.getFieldLabels(BUSINESS_REGISTRATION_NUMBER_FIELD, {
          exemptedFromRegistrationNumber: "iDontHaveARegistrationNumber"
        }),
        mask: formUtils.getMask("registrationNumber"),
        guidanceText: formUtils.getFieldGuidanceText(BUSINESS_REGISTRATION_NUMBER_FIELD),
        helperText: getRegistrationNumberHelperText(trustT, {
          country,
          companyType: LegalEntityTypes.TRUST
        }),
        readonly: formUtils.isReadOnly("registrationNumber"),
        optional: formUtils.isOptionalField("registrationNumber"),
        shouldValidate,
        handleChangeFor: handleChange,
        country,
        canExempt: formUtils.isRequiredField("exemptedFromRegistrationNumber"),
        companyType: LegalEntityTypes.TRUST
      }
    ),
    showField("vatNumber") && /* @__PURE__ */ jsx(
      VatNumberField,
      {
        data: formUtils.getFieldData(data, VAT_NUMBER_FIELD),
        valid: formUtils.getFieldValid(valid, VAT_NUMBER_FIELD),
        errors: formUtils.getFieldErrors(errors, fieldValidationErrors, VAT_NUMBER_FIELD),
        labels: formUtils.getFieldLabels(VAT_NUMBER_FIELD, {
          exemptedFromVat: "iDontHaveAVatNumber"
        }),
        guidanceText: formUtils.getFieldGuidanceText(VAT_NUMBER_FIELD),
        optional: formUtils.isOptionalField("vatNumber"),
        readonly: formUtils.isReadOnly("vatNumber"),
        handleChangeFor: handleChange,
        country,
        canExempt: formUtils.isRequiredField("exemptedFromVat")
      }
    )
  ] });
}
const trustForms = {
  trustRegistrationDetails: {
    formId: "trustRegistrationDetails",
    fields: [...trustRegistrationDetailsFields]
  },
  trustRegistrationAddress: {
    formId: "trustRegistrationAddress"
  },
  trustConstitutionalDocument: {
    formId: "trustConstitutionalDocument"
  }
};
const trustRegistrationAddressFormId = trustForms.trustRegistrationAddress.formId;
const trustRegistrationDetailsFormId = trustForms.trustRegistrationDetails.formId;
const trustConstitutionalDocumentFormId = trustForms.trustConstitutionalDocument.formId;
function TrustMultiform(props) {
  const { t } = useTranslation(["common", "trust"]);
  const { country, activeForm, taskType, shouldValidate, problems = {} } = props;
  const { form } = useFormContext();
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  function handleChange(formName, fieldName, mode) {
    return form.handleChangeFor(fieldName, formName, mode);
  }
  const renderActiveForm = (activeForm2) => {
    switch (activeForm2.formId) {
      case trustRegistrationDetailsFormId:
        return /* @__PURE__ */ jsx(
          TrustRegistrationDetailsMultiform,
          {
            heading: t(($) => $["registrationDetails"]),
            id: trustRegistrationDetailsFormId,
            taskType,
            shouldValidate,
            country
          }
        );
      case trustRegistrationAddressFormId:
        return /* @__PURE__ */ jsx(
          RegistrationAddressMultiform,
          {
            heading: t(($) => $["addressDetails"]),
            description: !isUnincorporatedPartnership ? t(($) => $["registeredAddressTrustHeaderDescription"], { ns: "trust" }) : t(($) => $["registeredAddressUnincorporatedPartnershipHeaderDescription"], {
              ns: "trust"
            }),
            id: trustRegistrationAddressFormId,
            country,
            problems,
            labels: {
              operationalAddressIsSame: !isUnincorporatedPartnership ? "isTrustOperationAddressSame" : "isPartnershipOperationAddressSame"
            },
            shouldValidate
          }
        );
      case trustConstitutionalDocumentFormId:
        return /* @__PURE__ */ jsx(
          MemoizedConstitutionalDocument,
          {
            id: activeForm2.formId,
            legalEntityType: isUnincorporatedPartnership ? LegalEntityTypes.UNINCORPORATED_PARTNERSHIP : LegalEntityTypes.TRUST,
            country,
            data: form.data?.trustConstitutionalDocument,
            errors: form.errors.trustConstitutionalDocument,
            valid: form.valid.trustConstitutionalDocument,
            allFields: form.allFields?.trustConstitutionalDocument,
            requiredFields: form.requiredFields?.trustConstitutionalDocument,
            optionalFields: form.optionalFields?.trustConstitutionalDocument,
            trustedFields: form.trustedFields?.trustConstitutionalDocument,
            handleFieldChange: () => handleChange("trustConstitutionalDocument", "constitutionalDocument"),
            shouldValidate,
            fieldValidationErrors: problems.validationErrors?.[activeForm2.formId] ?? {},
            formVerificationErrors: problems.verificationErrors?.[activeForm2.formId] ?? {}
          }
        );
      default:
        return null;
    }
  };
  return /* @__PURE__ */ jsx("div", { className: "adyen-kyc-trust", children: /* @__PURE__ */ jsx("div", { className: "adyen-kyc-form-wrapper", children: renderActiveForm(activeForm || trustForms.trustRegistrationDetails) }) });
}
function trustRegistrationDetailsValidators(country, trustRegistrationDetails = {}, isExperimentEnabled) {
  const isStrictNameAndAddressValidationEnabled = isExperimentEnabled(
    "StrictNameAndAddressValidationV4"
  );
  const defaultTrustRegistrationDetailsValidators = isStrictNameAndAddressValidationEnabled ? trustRegistrationDetailsValidationsV4 : trustRegistrationDetailsValidations;
  const { registrationNumberType, taxInformation, vatNumberType } = trustRegistrationDetails;
  return {
    ...defaultTrustRegistrationDetailsValidators,
    hasDoingBusinessAs: doingBusinessAsAbsentFieldMetadata.validators,
    doingBusinessAs: doingBusinessAsFieldMetadata.validators,
    taxInformation: resolveFieldMetadata(
      taxInformationDefaultFieldConfig[country],
      {
        taxIdNumberType: taxInformation?.find((taxId) => taxId.country === country)?.type,
        companyType: LegalEntityTypes.TRUST
      },
      taxInformationDefaultFieldMetadata
    )?.validators,
    exemptedFromTax: resolveFieldMetadata(
      exemptedFromTaxDefaultFieldConfig[country],
      {},
      exemptedFromTaxDefaultFieldMetadata
    )?.validators,
    registrationNumber: resolveFieldMetadata(
      registrationNumberDefaultFieldConfig[country],
      {
        companyType: LegalEntityTypes.TRUST,
        registrationNumberType,
        isExperimentEnabled
      },
      registrationNumberDefaultFieldMetadata
    )?.validators,
    exemptedFromRegistrationNumber: resolveFieldMetadata(
      exemptFromRegistrationNumberDefaultFieldConfig[country],
      {},
      exemptFromRegistrationNumberDefaultFieldMetadata
    )?.validators,
    vatNumber: resolveFieldMetadata(
      defaultFieldConfig[country],
      { vatNumberType },
      defaultFieldMetadata
    )?.validators
  };
}
const parseTrustScenarios = (scenarios, country) => augmentWithCountryConfigs(
  trustCountryConfig[country],
  composePerScenarioFormConfigurations(scenarios, trustFieldsPerScenario)
);
const parseConfiguration = ({ scenarios, country }) => parseTrustScenarios(scenarios, country);
function TrustMultiformDropin({
  parentLegalEntity,
  country: countryProp,
  existingTrust,
  taskType,
  problems: problemsProp,
  onSubmit: externalOnSubmit,
  onChange,
  handleHomeClick
}) {
  const {
    state: { currentState }
  } = useStateContext();
  useEffect(() => {
    onChange?.(currentState);
  }, [currentState, onChange]);
  const { baseUrl, rootLegalEntityId } = useApiContext();
  const { t, i18n } = useTranslation(["common", "trust"]);
  const userEvents = useAnalyticsContext();
  const [validationErrors, setValidationErrors] = useState();
  const datasetUtils = datasetUtilities(i18n.language);
  const { isExperimentEnabled } = useExperimentsContext();
  const { showToast } = useToastContext();
  const [loadingStatus, setLoadingStatus] = useState("success");
  const [country, setCountry] = useState(countryProp);
  useRef(null);
  const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
  const problems = useMemo(
    () => ({
      ...problemsProp,
      validationErrors
    }),
    [problemsProp, validationErrors]
  );
  const trustData = useMemo(() => {
    if (!existingTrust) return {};
    return isUnincorporatedPartnership ? mapLegalEntityToUnincorporatedPartnership(existingTrust, isExperimentEnabled) : mapLegalEntityToTrust(existingTrust, isExperimentEnabled);
  }, [isExperimentEnabled, existingTrust, isUnincorporatedPartnership]);
  const currentCountry = useMemo(
    () => currentState.data.trustRegistrationDetails?.country ?? countryProp,
    [countryProp, currentState.data.trustRegistrationDetails?.country]
  );
  const [initialData, setInitialData] = useState(trustData);
  const documentUtils = documentApiUtils({
    baseUrl: baseUrl.value,
    rootLegalEntityId: rootLegalEntityId.value
  });
  useEffect(() => {
    userEvents.updateBaseTrackingPayload({ task: taskType });
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
    if (!existingTrust?.documentDetails?.length) return;
    documentUtils.fetchDocuments(existingTrust.documentDetails, existingTrust.id).then(() => {
      const mappedDocuments = mapApiDocumentToTrustDocument(existingTrust.id);
      setInitialData({
        ...initialData,
        ...mappedDocuments
      });
    }).catch(() => {
      showToast({ label: t(($) => $["failedToFetchRelevantDocuments"]), variant: "error" });
    });
  }, [documentUtils, existingTrust, initialData, showToast, t, taskType, userEvents]);
  const { fieldConfigurations, requiredFields } = useScenarioConfiguration({
    parseConfiguration,
    legalEntityType: LegalEntityTypes.TRUST,
    setLoadingStatus,
    country: currentCountry
  });
  const fieldsFromCustomRules = useMemo(
    () => rules({
      data: currentState.data,
      country: currentCountry,
      taskType,
      isExperimentEnabled
    }),
    [currentCountry, currentState.data, taskType, requiredFields, isExperimentEnabled]
  );
  const derivedProps = useMemo(
    () => getPropsFromConfigurations({
      scenarioConfiguration: fieldConfigurations,
      forms: trustForms$1,
      remediationActions: problems?.remediationActions ? Object.values(problems?.remediationActions) : [],
      dataMissingErrors: problems?.missingData ?? [],
      fieldsWithExistingData: existingTrust ? getFieldsWithExistingData(existingTrust, trustApiKeyMapping, trustDocumentMapping) : [],
      customRules: fieldsFromCustomRules,
      legalEntityType: existingTrust?.type
    }),
    [
      fieldConfigurations,
      problems?.remediationActions,
      problems?.missingData,
      existingTrust,
      fieldsFromCustomRules
    ]
  );
  const buildTrustValidations = useCallback(
    (data) => {
      return {
        trustRegistrationDetails: trustRegistrationDetailsValidators(
          country,
          data?.trustRegistrationDetails,
          isExperimentEnabled
        )
      };
    },
    [country, isExperimentEnabled]
  );
  const multiForm = useMultiForm({
    defaultData: initialData,
    allFields: derivedProps?.allFields,
    requiredFields: derivedProps?.requiredFields,
    optionalFields: derivedProps?.optionalFields,
    obscuredFields: derivedProps?.obscuredFields,
    trustedFields: derivedProps?.trustedFields,
    rules: buildTrustValidations
  });
  const [prevCountry, setPrevCountry] = useState(multiForm.data.trustRegistrationDetails?.country);
  if (multiForm.data.trustRegistrationDetails?.country && prevCountry !== multiForm.data.trustRegistrationDetails?.country) {
    setCountry(multiForm.data?.trustRegistrationDetails?.country);
    setPrevCountry(multiForm.data.trustRegistrationDetails?.country);
  }
  const forms = useMemo(() => {
    const requiredForms = getRequiredForms(
      trustForms$1,
      derivedProps?.requiredFields,
      derivedProps?.optionalFields
    );
    return addValidityToForms(requiredForms, multiForm.isValid, problems);
  }, [derivedProps, multiForm.isValid, problems]);
  const onSubmitTrust = async () => {
    setLoadingStatus("loading");
    const trustDetails = mapTrustToLegalEntity(currentState.data, isExperimentEnabled);
    try {
      const updatedTrust = await submitTrustDetails(trustDetails);
      await submitDocuments({ forms, legalEntity: updatedTrust, dataSubmitted: currentState.data });
      await attachTrustToParentLegalEntity(updatedTrust);
      setLoadingStatus("success");
      showToast({ label: t(($) => $["successfullyUpdatedDetails"]), variant: "success" });
      externalOnSubmit?.(currentState.data);
    } catch (e) {
      showToast({ label: t(($) => $["failedToUpdateDetails"]), variant: "error" });
      if (isValidationError(e)) {
        setValidationErrors(processValidationErrors(e, taskType));
      } else if (isMaintenanceModeError(e)) {
        showToast({
          label: t(($) => $["maintenanceModeMessage"]),
          variant: "error",
          duration: "indefinite"
        });
      }
      setLoadingStatus("success");
    }
  };
  const onSubmitUnincorporatedPartnership = async () => {
    setLoadingStatus("loading");
    const unincorporatedPartnershipDetails = mapUnincorporatedPartnershipToLegalEntity(
      currentState.data,
      isExperimentEnabled
    );
    try {
      const updatedUnincorporatedPartnershipDetails = await submitTrustDetails(
        unincorporatedPartnershipDetails
      );
      await submitDocuments({
        forms,
        legalEntity: updatedUnincorporatedPartnershipDetails,
        dataSubmitted: currentState.data
      });
      await attachTrustToParentLegalEntity(updatedUnincorporatedPartnershipDetails);
      setLoadingStatus("success");
      showToast({ label: t(($) => $["successfullyUpdatedDetails"]), variant: "success" });
      externalOnSubmit?.(currentState.data);
    } catch (e) {
      showToast({ label: t(($) => $["failedToUpdateDetails"]), variant: "error" });
      if (isValidationError(e)) {
        setValidationErrors(processValidationErrors(e, taskType));
      } else if (isMaintenanceModeError(e)) {
        showToast({
          label: t(($) => $["maintenanceModeMessage"]),
          variant: "error",
          duration: "indefinite"
        });
      }
      setLoadingStatus("success");
    }
  };
  const { mutateAsync: createLegalEntity } = useCreateLegalEntity();
  const { mutateAsync: updateLegalEntity } = useUpdateLegalEntity();
  const submitTrustDetails = async (legalEntity) => {
    if (!existingTrust) {
      return await createLegalEntity(legalEntity);
    } else {
      return await updateLegalEntity({
        ...drop("type").from(legalEntity),
        id: existingTrust.id
      });
    }
  };
  const submitDocuments = async ({
    forms: forms2,
    legalEntity,
    dataSubmitted
  }) => {
    if (isDocumentsRequired(forms2)) {
      const formattedDocument = await mapTrustDocumentToApiDocument(dataSubmitted, legalEntity.id);
      if (formattedDocument) {
        await documentUtils.uploadDocuments([formattedDocument], legalEntity.id);
      }
    }
  };
  const isDocumentsRequired = (forms2) => forms2.some((form) => form.formId === trustForms$1.trustConstitutionalDocument.formId);
  const attachTrustToParentLegalEntity = async (trust) => {
    if (existingTrust?.id) {
      return;
    }
    const existingEntityAssociations = getOwnEntityAssociations(parentLegalEntity);
    const updatedParentLegalEntity = {
      entityAssociations: [
        {
          type: trust.type,
          legalEntityId: trust.id
        },
        ...existingEntityAssociations
      ]
    };
    await updateLegalEntity({ ...updatedParentLegalEntity, id: parentLegalEntity.id });
  };
  const formatDataForSummary = useCallback(
    (formData, forms2) => {
      let summaryData2 = cloneObject(formData) || {};
      const country2 = formData.trustRegistrationDetails?.country ?? (existingTrust ? getLegalEntityCountry(existingTrust) : getLegalEntityCountry(parentLegalEntity));
      if (formData.trustRegistrationDetails) {
        const trustCountry = formData.trustRegistrationDetails.country && datasetUtils.getCountryName(formData.trustRegistrationDetails.country);
        const trustType = formData.trustRegistrationDetails.trustType && t(($) => $[formData.trustRegistrationDetails.trustType], { ns: "trust" });
        const registrationNumberLabel = resolveFieldMetadata(
          registrationNumberDefaultFieldConfig[country2],
          {
            companyType: LegalEntityTypes.TRUST,
            registrationNumberType: formData.trustRegistrationDetails.registrationNumber ? inferCompanyRegistrationNumberType(
              formData.trustRegistrationDetails.registrationNumber,
              country2,
              LegalEntityTypes.TRUST
            ) : getCompanyRegistrationNumberOptions(country2, LegalEntityTypes.TRUST)?.[0]?.id
          },
          registrationNumberDefaultFieldMetadata
        ).label;
        const taxIdLabel = resolveFieldMetadata(
          taxInformationDefaultFieldConfig[country2],
          {
            companyType: LegalEntityTypes.TRUST,
            taxIdNumberType: countryToTaxInfoTypeMap[country2]
          },
          taxInformationDefaultFieldMetadata
        ).label;
        summaryData2.trustRegistrationDetails = {
          [isUnincorporatedPartnership ? "legalName" : "nameOfTrustAgreement"]: formData.trustRegistrationDetails?.legalName,
          doingBusinessAs: formData.trustRegistrationDetails?.doingBusinessAs,
          countryRegionOfEstablishment: trustCountry,
          typeOfTrustAgreement: isUnincorporatedPartnership ? void 0 : trustType,
          objectOfTrust: formData.trustRegistrationDetails?.objectOfTrust,
          [taxIdLabel]: formData.trustRegistrationDetails?.taxInformation?.find(
            (taxId) => country2 === taxId.country
          )?.number,
          [registrationNumberLabel]: formData.trustRegistrationDetails.registrationNumber
        };
      }
      if (formData.trustRegistrationAddress?.registrationAddress) {
        summaryData2.trustRegistrationAddress.hasInnerForms = true;
        summaryData2.trustRegistrationAddress.registrationAddress = mapAddressLabels(
          formData.trustRegistrationAddress.registrationAddress,
          datasetUtils
        );
      }
      if (formData.trustRegistrationAddress?.operationalAddress) {
        summaryData2.trustRegistrationAddress.operationalAddress = mapAddressLabels(
          formData.trustRegistrationAddress.operationalAddress,
          datasetUtils
        );
      }
      if (isDocumentsRequired(forms2)) {
        summaryData2 = {
          ...summaryData2,
          ...formatFileSummaryData(formData.trustConstitutionalDocument)
        };
      } else {
        delete summaryData2[trustConstitutionalDocumentFormId$1];
      }
      return summaryData2;
    },
    [datasetUtils, existingTrust, isUnincorporatedPartnership, parentLegalEntity, t]
  );
  const formatFileSummaryData = (trustConstitutionalDocument) => {
    const constitutionalDocument = trustConstitutionalDocument?.constitutionalDocument?.[0];
    return {
      ...constitutionalDocument && {
        trustConstitutionalDocument: {
          fileName: constitutionalDocument.name
        }
      }
    };
  };
  const {
    handleNextClick,
    handleBackClick,
    activeForm,
    shouldValidate,
    gotoFormByFormIndex,
    steps
  } = useFormComposer({
    problems,
    forms,
    onSubmit: isUnincorporatedPartnership ? onSubmitUnincorporatedPartnership : onSubmitTrust,
    triggerValidation: multiForm.triggerValidation
  });
  const summaryData = useMemo(
    () => formatDataForSummary(multiForm.data, forms),
    [formatDataForSummary, multiForm.data, forms]
  );
  return /* @__PURE__ */ jsx(FormContextProvider, { form: multiForm, children: /* @__PURE__ */ jsx(
    FormFlow,
    {
      summary: {
        data: summaryData,
        omitted: {
          keys: ["operationalAddressIsSame"]
        }
      },
      currentStep: steps.current,
      totalSteps: steps.total,
      forms,
      activeForm,
      gotoFormByFormIndex,
      handleNextClick,
      handleBackClick,
      handleCancelClick: handleHomeClick,
      loadingStatus,
      children: /* @__PURE__ */ jsx(
        TrustMultiform,
        {
          country,
          activeForm,
          taskType,
          shouldValidate,
          problems
        }
      )
    }
  ) });
}
const TrustDetailsPage = ({
  taskType,
  trustId,
  handleHomeClick,
  onSubmit
}) => {
  const { i18n } = useTranslation();
  const { data: trustLe } = useLegalEntity(trustId ?? skipToken);
  const { data: rootLe } = useLegalEntity(ROOT_LE);
  const { isExperimentEnabled } = useExperimentsContext();
  addResourceBundles(i18n, [
    { ns: "trust", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../language/bg-BG.json": () => import("./bg-BG-DMNRRZZE.js"), "../language/cs-CZ.json": () => import("./cs-CZ-DXSMRqPu.js"), "../language/da-DK.json": () => import("./da-DK-Cd5IQPv3.js"), "../language/de-DE.json": () => import("./de-DE-C9NH2zMh.js"), "../language/el-GR.json": () => import("./el-GR-DTHQslLc.js"), "../language/en-US.json": () => import("./en-US-DYP6rAvA.js"), "../language/es-ES.json": () => import("./es-ES-DK-7qtDf.js"), "../language/et-EE.json": () => import("./et-EE-DNC4hcxm.js"), "../language/fi-FI.json": () => import("./fi-FI-BJLU1JHw.js"), "../language/fr-FR.json": () => import("./fr-FR-B2je0smB.js"), "../language/hr-HR.json": () => import("./hr-HR-C0NLgF1r.js"), "../language/hu-HU.json": () => import("./hu-HU-DU-5ujQK.js"), "../language/it-IT.json": () => import("./it-IT-Dhwa9Ecj.js"), "../language/ja-JP.json": () => import("./ja-JP-Bc4U0S8-.js"), "../language/lt-LT.json": () => import("./lt-LT-C8n1GZoU.js"), "../language/lv-LV.json": () => import("./lv-LV-BZN4-Xat.js"), "../language/nl-NL.json": () => import("./nl-NL-B0fvINJj.js"), "../language/no-NO.json": () => import("./no-NO-Jw7Gae-a.js"), "../language/pl-PL.json": () => import("./pl-PL-Bmaq3IC3.js"), "../language/pt-BR.json": () => import("./pt-BR-BaTE6BB_.js"), "../language/pt-PT.json": () => import("./pt-PT-c0ap84_F.js"), "../language/ro-RO.json": () => import("./ro-RO-BPOHV6Wp.js"), "../language/sk-SK.json": () => import("./sk-SK-3_SoEn6P.js"), "../language/sl-SI.json": () => import("./sl-SI-DbfswGh0.js"), "../language/sv-SE.json": () => import("./sv-SE-D_Efxy3s.js") }), `../language/${lang}.json`, 3) }
  ]);
  const capabilities = useCapabilities();
  const capabilityNames = capabilities ? keysOf(capabilities) : [];
  const capabilityProblems = useCapabilityProblems();
  const problems = capabilityProblems && trustId ? getProblemsForEntity(capabilityProblems, EntityTypes.LEGAL_ENTITY, trustId) : void 0;
  if (trustId && !trustLe || !rootLe) {
    return /* @__PURE__ */ jsx(Loader, {});
  }
  const country = getLegalEntityCountry(trustLe ?? rootLe);
  const TrustPageDropin = isExperimentEnabled("EnableTrustDetailsMultiform") ? TrustMultiformDropin : TrustDropin;
  return /* @__PURE__ */ jsx(
    TrustPageDropin,
    {
      taskType,
      problems,
      existingTrust: trustLe,
      parentLegalEntity: rootLe,
      capabilities: capabilityNames,
      country,
      handleHomeClick,
      onSubmit
    }
  );
};
export {
  TrustDetailsPage
};
