;
{
  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] = "62978fc5-d373-4864-87d6-811d42de61ce", e._sentryDebugIdIdentifier = "sentry-dbid-62978fc5-d373-4864-87d6-811d42de61ce");
  } catch (e) {
  }
}
;
import { o as LegalEntityTypes, bn as TrustMemberTypes, ai as isEmpty, u as useTranslation, v as useExperimentsContext, c as useLegalEntity, ae as getOwnEntityAssociations, a0 as CountryCodes, a3 as createLogger, a as addResourceBundles, L as Loader, g as getLegalEntityCountry, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsx, jsxs, Fragment } from "preact/jsx-runtime";
import { skipToken } from "@tanstack/preact-query";
import { useParams } from "wouter-preact";
import { u as useTrustMembers } from "./useTrustMembers-Bu1X3sQq.js";
import { useEffect, useState } from "preact/hooks";
import { u as useCreateLegalEntity } from "./useCreateLegalEntity-swV6s65R.js";
import { u as useUpdateLegalEntity } from "./useUpdateLegalEntity-CcNBhTXa.js";
import { u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { A as ActionBar } from "./ActionBar-DPfNdSxA.js";
import { D as DropinLayout } from "./DropinLayout-CBP_cHLC.js";
import { F as FormNavigation } from "./FormNavigation-BJzGPCsX.js";
import { s as summaryStep, S as Summary } from "./Summary-6z7-keBb.js";
import { i as isNewEntity } from "./isNewEntity-7Vw_eQBr.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import cx from "classnames";
import { a as SelectListItem } from "./Select-DbIpx8xz.js";
import { T as TextArea } from "./TextArea-DR0WD0kF.js";
import { T as TileGroup } from "./TileGroup-CFNn8NKj.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { E as ErrorPanel } from "./ErrorPanel-D-VMcBB9.js";
import { C as CountryField, a as COUNTRY_FIELD } from "./CountryField-DDFphSWX.js";
import { a as defaultFieldMetadata, c as defaultFieldConfig, e as LegalCompanyNameField, g as getLegalCompanyNameHelperText, L as LEGAL_COMPANY_NAME_FIELD } from "./LegalCompanyNameField-DFL8yszv.js";
import { N as Name, n as nameFields } from "./Name-DmrPljpe.js";
import { r as resolveFieldMetadata } from "./fieldConfigurations-BUT9DTUH.js";
import { m as mergeFieldMetadataIntoProps, c as createFormUtils } from "./formUtils-CwOJPw6N.js";
import { g as getFieldProps } from "./getProps-Cc3J2-z9.js";
import { r as roleMetadata, g as getRoleName } from "./roleMetadata-BhGtDULY.js";
import { t as trustMemberLegalEntityTypes, i as isOrganizationAndSettlor, s as settlorExemptionReasonWithNoneOfTheAbove, c as couldBeExemptSettlor, a as isExemptSettlor } from "./types-0MYCUtrk.js";
import { s as summaryItem } from "./summaryItem-CAQCQSkt.js";
const handleKeys = (keys, callback, propagationMode = "stopIfMatches") => (event) => {
  if (propagationMode === "stop") event.stopPropagation();
  if (keys.includes(event.key)) {
    if (propagationMode === "stopIfMatches") event.stopPropagation();
    callback();
  }
};
const multiSelectList = "adyen-kyc-multi-select-list";
const multiSelectListItem = "adyen-kyc-multi-select-list-item";
const multiSelectListItemWithDescription = "adyen-kyc-multi-select-list-item-with-description";
const styles$1 = {
  multiSelectList,
  multiSelectListItem,
  multiSelectListItemWithDescription
};
const MultiSelectList = ({
  options,
  selected,
  onSelect,
  mapToSelectItem
}) => /* @__PURE__ */ jsx("ul", { className: styles$1.multiSelectList, children: options.map((option) => {
  const item = mapToSelectItem(option);
  const isSelected = selected.includes(option);
  const handleSelect = () => {
    const newSelection = isSelected ? selected.filter((selectedOption) => selectedOption !== option) : [...selected, option];
    onSelect(newSelection);
  };
  return /* @__PURE__ */ jsx(
    SelectListItem,
    {
      id: item.id,
      item,
      selected: isSelected,
      onKeyDown: handleKeys(["Enter", " "], handleSelect),
      onSelect: handleSelect,
      isMulti: true,
      className: cx([
        styles$1.multiSelectListItem,
        {
          [styles$1.multiSelectListItemWithDescription]: !!item.description
        }
      ])
    },
    item.id
  );
}) });
const makeSelectItemForRole = (role, t) => {
  const metadata = roleMetadata[role];
  if (!metadata)
    throw Error(
      `Cannot make select item for role "${role}"; no metadata found. Valid roles include: ${Object.keys(
        roleMetadata
      ).join("\n")}`
    );
  const { name, description } = metadata;
  return {
    id: role,
    name: t(($) => $[name]),
    description: description ? t(($) => $[description]) : void 0
  };
};
const convertExistingSettlorExemptionReasons = (existingReasons) => {
  if (!existingReasons || !existingReasons.length) return ["noneOfTheAbove"];
  return existingReasons;
};
const convertExistingTrustMember = (trustMember) => {
  switch (trustMember.trustMemberType) {
    case "undefinedBeneficiary":
      return {
        entityType: LegalEntityTypes.INDIVIDUAL,
        role: ["undefinedBeneficiary"],
        descriptionUndefinedBeneficiary: trustMember.description
      };
    case "regular":
    case "company":
      return {
        entityType: trustMember.legalEntityType,
        role: trustMember.roles,
        settlorExemptionReason: ["noneOfTheAbove"],
        country: trustMember.trustMemberType === "company" ? trustMember.country : void 0,
        legalCompanyName: trustMember.trustMemberType === "company" ? trustMember.name : void 0
      };
    case "rootTrustee":
      return {
        trustMemberType: trustMember.trustMemberType,
        entityType: trustMember.legalEntityType,
        role: trustMember.roles,
        settlorExemptionReason: ["noneOfTheAbove"]
      };
    case "exemptSettlor":
      return {
        entityType: trustMember.legalEntityType,
        role: ["settlor"],
        settlorExemptionReason: convertExistingSettlorExemptionReasons(
          trustMember.settlorExemptionReason
        ),
        firstName: trustMember.exemptSettlorName?.firstName,
        lastName: trustMember.exemptSettlorName?.lastName,
        legalCompanyName: trustMember.name,
        country: trustMember.country
      };
  }
};
const convertRootTrusteeTrustMember = (trustMember) => ({
  trustMemberType: trustMember.trustMemberType,
  entityType: trustMember.legalEntityType,
  role: trustMember.roles,
  settlorExemptionReason: ["noneOfTheAbove"]
});
const allowedCrossoverRolesMatrix = {
  settlor: ["secondaryTrustee", "protector"],
  secondaryTrustee: ["settlor", "protector", "definedBeneficiary"],
  protector: ["settlor", "secondaryTrustee", "definedBeneficiary"],
  definedBeneficiary: ["secondaryTrustee", "protector"],
  undefinedBeneficiary: []
};
const allowedCrossoverRolesMatrixByTrustMemberAndLegalEntityType = {
  rootTrustee: {
    [LegalEntityTypes.INDIVIDUAL]: {
      settlor: ["secondaryTrustee", "protector"],
      secondaryTrustee: ["settlor", "protector", "definedBeneficiary"],
      protector: ["settlor", "secondaryTrustee", "definedBeneficiary"],
      definedBeneficiary: ["secondaryTrustee", "protector"],
      undefinedBeneficiary: []
    },
    [LegalEntityTypes.ORGANIZATION]: {
      settlor: ["secondaryTrustee", "protector"],
      secondaryTrustee: ["settlor", "protector"],
      protector: ["settlor", "secondaryTrustee"],
      definedBeneficiary: [],
      undefinedBeneficiary: []
    }
  }
};
const getAllowedCrossoverRolesMatrixByTrustMemberAndLegalEntityType = (trustMember) => {
  const { trustMemberType } = trustMember;
  if (trustMemberType === "undefinedBeneficiary") {
    return allowedCrossoverRolesMatrix;
  }
  const crossoverRolesByTrustMember = allowedCrossoverRolesMatrixByTrustMemberAndLegalEntityType[trustMemberType];
  if (!crossoverRolesByTrustMember) {
    return allowedCrossoverRolesMatrix;
  }
  const crossoverRoles = crossoverRolesByTrustMember[trustMember.legalEntityType];
  if (!crossoverRoles) {
    return allowedCrossoverRolesMatrix;
  }
  return crossoverRoles;
};
const availablesRolesByTrustMemberTypeAndLegalEntityType = {
  rootTrustee: {
    [LegalEntityTypes.INDIVIDUAL]: ["settlor", "protector", "definedBeneficiary"],
    [LegalEntityTypes.ORGANIZATION]: ["settlor", "protector"]
  }
};
const getAvailableRolesByTrustMemberTypeAndLegalEntityType = (currentRoles, trustMember) => {
  if (!currentRoles?.length) {
    const { trustMemberType, legalEntityType } = trustMember;
    const availableRolesByTrustMemberType = availablesRolesByTrustMemberTypeAndLegalEntityType[trustMemberType];
    if (!availableRolesByTrustMemberType) {
      return Object.values(TrustMemberTypes);
    }
    const availableRoles = availableRolesByTrustMemberType[legalEntityType];
    if (!availableRoles) {
      return Object.values(TrustMemberTypes);
    }
    return availableRoles;
  }
  const crossoverRolesMatrix = trustMember ? getAllowedCrossoverRolesMatrixByTrustMemberAndLegalEntityType(trustMember) : allowedCrossoverRolesMatrix;
  const roles = currentRoles.map((role) => [role, ...crossoverRolesMatrix[role]]).reduce(
    (existingAllowed, allowedForRole) => existingAllowed.filter((role) => allowedForRole.includes(role))
  );
  return roles.filter((r) => r !== "secondaryTrustee");
};
const getAvailableRoles = (currentRoles) => {
  if (!currentRoles?.length) return Object.values(TrustMemberTypes);
  return currentRoles.map((role) => [role, ...allowedCrossoverRolesMatrix[role]]).reduce(
    (existingAllowed, allowedForRole) => existingAllowed.filter((role) => allowedForRole.includes(role))
  );
};
const roleAndTypeValidationRules = {
  entityType: {
    modes: ["blur"],
    validate: (entityType) => !isEmpty(entityType),
    errorMessage: "fieldIsRequired"
  },
  role: {
    modes: ["blur"],
    validate: (role) => !!role?.length,
    errorMessage: "fieldIsRequired"
  },
  descriptionUndefinedBeneficiary: {
    modes: ["blur"],
    validate: (description) => !isEmpty(description),
    errorMessage: "fieldIsRequired"
  },
  settlorExemptionReason: {
    modes: ["blur"],
    validate: (reasons) => Boolean(reasons?.length),
    errorMessage: "fieldIsRequired"
  },
  country: {
    modes: ["blur"],
    validate: (country) => !!country,
    errorMessage: "fieldIsRequired"
  },
  legalCompanyName: {
    modes: ["blur"],
    validate: (name) => !!name,
    errorMessage: "fieldIsRequired"
  }
};
const CHARACTERS_LIMIT = 256;
const leTypeCardDetails = {
  [LegalEntityTypes.INDIVIDUAL]: {
    id: "individual",
    name: "naturalPersonTitle",
    description: "naturalPersonDescription"
  },
  [LegalEntityTypes.ORGANIZATION]: {
    id: "organization",
    name: "businessEntityTitle",
    description: "businessEntityDescription"
  }
};
const convertExistingTrustMemberToDefaultData = (trustMember, allowMoreRolesForMainRootTrusteeEnabled) => {
  if (!trustMember) {
    return {};
  }
  if (allowMoreRolesForMainRootTrusteeEnabled && trustMember.trustMemberType === "rootTrustee") {
    return convertRootTrusteeTrustMember(trustMember);
  }
  return convertExistingTrustMember(trustMember);
};
const TrustRoleAndEntityType = (props) => {
  const { t: commonT } = useTranslation("common");
  const { t: trustT } = useTranslation("trust");
  const {
    existingTrustMember,
    isOrganizationSettlorWithExemptionEnabled,
    onChange,
    id,
    country,
    fieldValidationErrors,
    formVerificationErrors
  } = props;
  const trustRoleAndEntityTypeCountry = country;
  let mergedProps = props;
  mergedProps = mergeFieldMetadataIntoProps(
    "legalCompanyName",
    resolveFieldMetadata(
      defaultFieldConfig[trustRoleAndEntityTypeCountry],
      {},
      defaultFieldMetadata
    ),
    mergedProps
  );
  const { isExperimentEnabled } = useExperimentsContext();
  const allowMoreRolesForMainRootTrusteeEnabled = isExperimentEnabled(
    "AllowMoreRolesForMainRootTrustee"
  );
  const defaultData = convertExistingTrustMemberToDefaultData(
    existingTrustMember,
    allowMoreRolesForMainRootTrusteeEnabled
  );
  const formUtils = createFormUtils(mergedProps, commonT);
  const decideFields = (data2) => {
    if (data2.role?.includes("undefinedBeneficiary")) {
      return ["role", "descriptionUndefinedBeneficiary"];
    }
    if (data2.role?.length) {
      if (isOrganizationSettlorWithExemptionEnabled && isOrganizationAndSettlor(data2)) {
        return ["role", "entityType", "settlorExemptionReason", "country", "legalCompanyName"];
      }
      if (couldBeExemptSettlor(data2, country)) {
        return isExemptSettlor(data2) ? ["role", "entityType", "settlorExemptionReason", "firstName", "lastName"] : ["role", "entityType", "settlorExemptionReason"];
      }
      return allowMoreRolesForMainRootTrusteeEnabled ? ["role", "entityType", "trustMemberType"] : ["role", "entityType"];
    }
    return ["role"];
  };
  const { data, valid, schema, errors, fieldProblems, handleChangeFor, isValid } = useForm({
    ...props,
    schema: decideFields,
    rules: roleAndTypeValidationRules,
    defaultData,
    fieldProblems: fieldValidationErrors
  });
  const availableRoles = allowMoreRolesForMainRootTrusteeEnabled && existingTrustMember?.trustMemberType === "rootTrustee" ? getAvailableRolesByTrustMemberTypeAndLegalEntityType(data.role, existingTrustMember) : getAvailableRoles(data.role);
  const { data: exemptSettlorLe } = useLegalEntity(
    isOrganizationSettlorWithExemptionEnabled && existingTrustMember && existingTrustMember.trustMemberType === "exemptSettlor" && existingTrustMember.legalEntityId !== isNewEntity && existingTrustMember.roles !== void 0 && existingTrustMember.roles.length === 1 && existingTrustMember.roles[0] === "settlor" ? existingTrustMember.legalEntityId : skipToken
  );
  useEffect(() => {
    if (exemptSettlorLe && exemptSettlorLe.organization) {
      handleChangeFor("country")(exemptSettlorLe.organization.registeredAddress.country);
    }
  }, [exemptSettlorLe]);
  useEffect(() => {
    onChange?.({
      schema,
      data,
      errors,
      valid,
      isValid,
      dataStoreId: id,
      fieldProblems
    });
  }, [schema, data, isValid, commonT, errors, valid, id, fieldProblems]);
  const onInputDescription = (e) => {
    const { value } = e.currentTarget;
    handleChangeFor("descriptionUndefinedBeneficiary")(value);
  };
  const changeRoles = (roles) => {
    handleChangeFor("role")(roles);
    if (roles.includes("undefinedBeneficiary")) {
      handleChangeFor("entityType")(void 0);
    } else {
      handleChangeFor("descriptionUndefinedBeneficiary")(void 0);
    }
  };
  const changeSettlorExemptionReasons = (exemptionReasons) => {
    if (exemptionReasons.includes("noneOfTheAbove")) {
      handleChangeFor("settlorExemptionReason")(
        data.settlorExemptionReason?.includes("noneOfTheAbove") ? exemptionReasons.filter((reason) => reason !== "noneOfTheAbove") : ["noneOfTheAbove"]
      );
      return;
    }
    handleChangeFor("settlorExemptionReason")(exemptionReasons);
  };
  const nameProps = getFieldProps(props, nameFields);
  const onEntityTypeChange = (value) => {
    if (isOrganizationSettlorWithExemptionEnabled && value === LegalEntityTypes.ORGANIZATION && data.role?.length === 1 && data.role[0] === "settlor") {
      changeSettlorExemptionReasons(["professionalServiceProvider"]);
    }
    handleChangeFor("entityType")(value);
  };
  return /* @__PURE__ */ jsxs("form", { className: "adyen-kyc-trust__role-and-entity-type adyen-kyc-u-width-full", children: [
    /* @__PURE__ */ jsx(Header, { title: commonT(($) => $["roleAndEntityType"]) }),
    /* @__PURE__ */ jsx(
      ErrorPanel,
      {
        verificationErrors: formVerificationErrors,
        validationErrors: fieldValidationErrors,
        formUtils,
        id: "ariaErrorField"
      }
    ),
    /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "role",
        label: formUtils.getLabel("role", "selectTheApplicableRoles"),
        errorMessage: formUtils.getErrorMessage("role", errors, fieldProblems),
        isValid: valid.role,
        disabled: availableRoles.length === 0,
        showErrorIconBottom: true,
        children: (childProps) => /* @__PURE__ */ jsx(
          MultiSelectList,
          {
            ...childProps,
            options: Object.values(TrustMemberTypes),
            selected: data.role ?? [],
            onSelect: changeRoles,
            mapToSelectItem: (role) => ({
              ...makeSelectItemForRole(role, commonT),
              disabled: !availableRoles.includes(role)
            })
          }
        )
      }
    ),
    schema?.includes("entityType") && /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "entityType",
        errorMessage: formUtils.getErrorMessage("entityType", errors, fieldProblems),
        label: formUtils.getLabel("entityType", "whatTypeOfYourMembersEntity"),
        classNameModifiers: ["entityType"],
        disabled: Boolean(existingTrustMember),
        children: (childProps) => /* @__PURE__ */ jsx(
          TileGroup,
          {
            ...childProps,
            name: "entityType",
            tiles: trustMemberLegalEntityTypes.map((option) => ({
              value: option,
              label: trustT(($) => $[leTypeCardDetails[option].name]),
              subTitle: trustT(($) => $[leTypeCardDetails[option].description])
            })),
            selected: data.entityType ?? "",
            onChange: (value) => onEntityTypeChange(value),
            isHorizontal: true,
            "aria-required": true,
            "aria-invalid": !valid.entityType
          }
        )
      }
    ),
    schema?.includes("descriptionUndefinedBeneficiary") && /* @__PURE__ */ jsx(
      Field,
      {
        name: "descriptionUndefinedBeneficiary",
        label: formUtils.getLabel("description"),
        isValid: valid.descriptionUndefinedBeneficiary,
        errorMessage: formUtils.getErrorMessage(
          "descriptionUndefinedBeneficiary",
          errors,
          fieldProblems
        ),
        children: (childProps) => /* @__PURE__ */ jsx(
          TextArea,
          {
            ...childProps,
            name: "descriptionUndefinedBeneficiary",
            value: data.descriptionUndefinedBeneficiary,
            maxLength: CHARACTERS_LIMIT,
            onInput: onInputDescription,
            helper: trustT(($) => $["describeWhoIsABeneficiaryInYourTrust"]),
            "aria-required": true,
            "aria-invalid": !valid.descriptionUndefinedBeneficiary
          }
        )
      }
    ),
    schema?.includes("settlorExemptionReason") && !isOrganizationAndSettlor(data) && /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "settlorExemptionReason",
        label: formUtils.getLabel("settlorExemptionReason", "whichOfTheseApplyToTheSettlor"),
        isValid: valid.settlorExemptionReason,
        errorMessage: formUtils.getErrorMessage("settlorExemptionReason", errors, fieldProblems),
        showErrorIconBottom: true,
        children: (childProps) => /* @__PURE__ */ jsx(
          MultiSelectList,
          {
            ...childProps,
            options: settlorExemptionReasonWithNoneOfTheAbove,
            selected: data.settlorExemptionReason ?? [],
            onSelect: changeSettlorExemptionReasons,
            mapToSelectItem: (reason) => ({
              id: reason,
              name: trustT(($) => $[reason])
            })
          }
        )
      }
    ),
    data.trustMemberType !== "rootTrustee" && (schema.includes("firstName") || schema.includes("lastName")) ? /* @__PURE__ */ jsx(
      Name,
      {
        ...nameProps,
        data: {
          firstName: defaultData.firstName,
          lastName: defaultData.lastName
        },
        requiredFields: schema.filter(
          (field) => nameFields.includes(field)
        ),
        labels: {
          firstName: "firstNameOfSettlor",
          lastName: "lastNameOfSettlor",
          enterNameExactlyAsAppearInID: "enterSettlorsFirstNameExactlyAsItAppearsInID",
          enterLastNameExactlyAsAppearInID: "enterSettlorsLastNameExactlyAsItAppearsInID"
        },
        errors,
        fieldValidationErrors: fieldProblems,
        handleFieldChange: handleChangeFor,
        valid,
        dataStoreId: id
      }
    ) : void 0,
    isOrganizationSettlorWithExemptionEnabled && schema?.includes("country") && schema?.includes("legalCompanyName") ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__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),
          readonly: false,
          allowedCountries: void 0,
          handleChangeFor
        }
      ),
      /* @__PURE__ */ jsx(
        LegalCompanyNameField,
        {
          data: formUtils.getFieldData(data, LEGAL_COMPANY_NAME_FIELD),
          valid: formUtils.getFieldValid(valid, LEGAL_COMPANY_NAME_FIELD),
          errors: formUtils.getFieldErrors(errors, fieldProblems, LEGAL_COMPANY_NAME_FIELD),
          labels: formUtils.getFieldLabels(LEGAL_COMPANY_NAME_FIELD),
          helperText: getLegalCompanyNameHelperText(trustT, {
            country: trustRoleAndEntityTypeCountry
          }),
          readonly: false,
          handleChangeFor
        }
      )
    ] }) : void 0
  ] });
};
const mapTrustMemberToEntityAssociations = (trustMember) => {
  if (trustMember.legalEntityId === isNewEntity) {
    throw Error("Cannot map a new trust member, you must create it first");
  }
  if (trustMember.trustMemberType === "exemptSettlor")
    return [
      {
        legalEntityId: trustMember.legalEntityId,
        entityType: trustMember.legalEntityType,
        type: TrustMemberTypes.SETTLOR,
        settlorExemptionReason: trustMember.settlorExemptionReason,
        name: trustMember.legalEntityType === LegalEntityTypes.INDIVIDUAL ? `${trustMember.exemptSettlorName?.firstName} ${trustMember.exemptSettlorName?.lastName}` : trustMember.name ?? ""
      }
    ];
  return trustMember.roles.map((role) => ({
    legalEntityId: trustMember.legalEntityId,
    type: role
  }));
};
const addOrUpdateAssociatedTrustMember = async ({
  newOrUpdated,
  trust,
  updateLegalEntity
}) => {
  const otherAssociations = getOwnEntityAssociations(trust).filter(
    (existingAssociation) => existingAssociation.legalEntityId !== newOrUpdated.legalEntityId
  );
  const updatedAssociations = mapTrustMemberToEntityAssociations(newOrUpdated);
  const patchLE = {
    entityAssociations: [...otherAssociations, ...updatedAssociations]
  };
  await updateLegalEntity({ ...patchLE, id: trust.id });
};
const updateRootTrusteeTrustMember = async ({
  trustMember,
  trust,
  updateLegalEntity
}) => {
  const otherAssociations = getOwnEntityAssociations(trust).filter(
    (existingAssociation) => existingAssociation.legalEntityId !== trustMember.legalEntityId
  );
  const updatedAssociations = mapRootTrustMemberToEntityAssociations(trustMember);
  const patchLE = {
    entityAssociations: [...otherAssociations, ...updatedAssociations]
  };
  await updateLegalEntity({ ...patchLE, id: trust.id });
};
const mapRootTrustMemberToEntityAssociations = (trustMember) => trustMember.roles.filter((r) => r !== "secondaryTrustee").map((role) => ({
  legalEntityId: trustMember.legalEntityId,
  type: role
}));
const addOrUpdateUndefinedBeneficiary = async ({
  newOrUpdated,
  trust,
  updateLegalEntity
}) => {
  const otherUndefinedBeneficiaries = trust.trust?.undefinedBeneficiaryInfo?.filter(
    (ub) => ub.reference !== newOrUpdated.reference
  ) ?? [];
  const patchLE = {
    trust: {
      undefinedBeneficiaryInfo: [
        ...otherUndefinedBeneficiaries,
        newOrUpdated.reference === isNewEntity ? {
          description: newOrUpdated.description
        } : {
          reference: newOrUpdated.reference,
          description: newOrUpdated.description
        }
      ]
    }
  };
  await updateLegalEntity({ ...patchLE, id: trust.id });
};
const createExemptSettlor = async ({
  exemptSettlor,
  trust,
  handleCreateLegalEntity
}) => {
  const exemptSettlorLE = {
    type: LegalEntityTypes.INDIVIDUAL,
    individual: {
      name: {
        firstName: exemptSettlor.exemptSettlorName?.firstName ?? "",
        lastName: exemptSettlor.exemptSettlorName?.lastName ?? ""
      },
      residentialAddress: {
        country: trust.trust.registeredAddress.country
      }
    }
  };
  return handleCreateLegalEntity(exemptSettlorLE);
};
const createOrganizationExemptSettlor = async ({
  exemptSettlor,
  handleCreateLegalEntity
}) => {
  const exemptSettlorLE = {
    type: LegalEntityTypes.ORGANIZATION,
    organization: {
      legalName: exemptSettlor.name ?? "",
      registeredAddress: {
        country: exemptSettlor.country ?? "NL"
      }
    }
  };
  return handleCreateLegalEntity(exemptSettlorLE);
};
const exemptSettlorNamesTheSame = (existingSettlor, newSettlor) => JSON.stringify(existingSettlor.exemptSettlorName) === JSON.stringify(newSettlor.exemptSettlorName);
const updateExemptSettlorName = async ({
  exemptSettlor,
  updateLegalEntity
}) => {
  const exemptSettlorPatch = {
    individual: {
      name: {
        firstName: exemptSettlor.exemptSettlorName?.firstName,
        lastName: exemptSettlor.exemptSettlorName?.lastName
      }
    }
  };
  return updateLegalEntity({
    ...exemptSettlorPatch,
    id: exemptSettlor.legalEntityId
  });
};
const updateOrganizationExemptSettlorName = async ({
  exemptSettlor,
  updateLegalEntity
}) => {
  const exemptSettlorPatch = {
    organization: {
      legalName: exemptSettlor.name,
      registeredAddress: {
        country: exemptSettlor.country
      }
    }
  };
  return updateLegalEntity({
    ...exemptSettlorPatch,
    id: exemptSettlor.legalEntityId
  });
};
const settlorExemptionReasonsList = "adyen-kyc-settlor-exemption-reasons-list";
const styles = {
  settlorExemptionReasonsList
};
const formatRolesForSummary = (roles, commonT) => roles.map((role) => commonT(($) => $[getRoleName(role)])).join(", ");
const formatSettlorExemptionReasonsForSummary = (reasons, trustT) => /* @__PURE__ */ jsx("ul", { className: styles.settlorExemptionReasonsList, children: reasons.map((reason) => /* @__PURE__ */ jsx("li", { children: trustT(($) => $[reason]) }, reason)) });
const formatRoleAndEntityTypeSummary = (data, commonT, trustT, isOrganizationSettlorWithExemptionEnabled) => {
  const { trustMemberType, roles } = data;
  const role = formatRolesForSummary(roles, commonT);
  switch (trustMemberType) {
    case "undefinedBeneficiary":
      return {
        role,
        descriptionUndefinedBeneficiary: data.description
      };
    case "exemptSettlor":
      return {
        role,
        entityType: trustT(($) => $[data.legalEntityType]),
        firstName: data.exemptSettlorName?.firstName,
        lastName: data.exemptSettlorName?.lastName,
        country: isOrganizationSettlorWithExemptionEnabled ? data.country : void 0,
        legalCompanyName: isOrganizationSettlorWithExemptionEnabled ? data.name : void 0,
        settlorExemptionReason: summaryItem(
          "otherInformation",
          formatSettlorExemptionReasonsForSummary(data.settlorExemptionReason ?? [], trustT)
        )
      };
    case "company":
    case "rootTrustee":
    case "regular":
      return {};
  }
};
const summary = {
  formId: "summary",
  formName: "summary"
};
const regularForms = {
  roleAndEntityType: {
    formId: "roleAndEntityType",
    formName: "roleAndEntityType",
    fields: ["role", "entityType"]
  },
  memberDetails: {
    formId: "memberDetails",
    formName: "memberDetails"
  },
  summary
};
const undefinedBeneficiaryForms = {
  roleAndEntityType: {
    formId: "roleAndEntityType",
    formName: "roleAndEntityType",
    fields: ["role", "entityType", "descriptionUndefinedBeneficiary"]
  },
  summary
};
const exemptSettlorForms = {
  roleAndEntityType: {
    formId: "roleAndEntityType",
    formName: "roleAndEntityType",
    fields: ["role", "entityType", "settlorExemptionReason"]
  },
  summary
};
const decideForms = (trustMember) => {
  if (trustMember === "incomplete") return regularForms;
  switch (trustMember.trustMemberType) {
    case "undefinedBeneficiary":
      return undefinedBeneficiaryForms;
    case "exemptSettlor":
      return exemptSettlorForms;
    case "rootTrustee":
      return exemptSettlorForms;
    case "regular":
    case "company":
      return regularForms;
  }
};
const convertDataToTrustMember = (data, existingTrustMember, isOrganizationSettlorWithExemptionReasonEnabled = false) => {
  const existingId = existingTrustMember ? existingTrustMember.trustMemberType === "undefinedBeneficiary" ? existingTrustMember.reference : existingTrustMember.legalEntityId : void 0;
  if (data.trustMemberType === "rootTrustee") {
    return {
      trustMemberType: "rootTrustee",
      roles: data.role ?? [],
      legalEntityType: data.entityType ?? LegalEntityTypes.ORGANIZATION,
      legalEntityId: "",
      name: data.firstName ?? ""
    };
  }
  if (data.role?.length) {
    if (isExemptSettlor(data)) {
      if (isOrganizationSettlorWithExemptionReasonEnabled && data.entityType === LegalEntityTypes.ORGANIZATION) {
        return {
          trustMemberType: "exemptSettlor",
          roles: [TrustMemberTypes.SETTLOR],
          legalEntityType: LegalEntityTypes.ORGANIZATION,
          legalEntityId: existingId ?? isNewEntity,
          name: data.legalCompanyName ?? "",
          settlorExemptionReason: ["professionalServiceProvider"],
          country: data.country
        };
      }
      return {
        trustMemberType: "exemptSettlor",
        roles: [TrustMemberTypes.SETTLOR],
        legalEntityType: LegalEntityTypes.INDIVIDUAL,
        settlorExemptionReason: data.settlorExemptionReason.filter(
          (reason) => reason !== "noneOfTheAbove"
        ),
        exemptSettlorName: {
          firstName: data.firstName ?? "",
          lastName: data.lastName ?? ""
        },
        legalEntityId: existingId ?? isNewEntity
      };
    }
    if (data.role.includes("undefinedBeneficiary"))
      return {
        trustMemberType: "undefinedBeneficiary",
        roles: [TrustMemberTypes.UNDEFINED_BENEFICIARY],
        description: data.descriptionUndefinedBeneficiary ?? "",
        reference: existingId ?? isNewEntity
      };
    if (data.entityType === LegalEntityTypes.ORGANIZATION) {
      return {
        trustMemberType: "company",
        roles: data.role,
        legalEntityType: LegalEntityTypes.ORGANIZATION,
        legalEntityId: existingId ?? isNewEntity,
        name: data.legalCompanyName ?? "",
        country: data.country
      };
    }
    if (data.entityType === LegalEntityTypes.INDIVIDUAL)
      return {
        trustMemberType: "regular",
        roles: data.role,
        legalEntityType: LegalEntityTypes.INDIVIDUAL,
        legalEntityId: existingId ?? isNewEntity,
        name: ""
      };
  }
  return "incomplete";
};
const logger = createLogger();
function RoleAndTypeDropin({
  trust,
  trustMemberLe,
  existingTrustMember,
  navigateToFullDropinFor,
  navigateBack,
  country
}) {
  const { t: commonT } = useTranslation("common");
  const { t: trustT } = useTranslation("trust");
  const { isExperimentEnabled } = useExperimentsContext();
  const allowMoreRolesForMainRootTrustee = isExperimentEnabled("AllowMoreRolesForMainRootTrustee");
  const [trustMember, setTrustMember] = useState(
    existingTrustMember ?? "incomplete"
  );
  const [shouldValidate, setShouldValidate] = useState(false);
  const { showToast } = useToastContext();
  const isOrganizationSettlorWithExemptionReasonEnabled = (country2) => country2 === CountryCodes.Australia;
  const isOrganizationSettlorWithExemptionEnabled = isOrganizationSettlorWithExemptionReasonEnabled(
    trust?.trust?.countryOfGoverningLaw
  );
  const formList = decideForms(trustMember);
  const forms = Object.values(formList);
  const [formValidity, setFormValidity] = useState({
    roleAndEntityType: false
  });
  const [activeForm, setActiveForm] = useState(regularForms.roleAndEntityType);
  const isSummaryStep = activeForm.formId === summaryStep.formId;
  const { mutateAsync: createLegalEntity } = useCreateLegalEntity();
  const { mutateAsync: updateLegalEntity } = useUpdateLegalEntity();
  const addOrUpdateTrustMember = async (updated, existing) => {
    if (existing?.trustMemberType === "undefinedBeneficiary" && updated.trustMemberType === "undefinedBeneficiary" && existing.description === updated.description) {
      await updateLegalEntity(trustMemberLe);
      navigateBack();
      return;
    }
    if (trust === void 0) {
      throw new Error("No associated trust");
    }
    try {
      switch (updated.trustMemberType) {
        case "undefinedBeneficiary":
          await addOrUpdateUndefinedBeneficiary({
            newOrUpdated: updated,
            trust,
            updateLegalEntity
          });
          break;
        case "exemptSettlor":
          if (!existing) {
            const newSettlorLE = isOrganizationSettlorWithExemptionEnabled && updated.legalEntityType === "organization" ? await createOrganizationExemptSettlor({
              exemptSettlor: updated,
              handleCreateLegalEntity: createLegalEntity
            }) : await createExemptSettlor({
              exemptSettlor: updated,
              trust,
              handleCreateLegalEntity: createLegalEntity
            });
            updated.legalEntityId = newSettlorLE.id;
          }
          if (existing && !exemptSettlorNamesTheSame(existing, updated)) {
            await updateExemptSettlorName({
              exemptSettlor: updated,
              updateLegalEntity
            });
          }
          if (existing && isOrganizationSettlorWithExemptionEnabled && updated.legalEntityType === "organization") {
            await updateOrganizationExemptSettlorName({
              exemptSettlor: updated,
              updateLegalEntity
            });
          }
          await addOrUpdateAssociatedTrustMember({
            newOrUpdated: updated,
            trust,
            updateLegalEntity
          });
          break;
        case "regular":
        case "company":
          await addOrUpdateAssociatedTrustMember({
            newOrUpdated: updated,
            trust,
            updateLegalEntity
          });
          break;
        case "rootTrustee":
          if (allowMoreRolesForMainRootTrustee && existing) {
            existing.roles = updated.roles;
            await updateRootTrusteeTrustMember({
              trustMember: existing,
              trust,
              updateLegalEntity
            });
          }
          break;
        default:
          logger.warn(
            `Updating trust member type "${updated.trustMemberType}" is not implemented.`
          );
      }
      showToast({ label: commonT(($) => $["successfullyUpdatedDetails"]), variant: "success" });
      navigateBack();
    } catch (err) {
      logger.error(err);
      showToast({ label: commonT(($) => $["failedToUpdateDetails"]), variant: "error" });
    }
  };
  const summaryData = trustMember === "incomplete" ? {} : {
    roleAndEntityType: formatRoleAndEntityTypeSummary(
      trustMember,
      commonT,
      trustT,
      isOrganizationSettlorWithExemptionEnabled
    )
  };
  const onNavigateToNextStep = () => {
    if (isSummaryStep && trustMember !== "incomplete") {
      addOrUpdateTrustMember(trustMember, existingTrustMember);
      return;
    }
    gotoFormByFormIndex(forms.findIndex((form) => form.formId === activeForm.formId) + 1);
  };
  const onTrustMemberChange = ({
    data,
    isValid = false,
    dataStoreId = void 0
  }) => {
    if (dataStoreId) {
      setFormValidity({ ...formValidity, [dataStoreId]: isValid });
    }
    setTrustMember(
      convertDataToTrustMember(
        data,
        existingTrustMember,
        isOrganizationSettlorWithExemptionEnabled
      )
    );
  };
  const saveRolesAndNavigate = async () => {
    if (trustMember === "incomplete") return;
    if (hasRolesChanged(trustMember.roles, existingTrustMember?.roles)) {
      addOrUpdateTrustMember(trustMember, existingTrustMember);
    }
    navigateBack();
  };
  const hasRolesChanged = (newRoles = [], existingRoles = []) => newRoles.length !== existingRoles.length || !newRoles.every((newRole) => existingRoles.includes(newRole));
  const formsWithValidity = forms.map((form) => ({
    formId: form.formId,
    formName: form.formName,
    isValid: formValidity[form.formId]
  }));
  const gotoFormByFormIndex = (formIndex) => {
    const targetForm = forms[formIndex];
    if (!formValidity.roleAndEntityType || trustMember === "incomplete") {
      setShouldValidate(true);
      return;
    }
    if (trustMember.trustMemberType === "regular" || trustMember.trustMemberType === "company") {
      if (targetForm.formId === regularForms.memberDetails.formId) {
        navigateToFullDropinFor(trustMember);
        return;
      }
      if (targetForm.formId === summaryStep.formId) return;
    }
    setActiveForm(targetForm);
  };
  const content = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx("div", { className: "adyen-kyc-dropin__sidebar-wrapper", children: /* @__PURE__ */ jsx(
      FormNavigation,
      {
        forms: formsWithValidity,
        activeForm: formsWithValidity.find((form) => form.formId === activeForm.formId),
        taskName: "trustMembers",
        gotoForm: gotoFormByFormIndex
      }
    ) }),
    /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-form-container", children: [
      /* @__PURE__ */ jsx(
        "div",
        {
          className: activeForm.formId !== "roleAndEntityType" ? "adyen-kyc-form-wrapper adyen-kyc-form-wrapper--hidden" : "adyen-kyc-form-wrapper",
          children: /* @__PURE__ */ jsx(
            TrustRoleAndEntityType,
            {
              id: "roleAndEntityType",
              existingTrustMember,
              onChange: onTrustMemberChange,
              shouldValidate,
              isOrganizationSettlorWithExemptionEnabled,
              country
            }
          )
        }
      ),
      isSummaryStep && /* @__PURE__ */ jsx("div", { className: "adyen-kyc-form-wrapper", children: /* @__PURE__ */ jsx(
        Summary,
        {
          data: summaryData,
          forms: [undefinedBeneficiaryForms.roleAndEntityType],
          gotoForm: gotoFormByFormIndex
        }
      ) }),
      /* @__PURE__ */ jsx(
        ActionBar,
        {
          onNext: onNavigateToNextStep,
          onHome: saveRolesAndNavigate,
          nextButtonLabel: isSummaryStep ? commonT(($) => $["submit"]) : commonT(($) => $["continue"]),
          homeButtonLabel: commonT(($) => $["saveAndGoToOverview"])
        }
      )
    ] })
  ] });
  return /* @__PURE__ */ jsx(DropinLayout, { content });
}
function TrustMemberRoleAndTypePage({
  trustId,
  memberId: memberIdProp,
  navigateToFullDropinFor,
  navigateBack
}) {
  const routeParams = useParams();
  const memberId = memberIdProp ?? routeParams.memberId;
  const { i18n } = useTranslation();
  const { data: memberLe } = useLegalEntity(memberId ?? skipToken);
  const { data: trustLe } = useLegalEntity(trustId ?? skipToken);
  const trustMembers = useTrustMembers();
  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) }
  ]);
  if (!trustLe || memberId && !memberLe) {
    return /* @__PURE__ */ jsx(Loader, {});
  }
  const country = getLegalEntityCountry(memberLe ?? trustLe);
  const trustMember = memberId ? trustMembers.find(
    (tm) => tm.trustMemberType !== "undefinedBeneficiary" && tm.legalEntityId === memberId
  ) : void 0;
  return /* @__PURE__ */ jsx(
    RoleAndTypeDropin,
    {
      trust: trustLe,
      trustMemberLe: memberLe,
      existingTrustMember: trustMember,
      country,
      navigateToFullDropinFor,
      navigateBack
    }
  );
}
export {
  TrustMemberRoleAndTypePage
};
