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] = "eadb17ff-7cdd-4654-960f-3ef8c44ec7d0", e._sentryDebugIdIdentifier = "sentry-dbid-eadb17ff-7cdd-4654-960f-3ef8c44ec7d0");
} catch (e) {}
import { n as addResourceBundles, o as createLogger, r as useTranslation } from "./translation-Br5wIPO-.js";
import { r as Loader, t as Button } from "./Button-BDEdGXnd.js";
import { r as useLegalEntity } from "./useLegalEntity-Dm6g0wmt.js";
import { t as LegalEntityTypes } from "./legal-entity-type-VIfNYnJP.js";
import { t as getLegalEntityCountry } from "./getLegalEntityCountry-C6bSV6sB.js";
import { y as isEmpty } from "./validatorUtils-Dz6AklT-.js";
import { t as useToggleContext } from "./useToggleContext-CLfowItk.js";
import { t as _rolldown_dynamic_import_helper_default } from "./_rolldown_dynamic_import_helper-CCXvMgfE.js";
import { t as Header } from "./Header-B_MIsVov.js";
import { t as CountryCodes } from "./country-code-D3oCpE4i.js";
import { s as getOwnEntityAssociations } from "./entityAssociationUtil-C0gX4Ewv.js";
import { r as TrustMemberTypes } from "./trustMemberGuidance-paR1FXfI.js";
import { t as useToastContext } from "./useToastContext-CK7UoZ5Z.js";
import { t as isNewEntity } from "./isNewEntity-BCb_oxKh.js";
import { t as useTrustMembers } from "./useTrustMembers-BP6ygpU4.js";
import { t as useCreateLegalEntity } from "./useCreateLegalEntity-C149Z7Xu.js";
import { t as useUpdateLegalEntity } from "./useUpdateLegalEntity-CUs6TYPF.js";
import { t as ErrorPanel } from "./ErrorPanel-5g1eTEVD.js";
import { n as mergeFieldMetadataIntoProps, t as createFormUtils } from "./formUtils-DERTAXyh.js";
import { r as roleMetadata, t as getRoleName } from "./roleMetadata-Dt8-oMGP.js";
import { n as summaryStep, t as Summary } from "./Summary-DZq5UKMv.js";
import { r as summaryItem } from "./summaryItem-Dehjwp8D.js";
import { t as resolveFieldMetadata } from "./fieldConfigurations-B3oqm4GC.js";
import { t as Field } from "./Field-BEqknhTe.js";
import { t as TileGroup } from "./TileGroup-COge4hw4.js";
import { n as SelectListItem } from "./Select-CMFHti4N.js";
import { t as TextArea } from "./TextArea-qzKHJyZG.js";
import { t as useForm } from "./useForm-DzG9tJAE.js";
import { t as getFieldProps } from "./getProps-DQy_qV_x.js";
import { n as CountryField, t as COUNTRY_FIELD } from "./CountryField-B-JxQ6z9.js";
import { n as nameFields, t as Name } from "./Name-VckG8ggI.js";
import { t as Spacer } from "./Spacer-D1yp_1Io.js";
import { t as FormNavigation } from "./FormNavigation-Btkou5O7.js";
import { a as defaultFieldMetadata, n as LegalCompanyNameField, r as defaultFieldConfig, s as getLegalCompanyNameGuidanceText, t as LEGAL_COMPANY_NAME_FIELD } from "./LegalCompanyNameField-Dgn4iOVN.js";
import { a as trustMemberLegalEntityTypes, i as settlorExemptionReasonWithNoneOfTheAbove, n as isExemptSettlor, r as isOrganizationAndSettlor, t as couldBeExemptSettlor } from "./types-BvdB7N_Z.js";
import { useEffect, useState } from "preact/hooks";
import cx from "classnames";
import { Fragment, jsx, jsxs } from "preact/jsx-runtime";
import { skipToken } from "@tanstack/preact-query";
import { useParams } from "wouter-preact";
//#region src/utils/eventHandlers/handleKeys.ts
var handleKeys = (keys, callback, propagationMode = "stopIfMatches") => (event) => {
	if (propagationMode === "stop") event.stopPropagation();
	if (keys.includes(event.key)) {
		if (propagationMode === "stopIfMatches") event.stopPropagation();
		callback();
	}
};
var MultiSelectList_module_default = {
	"multi-select-list": "adyen-kyc-multi-select-list",
	multiSelectList: "adyen-kyc-multi-select-list",
	"multi-select-list-item": "adyen-kyc-multi-select-list-item",
	multiSelectListItem: "adyen-kyc-multi-select-list-item",
	"multi-select-list-item-with-description": "adyen-kyc-multi-select-list-item-with-description",
	multiSelectListItemWithDescription: "adyen-kyc-multi-select-list-item-with-description",
	"adyen-kyc-checkbox__label": "adyen-kyc-adyen-kyc-checkbox__label",
	adyenKycCheckboxLabel: "adyen-kyc-adyen-kyc-checkbox__label"
};
//#endregion
//#region src/components/ui/atoms/MultiSelectList/MultiSelectList.tsx
var MultiSelectList = ({ options, selected, onSelect, mapToSelectItem }) => /* @__PURE__ */ jsx("ul", {
	className: MultiSelectList_module_default.multiSelectList,
	children: options.map((option) => {
		const item = mapToSelectItem(option);
		const isSelected = selected.includes(option);
		const handleSelect = () => {
			onSelect(isSelected ? selected.filter((selectedOption) => selectedOption !== option) : [...selected, option]);
		};
		return /* @__PURE__ */ jsx(SelectListItem, {
			id: item.id,
			item,
			selected: isSelected,
			onKeyDown: handleKeys(["Enter", " "], handleSelect),
			onSelect: handleSelect,
			isMulti: true,
			className: cx([MultiSelectList_module_default.multiSelectListItem, { [MultiSelectList_module_default.multiSelectListItemWithDescription]: !!item.description }])
		}, item.id);
	})
});
//#endregion
//#region src/utils/makeSelectItemForRole.ts
var 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
	};
};
//#endregion
//#region src/components/Trust/forms/TrustRoleAndEntityType/convertExistingTrustMember.ts
var convertExistingSettlorExemptionReasons = (existingReasons) => {
	if (!existingReasons || !existingReasons.length) return ["noneOfTheAbove"];
	return existingReasons;
};
var 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
		};
	}
};
var convertRootTrusteeTrustMember = (trustMember) => ({
	trustMemberType: trustMember.trustMemberType,
	entityType: trustMember.legalEntityType,
	role: trustMember.roles,
	settlorExemptionReason: ["noneOfTheAbove"]
});
//#endregion
//#region src/components/Trust/forms/TrustRoleAndEntityType/getAvailableRoles.ts
/**
* For each role, there is some other roles they may also hold for the trust
*/
var allowedCrossoverRolesMatrix = {
	settlor: ["secondaryTrustee", "protector"],
	secondaryTrustee: [
		"settlor",
		"protector",
		"definedBeneficiary"
	],
	protector: [
		"settlor",
		"secondaryTrustee",
		"definedBeneficiary"
	],
	definedBeneficiary: ["secondaryTrustee", "protector"],
	undefinedBeneficiary: []
};
var 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: []
	}
} };
var 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;
};
var availablesRolesByTrustMemberTypeAndLegalEntityType = { rootTrustee: {
	[LegalEntityTypes.INDIVIDUAL]: [
		"settlor",
		"protector",
		"definedBeneficiary"
	],
	[LegalEntityTypes.ORGANIZATION]: ["settlor", "protector"]
} };
var 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;
	return currentRoles.map((role) => [role, ...crossoverRolesMatrix[role]]).reduce((existingAllowed, allowedForRole) => existingAllowed.filter((role) => allowedForRole.includes(role))).filter((r) => r !== "secondaryTrustee");
};
var 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)));
};
//#endregion
//#region src/components/Trust/forms/TrustRoleAndEntityType/validate.ts
var 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"
	}
};
//#endregion
//#region src/components/Trust/forms/TrustRoleAndEntityType/TrustRoleAndEntityType.tsx
var CHARACTERS_LIMIT = 256;
var leTypeCardDetails = {
	[LegalEntityTypes.INDIVIDUAL]: {
		id: "individual",
		name: "naturalPersonTitle",
		description: "naturalPersonDescription"
	},
	[LegalEntityTypes.ORGANIZATION]: {
		id: "organization",
		name: "businessEntityTitle",
		description: "businessEntityDescription"
	}
};
var convertExistingTrustMemberToDefaultData = (trustMember, allowMoreRolesForMainRootTrusteeEnabled) => {
	if (!trustMember) return {};
	if (allowMoreRolesForMainRootTrusteeEnabled && trustMember.trustMemberType === "rootTrustee") return convertRootTrusteeTrustMember(trustMember);
	return convertExistingTrustMember(trustMember);
};
var 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 { isFeatureEnabled } = useToggleContext();
	const allowMoreRolesForMainRootTrusteeEnabled = isFeatureEnabled("AllowMoreRolesForMainRootTrustee");
	const defaultData = convertExistingTrustMemberToDefaultData(existingTrustMember, allowMoreRolesForMainRootTrusteeEnabled);
	const formUtils = createFormUtils(mergedProps, commonT);
	const decideFields = (data) => {
		if (data.role?.includes("undefinedBeneficiary")) return ["role", "descriptionUndefinedBeneficiary"];
		if (data.role?.length) {
			if (isOrganizationSettlorWithExemptionEnabled && isOrganizationAndSettlor(data)) return [
				"role",
				"entityType",
				"settlorExemptionReason",
				"country",
				"legalCompanyName"
			];
			if (couldBeExemptSettlor(data, country)) return isExemptSettlor(data) ? [
				"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: "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"),
				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),
				guidance: getLegalCompanyNameGuidanceText(trustT, { country: trustRoleAndEntityTypeCountry }),
				readonly: false,
				handleChangeFor
			})] }) : void 0
		]
	});
};
//#endregion
//#region src/components/Trust/utils/addOrUpdateAssociatedTrustMember.ts
var 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
	}));
};
var addOrUpdateAssociatedTrustMember = async ({ newOrUpdated, trust, updateLegalEntity }) => {
	const otherAssociations = getOwnEntityAssociations(trust).filter((existingAssociation) => existingAssociation.legalEntityId !== newOrUpdated.legalEntityId);
	const updatedAssociations = mapTrustMemberToEntityAssociations(newOrUpdated);
	await updateLegalEntity({
		id: trust.id,
		entityAssociations: [...otherAssociations, ...updatedAssociations]
	});
};
var updateRootTrusteeTrustMember = async ({ trustMember, trust, updateLegalEntity }) => {
	const otherAssociations = getOwnEntityAssociations(trust).filter((existingAssociation) => existingAssociation.legalEntityId !== trustMember.legalEntityId);
	const updatedAssociations = mapRootTrustMemberToEntityAssociations(trustMember);
	await updateLegalEntity({
		id: trust.id,
		entityAssociations: [...otherAssociations, ...updatedAssociations]
	});
};
var mapRootTrustMemberToEntityAssociations = (trustMember) => trustMember.roles.filter((r) => r !== "secondaryTrustee").map((role) => ({
	legalEntityId: trustMember.legalEntityId,
	type: role
}));
//#endregion
//#region src/components/Trust/utils/addOrUpdateUndefinedBeneficiary.ts
var addOrUpdateUndefinedBeneficiary = async ({ newOrUpdated, trust, updateLegalEntity }) => {
	const otherUndefinedBeneficiaries = trust.trust?.undefinedBeneficiaryInfo?.filter((ub) => ub.reference !== newOrUpdated.reference) ?? [];
	await updateLegalEntity({
		id: trust.id,
		trust: { undefinedBeneficiaryInfo: [...otherUndefinedBeneficiaries, newOrUpdated.reference === isNewEntity ? { description: newOrUpdated.description } : {
			reference: newOrUpdated.reference,
			description: newOrUpdated.description
		}] }
	});
};
//#endregion
//#region src/components/Trust/utils/createExemptSettlor.ts
var createExemptSettlor = async ({ exemptSettlor, trust, handleCreateLegalEntity }) => {
	return handleCreateLegalEntity({
		type: LegalEntityTypes.INDIVIDUAL,
		individual: {
			name: {
				firstName: exemptSettlor.exemptSettlorName?.firstName ?? "",
				lastName: exemptSettlor.exemptSettlorName?.lastName ?? ""
			},
			residentialAddress: { country: trust.trust.registeredAddress.country }
		}
	});
};
var createOrganizationExemptSettlor = async ({ exemptSettlor, handleCreateLegalEntity }) => {
	return handleCreateLegalEntity({
		type: LegalEntityTypes.ORGANIZATION,
		organization: {
			legalName: exemptSettlor.name ?? "",
			registeredAddress: { country: exemptSettlor.country ?? "NL" }
		}
	});
};
//#endregion
//#region src/components/Trust/utils/updateExemptSettlorName.ts
var exemptSettlorNamesTheSame = (existingSettlor, newSettlor) => JSON.stringify(existingSettlor.exemptSettlorName) === JSON.stringify(newSettlor.exemptSettlorName);
var updateExemptSettlorName = async ({ exemptSettlor, updateLegalEntity }) => {
	return updateLegalEntity({
		id: exemptSettlor.legalEntityId,
		individual: { name: {
			firstName: exemptSettlor.exemptSettlorName?.firstName,
			lastName: exemptSettlor.exemptSettlorName?.lastName
		} }
	});
};
var updateOrganizationExemptSettlorName = async ({ exemptSettlor, updateLegalEntity }) => {
	return updateLegalEntity({
		id: exemptSettlor.legalEntityId,
		organization: {
			legalName: exemptSettlor.name,
			registeredAddress: { country: exemptSettlor.country }
		}
	});
};
var RoleAndTypeDropin_module_default = {
	"settlor-exemption-reasons-list": "adyen-kyc-settlor-exemption-reasons-list",
	settlorExemptionReasonsList: "adyen-kyc-settlor-exemption-reasons-list"
};
//#endregion
//#region src/components/Trust/tasks/RoleAndTypeDropin/formatRoleAndEntityTypeSummary.tsx
var formatRolesForSummary = (roles, commonT) => roles.map((role) => commonT(($) => $[getRoleName(role)])).join(", ");
var formatSettlorExemptionReasonsForSummary = (reasons, trustT) => /* @__PURE__ */ jsx("ul", {
	className: RoleAndTypeDropin_module_default.settlorExemptionReasonsList,
	children: reasons.map((reason) => /* @__PURE__ */ jsx("li", { children: trustT(($) => $[reason]) }, reason))
});
var 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 {};
	}
};
//#endregion
//#region src/components/Trust/tasks/RoleAndTypeDropin/RoleAndTypeDropin.tsx
var summary = {
	formId: "summary",
	formName: "summary"
};
var regularForms = {
	roleAndEntityType: {
		formId: "roleAndEntityType",
		formName: "roleAndEntityType",
		fields: ["role", "entityType"]
	},
	memberDetails: {
		formId: "memberDetails",
		formName: "memberDetails"
	},
	summary
};
var undefinedBeneficiaryForms = {
	roleAndEntityType: {
		formId: "roleAndEntityType",
		formName: "roleAndEntityType",
		fields: [
			"role",
			"entityType",
			"descriptionUndefinedBeneficiary"
		]
	},
	summary
};
var exemptSettlorForms = {
	roleAndEntityType: {
		formId: "roleAndEntityType",
		formName: "roleAndEntityType",
		fields: [
			"role",
			"entityType",
			"settlorExemptionReason"
		]
	},
	summary
};
var 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;
	}
};
var 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";
};
var logger = createLogger();
function RoleAndTypeDropin({ trust, trustMemberLe, existingTrustMember, navigateToFullDropinFor, navigateBack, country }) {
	const { t: commonT } = useTranslation("common");
	const { t: trustT } = useTranslation("trust");
	const { isFeatureEnabled } = useToggleContext();
	const allowMoreRolesForMainRootTrustee = isFeatureEnabled("AllowMoreRolesForMainRootTrustee");
	const [trustMember, setTrustMember] = useState(existingTrustMember ?? "incomplete");
	const [shouldValidate, setShouldValidate] = useState(false);
	const { showToast } = useToastContext();
	const isOrganizationSettlorWithExemptionReasonEnabled = (country) => country === 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) updated.legalEntityId = (isOrganizationSettlorWithExemptionEnabled && updated.legalEntityType === "organization" ? await createOrganizationExemptSettlor({
						exemptSettlor: updated,
						handleCreateLegalEntity: createLegalEntity
					}) : await createExemptSettlor({
						exemptSettlor: updated,
						trust,
						handleCreateLegalEntity: createLegalEntity
					})).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);
	};
	return /* @__PURE__ */ jsxs("div", {
		className: "u-display-flex",
		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--hidden" : "",
					children: /* @__PURE__ */ jsx(TrustRoleAndEntityType, {
						id: "roleAndEntityType",
						existingTrustMember,
						onChange: onTrustMemberChange,
						shouldValidate,
						isOrganizationSettlorWithExemptionEnabled,
						country
					})
				}),
				isSummaryStep && /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Summary, {
					data: summaryData,
					forms: [undefinedBeneficiaryForms.roleAndEntityType],
					gotoForm: gotoFormByFormIndex
				}) }),
				/* @__PURE__ */ jsxs("div", {
					class: "u-display-flex u-margin-top-48 u-justify-content-space-between",
					children: [
						/* @__PURE__ */ jsx(Button, {
							variant: "secondary",
							onClick: saveRolesAndNavigate,
							children: commonT(($) => $["saveAndGoToOverview"])
						}),
						/* @__PURE__ */ jsx(Spacer, {}),
						/* @__PURE__ */ jsx(Button, {
							onClick: onNavigateToNextStep,
							children: isSummaryStep ? commonT(($) => $["submit"]) : commonT(($) => $["continue"])
						})
					]
				})
			]
		})]
	});
}
//#endregion
//#region src/components/Trust/pages/TrustMemberRoleAndTypePage.tsx
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) => _rolldown_dynamic_import_helper_default(/* @__PURE__ */ Object.assign({
			"../language/bg-BG.json": () => import("./bg-BG-YZ34LkMd.js"),
			"../language/cs-CZ.json": () => import("./cs-CZ-Bl8qBkx4.js"),
			"../language/da-DK.json": () => import("./da-DK-BOU9aCaN.js"),
			"../language/de-DE.json": () => import("./de-DE-B8D6bV3u.js"),
			"../language/el-GR.json": () => import("./el-GR-mGnv3b-O.js"),
			"../language/en-US.json": () => import("./en-US-aJtjsYKh.js"),
			"../language/es-ES.json": () => import("./es-ES-BAAL2h3R.js"),
			"../language/et-EE.json": () => import("./et-EE-C4U93xrJ.js"),
			"../language/fi-FI.json": () => import("./fi-FI-IwaR92iX.js"),
			"../language/fr-FR.json": () => import("./fr-FR-DwYX21r1.js"),
			"../language/hr-HR.json": () => import("./hr-HR-CFAySNqh.js"),
			"../language/hu-HU.json": () => import("./hu-HU-DXHf3uuK.js"),
			"../language/it-IT.json": () => import("./it-IT-BK6Yn4vc.js"),
			"../language/ja-JP.json": () => import("./ja-JP-B5fRnSzi.js"),
			"../language/lt-LT.json": () => import("./lt-LT-Dkvuak-E.js"),
			"../language/lv-LV.json": () => import("./lv-LV-Cz0igciN.js"),
			"../language/nl-NL.json": () => import("./nl-NL-BTuDiajY.js"),
			"../language/no-NO.json": () => import("./no-NO-D6C6Imfk.js"),
			"../language/pl-PL.json": () => import("./pl-PL-DNdGYT-E.js"),
			"../language/pt-BR.json": () => import("./pt-BR-BgiNMjMc.js"),
			"../language/pt-PT.json": () => import("./pt-PT-CWzCKCL8.js"),
			"../language/ro-RO.json": () => import("./ro-RO-DLtPW1MX.js"),
			"../language/sk-SK.json": () => import("./sk-SK-DNKyL6Hl.js"),
			"../language/sl-SI.json": () => import("./sl-SI-DNgxTuIJ.js"),
			"../language/sv-SE.json": () => import("./sv-SE-BM8WESGs.js")
		}), `../language/${lang}.json`, 3)
	}]);
	if (!trustLe || memberId && !memberLe) return /* @__PURE__ */ jsx(Loader, {});
	const country = getLegalEntityCountry(memberLe ?? trustLe);
	return /* @__PURE__ */ jsx(RoleAndTypeDropin, {
		trust: trustLe,
		trustMemberLe: memberLe,
		existingTrustMember: memberId ? trustMembers.find((tm) => tm.trustMemberType !== "undefinedBeneficiary" && tm.legalEntityId === memberId) : void 0,
		country,
		navigateToFullDropinFor,
		navigateBack
	});
}
//#endregion
export { TrustMemberRoleAndTypePage };
