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] = "7702d07b-f1af-4fe5-be4e-563d73acd805", e._sentryDebugIdIdentifier = "sentry-dbid-7702d07b-f1af-4fe5-be4e-563d73acd805");
} catch (e) {}
import { i as Typography, n as addResourceBundles, r as useTranslation } from "./translation-Br5wIPO-.js";
import { r as Loader } from "./Button-BDEdGXnd.js";
import { s as useApiContext } from "./http-CHTzpXCd.js";
import { r as useLegalEntity, t as ROOT_LE } from "./useLegalEntity-Dm6g0wmt.js";
import { t as LegalEntityTypes } from "./legal-entity-type-VIfNYnJP.js";
import { t as getLegalEntityCountry } from "./getLegalEntityCountry-C6bSV6sB.js";
import { i as drop, l as keysOf, n as cloneObject } from "./AnalyticsContext-C0HNdPss.js";
import { C as isValidMinLength, _ as hasText, a as NO_ALPHABET_REGEX, g as hasRepeatedCharacters, n as EMOJI_REGEX, s as OTHER_ENTITIES_VALID_CHAR_REGEX, w as matchesRegex, x as isInvalidName } 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 { t as useCapabilities } from "./useCapabilities-DN0V0pML.js";
import { n as datasetUtilities } from "./datasetUtil-BZmNUckr.js";
import { t as Alert } from "./Alert-CjZYipjN.js";
import { C as EntityTypes, a as trustComponentsKeyMapping, i as trustApiKeyMapping, o as trustDocumentMapping, y as reverseMapping } from "./processCapabilities-CDSEJpB8.js";
import { t as TaskTypes } from "./taskTypes-DWaxzvnQ.js";
import { s as getOwnEntityAssociations } from "./entityAssociationUtil-C0gX4Ewv.js";
import { t as getCountrySpecificTrustTypeOptions } from "./trustUtil-CVipffas.js";
import { t as useToastContext } from "./useToastContext-CK7UoZ5Z.js";
import { n as useCapabilityProblems, t as getProblemsForEntity } from "./getProblemsForEntity-COcJt47f.js";
import { t as useAssociatedLegalEntity } from "./useAssociatedLegalEntity-CYu0lsaE.js";
import { t as useCreateLegalEntity } from "./useCreateLegalEntity-C149Z7Xu.js";
import { t as useUpdateLegalEntity } from "./useUpdateLegalEntity-CUs6TYPF.js";
import { t as Address } from "./Address-CHpJLi-Q.js";
import { i as FormFlow, n as addValidityToForms, o as useFormComposer, r as getRequiredForms, s as FormContextProvider, t as useFormContext } from "./useFormContext-Cu4dKSCy.js";
import { n as composePerScenarioFormConfigurations, r as getPropsFromConfigurations, t as augmentWithCountryConfigs } from "./process-field-configurations-B8wJu-eM.js";
import { t as ErrorPanel } from "./ErrorPanel-5g1eTEVD.js";
import { n as mergeFieldMetadataIntoProps, t as createFormUtils } from "./formUtils-DERTAXyh.js";
import { t as useMultiForm } from "./useMultiForm-tpVMuqHM.js";
import { i as useScenarioConfiguration, r as getPageName, t as mapExistingFile } from "./mapExistingFile-BeFexL6Z.js";
import { t as useTaskLandedEvent } from "./useTaskLandedEvent-DCdJo64z.js";
import { i as mapAddressLabels } from "./utils-DLDyhf2J.js";
import { i as isValidationError, o as processValidationErrors, s as isMaintenanceModeError } from "./validationError-Dr0g0lGN.js";
import { c as getDocument, o as createDocumentRequest, s as documentApiUtils } from "./validate-DlG5LXuM.js";
import { r as formatObject } from "./utils--gwzjjeS.js";
import { a as getFieldsWithExistingData, n as TaxInformationField, t as TAX_INFORMATION_FIELD } from "./TaxInformationField-CJyqFS0F.js";
import { a as validateNotEmptyOnBlur } from "./patternValidators-DMnU4iGe.js";
import { S as taxInformationDefaultFieldMetadata, i as COUNTRIES_THAT_USE_TAX_ID_INSTEAD_OF_VAT, u as countryToTaxInfoTypeMap, v as exemptedFromTaxDefaultFieldConfig, x as taxInformationDefaultFieldConfig, y as exemptedFromTaxDefaultFieldMetadata } from "./utils-CkQJVYhR.js";
import { t as resolveFieldMetadata } from "./fieldConfigurations-B3oqm4GC.js";
import { t as Field } from "./Field-BEqknhTe.js";
import { t as Select } from "./Select-CMFHti4N.js";
import { n as getFormProps } from "./getProps-DQy_qV_x.js";
import { t as InputText } from "./InputText-CadVntiC.js";
import { n as CountryField, t as COUNTRY_FIELD } from "./CountryField-B-JxQ6z9.js";
import { t as RadioGroup } from "./RadioGroup-XuCtbRrH.js";
import { t as createFormRules } from "./form-rules-CvdV5rPY.js";
import { t as ContextGuidance } from "./ContextGuidance-CxOv00_a.js";
import { c as getRegistrationNumberHelperText, i as getCompanyRegistrationNumberOptions, l as registrationNumberDefaultFieldConfig, n as getDefaultRegistrationNumberType, o as exemptFromRegistrationNumberDefaultFieldConfig, r as inferCompanyRegistrationNumberType, s as exemptFromRegistrationNumberDefaultFieldMetadata, u as registrationNumberDefaultFieldMetadata } from "./CompanyRegistrationNumberTypeSelector-CeRtLSxc.js";
import { a as VAT_NUMBER_FIELD, c as defaultFieldConfig, d as doingBusinessAsAbsentFieldMetadata, f as doingBusinessAsFieldMetadata, g as BusinessRegistrationNumberField, h as BUSINESS_REGISTRATION_NUMBER_FIELD, i as operationalAddressIsSameItems, l as defaultFieldMetadata, m as DBA_NAME_FIELD, n as registrationAddressFields, o as VatNumberField, p as DBANameField, r as operationalAddressIsSameIds, s as getDefaultVatNumberType, t as MemoizedConstitutionalDocument } from "./ConstitutionalDocument-Jqgyahcj.js";
import { a as UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_REQUIRED, i as UNINCORPORATED_PARTNERSHIP_COUNTRIES_TAX_INFORMATION_OPTIONAL, n as UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_OPTIONAL, o as UNINCORPORATED_PARTNERSHIP_COUNTRIES_VAT_NUMBER_OPTIONAL, r as UNINCORPORATED_PARTNERSHIP_COUNTRIES_REGISTRATION_NUMBER_REQUIRED, t as ALLOWED_UNINCORPORATED_PARTNERSHIP_COUNTRIES } from "./types-ewJwhKUi.js";
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { Fragment, jsx, jsxs } from "preact/jsx-runtime";
import { skipToken } from "@tanstack/preact-query";
//#region src/components/Trust/mapping/mapApiDocumentToTrustDocument.ts
var mapApiDocumentToTrustDocument = (entityId) => {
	const constitutionalDocument = getDocument(entityId, "constitutionalDocument") || null;
	return { trustConstitutionalDocument: constitutionalDocument ? { constitutionalDocument: [mapExistingFile(getPageName(constitutionalDocument))] } : void 0 };
};
//#endregion
//#region src/components/UnincorporatedPartnership/mapping/unincorporatedPartnershipKeyMappings.ts
var 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"
};
var unincorporatedPartnershipComponentsKeyMapping = {
	"trustRegistrationDetails.exemptedFromVat": "unincorporatedPartnership.vatAbsenceReason",
	...unincorporatedPartnershipBaseMapping
};
var unincorporatedPartnershipApiKeyMapping = { ...reverseMapping(unincorporatedPartnershipBaseMapping) };
//#endregion
//#region src/components/UnincorporatedPartnership/mapping/mapLegalEntityToUnincorporatedPartnership.ts
var mapLegalEntityToUnincorporatedPartnership = (legalEntity, isFeatureEnabled) => {
	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 (isFeatureEnabled("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;
};
//#endregion
//#region src/components/UnincorporatedPartnership/mapping/mapUnincorporatedPartnershipToLegalEntity.ts
var mapUnincorporatedPartnershipToLegalEntity = (data, isFeatureEnabled) => {
	const requestObj = { ...formatObject(data, unincorporatedPartnershipApiKeyMapping) };
	if (!requestObj.unincorporatedPartnership) return requestObj;
	if (requestObj.unincorporatedPartnership?.taxInformation?.[0]?.type === "GST") requestObj.unincorporatedPartnership.taxInformation[0].type = "UEN";
	if (isFeatureEnabled("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;
};
//#endregion
//#region src/components/Trust/forms/Trust/rules.ts
var COUNTRIES_THAT_USE_REGISTRATION_NUMBER = [CountryCodes.NewZealand];
var rules = ({ data, country, 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";
	},
	requireDoingBusinessAsName: () => {
		return data?.trustRegistrationDetails?.hasDoingBusinessAs ? "REQUIRED" : void 0;
	},
	requiresTrustType: () => {
		if (taskType === TaskTypes.TRUST) return "REQUIRED";
	}
});
//#endregion
//#region src/components/Trust/mapping/mapLegalEntityToTrust.ts
var mapLegalEntityToTrust = (legalEntity, isFeatureEnabled) => {
	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 (isFeatureEnabled("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;
};
//#endregion
//#region src/components/Trust/mapping/mapTrustDocumentToApiDocument.ts
var 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");
	return await createDocumentRequest({
		entityId,
		entityType: "legalEntity",
		documentType: "constitutionalDocument",
		page1,
		existingDocument: getDocument(entityId, "constitutionalDocument")
	});
};
//#endregion
//#region src/components/Trust/mapping/mapTrustToLegalEntity.ts
var mapTrustToLegalEntity = (data, isFeatureEnabled) => {
	const requestObj = { ...formatObject(data, trustApiKeyMapping) };
	if (!requestObj.trust) return requestObj;
	if (data.trustRegistrationDetails?.objectOfTrust) requestObj.trust.description = data.trustRegistrationDetails.objectOfTrust;
	if (isFeatureEnabled("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;
};
//#endregion
//#region src/components/Shared/forms/RegistrationAddress/RegistrationAddressMultiform.tsx
var registrationAddressFormID = {
	registrationAddress: {
		formId: "registrationAddress",
		formName: "registeredAddress",
		fields: ["address"]
	},
	operationalAddress: {
		formId: "operationalAddress",
		formName: "operationalAddressHeader",
		fields: ["address"]
	}
}.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 formUtils = createFormUtils({
		...props,
		requiredFields: registrationAddressRequiredFields,
		optionalFields: registrationAddressOptionalFields,
		readOnlyFields: registrationAddressReadOnlyFields,
		obscuredFields: registrationAddressObscuredFields,
		verifyFields: registrationAddressVerifyFields,
		trustedFields: registrationAddressTrustedFields
	}, t);
	const isOperationAddressNotSame = () => data?.operationalAddressIsSame === operationalAddressIsSameIds.OPERATIONAL_ADDRESS_IS_NOT_SAME;
	const registrationAddressValidRef = useRef(Boolean(form.valid.trustRegistrationAddress?.registrationAddress));
	const operationalAddressValidRef = useRef(Boolean(form.valid.trustRegistrationAddress?.operationalAddress));
	useEffect(() => {
		if (form.valid.trustRegistrationAddress?.registrationAddress !== registrationAddressValidRef.current) form.setValid("registrationAddress", registrationAddressValidRef.current, "trustRegistrationAddress");
		if (isOperationAddressNotSame() && form.valid.trustRegistrationAddress?.operationalAddress !== operationalAddressValidRef.current) form.setValid("operationalAddress", operationalAddressValidRef.current, "trustRegistrationAddress");
	}, [form.valid.trustRegistrationAddress]);
	const handleChangeFor = useCallback((fieldName, mode) => form.handleChangeFor(fieldName, "trustRegistrationAddress", mode), [form]);
	const handleRegistrationAddressChange = (state) => {
		handleChangeFor("registrationAddress")(state.data);
		registrationAddressValidRef.current = Boolean(state.isValid);
	};
	const handleOperationalAddressChange = (state) => {
		handleChangeFor("operationalAddress")(state.data);
		operationalAddressValidRef.current = Boolean(state.isValid);
	};
	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")
	] });
}
//#endregion
//#region src/components/Trust/forms/TrustRegistrationDetails/TrustRegistrationDetails.tsx
var trustRegistrationDetailsFields = [
	"legalName",
	...DBA_NAME_FIELD,
	"country",
	"trustType",
	"objectOfTrust",
	...TAX_INFORMATION_FIELD,
	...BUSINESS_REGISTRATION_NUMBER_FIELD,
	...VAT_NUMBER_FIELD
];
var ALLOWED_TRUST_COUNTRIES = [CountryCodes.Australia, CountryCodes.NewZealand];
var TRUST_REGISTRATION_DETAILS = "trustRegistrationDetails";
function TrustRegistrationDetails({ fieldValidationErrors = {}, formVerificationErrors = {}, heading, shouldValidate, taskType, country: parentLegalEntityCountry }) {
	const { t: trustT } = useTranslation("trust");
	const { t: CommonT } = useTranslation("common");
	const { form } = useFormContext();
	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, TRUST_REGISTRATION_DETAILS, 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
				}, 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,
		obscuredFields,
		optionalFields,
		requiredFields,
		trustedFields,
		valid
	]);
	const showField = (fieldName) => formUtils.isRequiredField(fieldName) || formUtils.isOptionalField(fieldName);
	return /* @__PURE__ */ jsxs("form", {
		id: 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: "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),
				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"),
				readonly: formUtils.isReadOnly("taxInformation"),
				shouldValidate,
				handleChangeFor: handleChange,
				optional: formUtils.isOptionalField("taxInformation"),
				canExempt: formUtils.isRequiredField("exemptedFromTax"),
				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"),
				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" }),
				optional: formUtils.isOptionalField("vatNumber"),
				readonly: formUtils.isReadOnly("vatNumber"),
				handleChangeFor: handleChange,
				country,
				canExempt: formUtils.isRequiredField("exemptedFromVat")
			})
		]
	});
}
//#endregion
//#region src/components/Trust/tasks/TrustDropin/Trust.tsx
var trustForms = {
	trustRegistrationDetails: {
		formId: TRUST_REGISTRATION_DETAILS,
		formName: "registrationDetails",
		fields: [...trustRegistrationDetailsFields]
	},
	trustRegistrationAddress: {
		formId: "trustRegistrationAddress",
		formName: "addressDetails",
		fields: registrationAddressFields
	},
	trustConstitutionalDocument: {
		formId: "trustConstitutionalDocument",
		formName: "constitutionalDocument",
		fields: ["constitutionalDocument"]
	}
};
var trustRegistrationAddressFormId = trustForms.trustRegistrationAddress.formId;
var trustRegistrationDetailsFormId = TRUST_REGISTRATION_DETAILS;
var trustConstitutionalDocumentFormId = trustForms.trustConstitutionalDocument.formId;
function Trust(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 = (activeForm) => {
		switch (activeForm.formId) {
			case trustRegistrationDetailsFormId: return /* @__PURE__ */ jsx(TrustRegistrationDetails, {
				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: activeForm.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?.[activeForm.formId] ?? {},
				formVerificationErrors: problems.verificationErrors?.[activeForm.formId] ?? {}
			});
			default: return null;
		}
	};
	return /* @__PURE__ */ jsx("div", { children: renderActiveForm(activeForm || trustForms.trustRegistrationDetails) });
}
//#endregion
//#region src/components/Trust/tasks/TrustDropin/trustFormConfig.ts
var trustBase = {
	trustType: { rule: "requiresTrustType" },
	objectOfTrust: { rule: "trustTypeHasDescription" },
	legalName: { rule: "REQUIRED" },
	hasDoingBusinessAs: { rule: "REQUIRED" },
	doingBusinessAs: { rule: "requireDoingBusinessAsName" },
	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" }
};
var trustFieldsPerScenario = {
	L0: { ...trustBase },
	L1: { ...trustBase },
	L: { ...trustBase }
};
var trustCountryConfig = {};
//#endregion
//#region src/components/Trust/forms/TrustRegistrationDetails/validate.ts
var 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
};
var 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
};
//#endregion
//#region src/components/Trust/tasks/TrustDropin/validate.ts
function trustRegistrationDetailsValidators(country, trustRegistrationDetails = {}, isFeatureEnabled) {
	const defaultTrustRegistrationDetailsValidators = isFeatureEnabled("StrictNameAndAddressValidationV4") ? 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,
			isFeatureEnabled
		}, registrationNumberDefaultFieldMetadata)?.validators,
		exemptedFromRegistrationNumber: resolveFieldMetadata(exemptFromRegistrationNumberDefaultFieldConfig[country], {}, exemptFromRegistrationNumberDefaultFieldMetadata)?.validators,
		vatNumber: resolveFieldMetadata(defaultFieldConfig[country], { vatNumberType }, defaultFieldMetadata)?.validators
	};
}
//#endregion
//#region src/components/Trust/tasks/TrustDropin/TrustDropin.tsx
var parseTrustScenarios = (scenarios, country) => augmentWithCountryConfigs(trustCountryConfig[country], composePerScenarioFormConfigurations(scenarios, trustFieldsPerScenario));
var parseConfiguration = ({ scenarios, country }) => parseTrustScenarios(scenarios, country);
function TrustDropin({ parentLegalEntity, country: countryProp, existingTrust, taskType, problems: problemsProp, onSubmit: externalOnSubmit, handleHomeClick }) {
	const { baseUrl, rootLegalEntityId } = useApiContext();
	const { t, i18n } = useTranslation(["common", "trust"]);
	const [validationErrors, setValidationErrors] = useState();
	const datasetUtils = datasetUtilities(i18n.language);
	const { isFeatureEnabled } = useToggleContext();
	const { showToast } = useToastContext();
	const [loadingStatus, setLoadingStatus] = useState("success");
	const [country, setCountry] = useState(countryProp);
	const isUnincorporatedPartnership = taskType === TaskTypes.UNINCORPORATED_PARTNERSHIP;
	const problems = useMemo(() => ({
		...problemsProp,
		validationErrors
	}), [problemsProp, validationErrors]);
	const [initialData, setInitialData] = useState(useMemo(() => {
		if (!existingTrust) return { trustRegistrationDetails: { country: countryProp } };
		return isUnincorporatedPartnership ? mapLegalEntityToUnincorporatedPartnership(existingTrust, isFeatureEnabled) : mapLegalEntityToTrust(existingTrust, isFeatureEnabled);
	}, [
		isFeatureEnabled,
		existingTrust,
		isUnincorporatedPartnership,
		countryProp
	]));
	const documentUtils = documentApiUtils({
		baseUrl: baseUrl.value,
		rootLegalEntityId: rootLegalEntityId.value
	});
	/**
	* Analytics
	*/
	useTaskLandedEvent(taskType);
	useEffect(() => {
		if (!existingTrust?.documentDetails?.length) return;
		documentUtils.fetchDocuments(existingTrust.documentDetails, existingTrust.id).then(() => {
			const mappedDocuments = mapApiDocumentToTrustDocument(existingTrust.id);
			setInitialData((prev) => ({
				...prev,
				...mappedDocuments
			}));
		}).catch(() => {
			showToast({
				label: t(($) => $["failedToFetchRelevantDocuments"]),
				variant: "error"
			});
		});
	}, []);
	const [derivedProps, setDerivedProps] = useState();
	const buildTrustValidations = useCallback((data) => {
		return { trustRegistrationDetails: trustRegistrationDetailsValidators(country, data?.trustRegistrationDetails, isFeatureEnabled) };
	}, [country, isFeatureEnabled]);
	const multiForm = useMultiForm({
		defaultData: initialData,
		allFields: derivedProps?.allFields,
		requiredFields: derivedProps?.requiredFields,
		optionalFields: derivedProps?.optionalFields,
		obscuredFields: derivedProps?.obscuredFields,
		trustedFields: derivedProps?.trustedFields,
		rules: buildTrustValidations
	});
	/**
	* Fetch Configurations
	*/
	const { fieldConfigurations, requiredFields } = useScenarioConfiguration({
		parseConfiguration,
		legalEntityType: LegalEntityTypes.TRUST,
		setLoadingStatus,
		country
	});
	const fieldsFromCustomRules = useMemo(() => rules({
		data: multiForm.data,
		country,
		taskType,
		requiredFields
	}), [
		country,
		multiForm.data,
		taskType,
		requiredFields
	]);
	useEffect(() => {
		setDerivedProps(getPropsFromConfigurations({
			scenarioConfiguration: fieldConfigurations,
			forms: trustForms,
			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
	]);
	/**
	* Current country value must be kept in sync with what is selected in basicInformation form
	*/
	const [prevCountry, setPrevCountry] = useState(multiForm.data.trustRegistrationDetails?.country);
	if (multiForm.data.trustRegistrationDetails?.country && prevCountry !== multiForm.data.trustRegistrationDetails?.country) {
		setCountry(multiForm.data?.trustRegistrationDetails?.country ?? countryProp);
		setPrevCountry(multiForm.data.trustRegistrationDetails?.country);
	}
	const forms = useMemo(() => {
		return addValidityToForms(getRequiredForms(trustForms, derivedProps?.requiredFields, derivedProps?.optionalFields), multiForm.isValid, problems);
	}, [
		derivedProps,
		multiForm.isValid,
		problems
	]);
	const onSubmitTrust = async () => {
		setLoadingStatus("loading");
		const trustDetails = mapTrustToLegalEntity(multiForm.data, isFeatureEnabled);
		try {
			const updatedTrust = await submitTrustDetails(trustDetails);
			await submitDocuments({
				forms,
				legalEntity: updatedTrust,
				dataSubmitted: multiForm.data
			});
			await attachTrustToParentLegalEntity(updatedTrust);
			setLoadingStatus("success");
			showToast({
				label: t(($) => $["successfullyUpdatedDetails"]),
				variant: "success"
			});
			externalOnSubmit?.(multiForm.data);
		} catch (e) {
			if (isValidationError(e)) setValidationErrors(processValidationErrors(e, taskType));
			else if (isMaintenanceModeError(e)) showToast({
				label: t(($) => $["maintenanceModeMessage"]),
				variant: "error",
				duration: "indefinite"
			});
			else showToast({
				label: t(($) => $["failedToUpdateDetails"]),
				variant: "error"
			});
			setLoadingStatus("success");
		}
	};
	const onSubmitUnincorporatedPartnership = async () => {
		setLoadingStatus("loading");
		const unincorporatedPartnershipDetails = mapUnincorporatedPartnershipToLegalEntity(multiForm.data, isFeatureEnabled);
		try {
			const updatedUnincorporatedPartnershipDetails = await submitTrustDetails(unincorporatedPartnershipDetails);
			await submitDocuments({
				forms,
				legalEntity: updatedUnincorporatedPartnershipDetails,
				dataSubmitted: multiForm.data
			});
			await attachTrustToParentLegalEntity(updatedUnincorporatedPartnershipDetails);
			setLoadingStatus("success");
			showToast({
				label: t(($) => $["successfullyUpdatedDetails"]),
				variant: "success"
			});
			externalOnSubmit?.(multiForm.data);
		} catch (e) {
			if (isValidationError(e)) setValidationErrors(processValidationErrors(e, taskType));
			else if (isMaintenanceModeError(e)) showToast({
				label: t(($) => $["maintenanceModeMessage"]),
				variant: "error",
				duration: "indefinite"
			});
			else showToast({
				label: t(($) => $["failedToUpdateDetails"]),
				variant: "error"
			});
			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, legalEntity, dataSubmitted }) => {
		if (isDocumentsRequired(forms)) {
			const formattedDocument = await mapTrustDocumentToApiDocument(dataSubmitted, legalEntity.id);
			if (formattedDocument) await documentUtils.uploadDocuments([formattedDocument], legalEntity.id);
		}
	};
	const isDocumentsRequired = (forms) => forms.some((form) => form.formId === trustForms.trustConstitutionalDocument.formId);
	const attachTrustToParentLegalEntity = async (trust) => {
		if (existingTrust?.id) return;
		const existingEntityAssociations = getOwnEntityAssociations(parentLegalEntity);
		await updateLegalEntity({
			entityAssociations: [{
				type: trust.type,
				legalEntityId: trust.id
			}, ...existingEntityAssociations],
			id: parentLegalEntity.id
		});
	};
	const formatDataForSummary = useCallback((formData, forms) => {
		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(forms)) summaryData = {
			...summaryData,
			...formatFileSummaryData(formData.trustConstitutionalDocument)
		};
		else delete summaryData[trustConstitutionalDocumentFormId];
		return summaryData;
	}, [
		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, gotoFormByFormId, steps } = useFormComposer({
		problems,
		forms,
		onSubmit: isUnincorporatedPartnership ? onSubmitUnincorporatedPartnership : onSubmitTrust,
		triggerValidation: multiForm.triggerValidation
	});
	return /* @__PURE__ */ jsx(FormContextProvider, {
		form: multiForm,
		children: /* @__PURE__ */ jsx(FormFlow, {
			summary: {
				data: useMemo(() => formatDataForSummary(multiForm.data, forms), [
					formatDataForSummary,
					multiForm.data,
					forms
				]),
				omitted: { keys: ["operationalAddressIsSame"] }
			},
			currentStep: steps.current,
			totalSteps: steps.total,
			forms,
			activeForm,
			gotoFormByFormIndex,
			gotoFormByFormId,
			handleNextClick,
			handleBackClick,
			handleCancelClick: handleHomeClick,
			loadingStatus,
			children: /* @__PURE__ */ jsx(Trust, {
				country,
				activeForm,
				taskType,
				shouldValidate,
				problems
			})
		})
	});
}
//#endregion
//#region src/components/Trust/pages/TrustDetailsPage.tsx
var TrustDetailsPage = ({ taskType, trustId, handleHomeClick, onSubmit }) => {
	const { i18n } = useTranslation();
	const { data: rootLe } = useLegalEntity(ROOT_LE);
	const { data: associatedEntity, isLoading: isAssociatedEntityLoading } = useAssociatedLegalEntity(rootLe, taskType === "TRUST" ? LegalEntityTypes.TRUST : LegalEntityTypes.UNINCORPORATED_PARTNERSHIP);
	const { data: trustLeFromProp, isLoading: isTrustLeFromPropLoading } = useLegalEntity(trustId ?? skipToken);
	const trustLe = trustLeFromProp ?? associatedEntity;
	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)
	}]);
	const capabilities = useCapabilities();
	const capabilityNames = capabilities ? keysOf(capabilities) : [];
	const capabilityProblems = useCapabilityProblems();
	const problems = capabilityProblems && trustLe?.id ? getProblemsForEntity(capabilityProblems, EntityTypes.LEGAL_ENTITY, trustLe.id) : void 0;
	if (!rootLe || isAssociatedEntityLoading || isTrustLeFromPropLoading) return /* @__PURE__ */ jsx(Loader, {});
	return /* @__PURE__ */ jsx(TrustDropin, {
		taskType,
		problems,
		existingTrust: trustLe,
		parentLegalEntity: rootLe,
		capabilities: capabilityNames,
		country: getLegalEntityCountry(trustLe ?? rootLe),
		handleHomeClick,
		onSubmit
	});
};
//#endregion
export { TrustDetailsPage };
