;
{
  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] = "9e15aafd-893a-42bc-b47f-fc221c4de5c0", e._sentryDebugIdIdentifier = "sentry-dbid-9e15aafd-893a-42bc-b47f-fc221c4de5c0");
  } catch (e) {
  }
}
;
import { b as useApiContext, $ as httpPost, k as httpGet, u as useTranslation, z as Typography, V as Button, aa as useI18nContext, L as Loader, r as Icon, t as IconButton, H as TASK_STATUS_POLLING_INTERVAL_MS, a3 as createLogger, c as useLegalEntity, R as ROOT_LE, p as useAnalyticsContext, bE as useLegalEntities, a as addResourceBundles, a8 as EntityTypes, g as getLegalEntityCountry, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsxs, Fragment, jsx } from "preact/jsx-runtime";
import { u as useCapabilityProblems, g as getProblemsForEntity } from "./getProblemsForEntity-C1PgQbDM.js";
import { useState, useMemo, useCallback, useEffect } from "preact/hooks";
import { u as useBusinessLines } from "./useBusinessLines-Bqjsys_I.js";
import { useMutation, useQuery, useQueryClient } from "@tanstack/preact-query";
import { a as useInvalidateRootLegalEntity, u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { u as useCreateLegalEntity } from "./useCreateLegalEntity-swV6s65R.js";
import { u as useUpdateLegalEntity } from "./useUpdateLegalEntity-CcNBhTXa.js";
import { u as useFormContext, F as FormContextProvider, a as FormFlow } from "./useFormContext-LfOXbOKX.js";
import { g as getRequiredForms, a as addValidityToForms, u as useFormComposer } from "./dropinUtils-G5Ua27s3.js";
import { u as useMultiForm } from "./useMultiForm-XT1CUuQs.js";
import { c as createDocumentRequest, d as documentApiUtils } from "./validate-CtroZEiR.js";
import { f as formatObject } from "./utils-DNSfZiio.js";
import { signal } from "@preact/signals";
import { E as ErrorPanel } from "./ErrorPanel-D-VMcBB9.js";
import { c as createFormUtils } from "./formUtils-CwOJPw6N.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { T as TextArea } from "./TextArea-DR0WD0kF.js";
import { I as InputDate } from "./InputDate-4iN1Hh4k.js";
import { I as InputGroup } from "./InputGroup-WBfGDV5F.js";
import { I as InputText } from "./InputText-DRSK56ma.js";
import { a as allowedCurrencies, T as TODAY_DATE, S as SOF_CHARACTERS_LIMIT, b as formatDateForInput, g as getInputErrors, c as formatAmountWithCurrency, s as sofCategoryItemMapper, d as getPageHeadings, e as getServiceTranslationSelectTitle, h as getSofCardDetails, i as getGettingStartedCardDetails, j as getAdditionalDataSchemaKeys, k as getServiceTranslation, p as parseSOFDocumentDescription, l as getRelevantErrors, m as getUniqueRemediationActions, n as SOF_INVALID_INPUT_ERROR_CODES, o as getServiceTranslationKey, q as getDocumentRequirements, r as getDocumentLists, t as getSourceOfFundsRequiredFields, M as MISSING_DATA_SOF_UPLOAD_CODE, u as parseOriginatorDetails, v as getSourceOfFundsRequiredForms, w as getSourceOfFundsPayload, A as ALLOWED_SOF_SERVICES, x as parseSofOriginatorPayload } from "./utils-C5l2PwQS.js";
import { R as RadioGroup } from "./RadioGroup-jkgDMvvX.js";
import { C as CountryField } from "./CountryField-DDFphSWX.js";
import { A as Avatar } from "./Avatar-9UrQk3Hf.js";
import { a as Alert } from "./Alert-CpDg47bv.js";
import { M as Modal } from "./Modal-1lLoobr9.js";
import { C as Confirm } from "./Confirm-BeimUgOe.js";
import { T as TileGroup } from "./TileGroup-CFNn8NKj.js";
import { lazy } from "preact/compat";
import { u as useTaskStatus } from "./useTaskStatus-mjcLNZSC.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import { I as Image } from "./Image-C0SMWMbc.js";
import { L as LandingLayout } from "./LandingLayout-B4GiCZLB.js";
import { S as StackLayout } from "./unincorporated-partnership-MeN1dp53.js";
import { i as isEmpty } from "./isEmpty-vwqWRDI4.js";
import { C as Card } from "./Card-OQuFzmxm.js";
import { S as StructuredList } from "./StructuredList-BNLhk_zV.js";
import { D as Dropzone } from "./Dropzone-Gyk4t9Dh.js";
import { v as validateDateNotInTheFuture } from "./validate-BECfS2vQ.js";
const updateSourceOfFunds = async (businessLineId, legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/businessLines/${businessLineId}/sourceOfFunds`
    },
    data
  );
};
const useUpdateSourceOfFunds = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  const invalidateRootLegalEntity = useInvalidateRootLegalEntity();
  return useMutation({
    mutationFn: ({ businessLineId, ...requestData }) => updateSourceOfFunds(businessLineId, rootLegalEntityId.value, baseUrl.value, requestData),
    onSuccess: async () => {
      await invalidateRootLegalEntity();
    },
    ...options
  });
};
const sourceOfFundsBaseMapping = {
  "sourceOfFundsType.type": "sourceOfFunds.type",
  "additionalData.description": "sourceOfFunds.description",
  "additionalData.amount": "sourceOfFunds.amount",
  "additionalData.dateOfFundsReceived": "sourceOfFunds.dateOfFundsReceived",
  "additionalData.purpose": "sourceOfFunds.purpose",
  "additionalData.relationship": "sourceOfFunds.relationship",
  "additionalData.originatorLegalEntityId": "sourceOfFunds.originatorLegalEntityId",
  "additionalData.financiers": "sourceOfFunds.financiers",
  "additionalData.cryptocurrencyExchange": "sourceOfFunds.cryptocurrencyExchange",
  "additionalData.dateOfSourceEvent": "sourceOfFunds.dateOfSourceEvent",
  "additionalData.website": "sourceOfFunds.website",
  "additionalData.legalName": "sourceOfFunds.legalName",
  "additionalData.firstName": "sourceOfFunds.firstName",
  "additionalData.lastName": "sourceOfFunds.lastName",
  "additionalData.country": "sourceOfFunds.country",
  "additionalData.originatorType": "sourceOfFunds.originatorType"
};
const sourceOfFundsComponentsKeyMapping = {
  ...sourceOfFundsBaseMapping
};
const mapSourceOfFundToSourceOfFundsSchema = (businessLine) => formatObject(businessLine, sourceOfFundsComponentsKeyMapping);
const sofErrorMessage = signal(void 0);
const setSofErrorMessage = (message) => {
  sofErrorMessage.value = message;
};
const clearSofErrorMessage = () => {
  sofErrorMessage.value = void 0;
};
const getSourceOfFundsTypes = async (baseUrl) => {
  return httpGet({
    baseUrl,
    path: `datasets/sourceOfFundsTypes`
  });
};
const useSourceOfFundsTypes = (options) => {
  const { baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["sourceOfFundsTypes"],
    queryFn: () => getSourceOfFundsTypes(baseUrl.value),
    ...options
  });
};
const sourceOfFunds = "adyen-kyc-source-of-funds";
const sourceOfFundsWrapperLoading = "adyen-kyc-source-of-funds-wrapper-loading";
const sourceOfFundsWrapperHeading = "adyen-kyc-source-of-funds-wrapper-heading";
const sourceOfFundsWrapperDescription = "adyen-kyc-source-of-funds-wrapper-description";
const sourceOfFundsGettingStarted = "adyen-kyc-source-of-funds-getting-started";
const sourceOfFundsGettingStartedError = "adyen-kyc-source-of-funds-getting-started-error";
const sourceOfFundsGettingStartedErrorActions = "adyen-kyc-source-of-funds-getting-started-error-actions";
const sourceOfFundsGettingStartedCards = "adyen-kyc-source-of-funds-getting-started-cards";
const sourceOfFundsGettingStartedCardsCardHeader = "adyen-kyc-source-of-funds-getting-started-cards-card-header";
const sourceOfFundsGettingStartedCardsCardBody = "adyen-kyc-source-of-funds-getting-started-cards-card-body";
const sourceOfFundsGettingStartedActions = "adyen-kyc-source-of-funds-getting-started-actions";
const sourceOfFundsAdditionalDataForm = "adyen-kyc-source-of-funds-additional-data-form";
const sourceOfFundsThirdPartyFundingFinancierGroup = "adyen-kyc-source-of-funds-third-party-funding-financier-group";
const sourceOfFundsThirdPartyFundingNameAvatarGroup = "adyen-kyc-source-of-funds-third-party-funding-name-avatar-group";
const sourceOfFundsThirdPartyFundingNameAddressGroup = "adyen-kyc-source-of-funds-third-party-funding-name-address-group";
const sourceOfFundsSofFinancierFormError = "adyen-kyc-source-of-funds-sof-financier-form-error";
const sourceOfFundsSofFinancierFormNameGroup = "adyen-kyc-source-of-funds-sof-financier-form-name-group";
const sourceOfFundsFinancierFooter = "adyen-kyc-source-of-funds-financier-footer";
const sourceOfFundsGridContainer = "adyen-kyc-source-of-funds-grid-container";
const sourceOfFundsUploadModalContentField = "adyen-kyc-source-of-funds-upload-modal-content-field";
const sourceOfFundsUploadModalContentFieldRadioGroup = "adyen-kyc-source-of-funds-upload-modal-content-field-radio-group";
const sourceOfFundsUploadModalContentRequirementsContainer = "adyen-kyc-source-of-funds-upload-modal-content-requirements-container";
const sourceOfFundsUploadListHeading = "adyen-kyc-source-of-funds-upload-list-heading";
const sourceOfFundsModal = "adyen-kyc-source-of-funds-modal";
const styles = {
  sourceOfFunds,
  sourceOfFundsWrapperLoading,
  sourceOfFundsWrapperHeading,
  sourceOfFundsWrapperDescription,
  sourceOfFundsGettingStarted,
  sourceOfFundsGettingStartedError,
  sourceOfFundsGettingStartedErrorActions,
  sourceOfFundsGettingStartedCards,
  sourceOfFundsGettingStartedCardsCardHeader,
  sourceOfFundsGettingStartedCardsCardBody,
  sourceOfFundsGettingStartedActions,
  sourceOfFundsAdditionalDataForm,
  sourceOfFundsThirdPartyFundingFinancierGroup,
  sourceOfFundsThirdPartyFundingNameAvatarGroup,
  sourceOfFundsThirdPartyFundingNameAddressGroup,
  sourceOfFundsSofFinancierFormError,
  sourceOfFundsSofFinancierFormNameGroup,
  sourceOfFundsFinancierFooter,
  sourceOfFundsGridContainer,
  sourceOfFundsUploadModalContentField,
  sourceOfFundsUploadModalContentFieldRadioGroup,
  sourceOfFundsUploadModalContentRequirementsContainer,
  sourceOfFundsUploadListHeading,
  sourceOfFundsModal
};
function AdditionalDataForAssetSale(props) {
  const [isFocused, setIsFocused] = useState(false);
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor, handleAmountChange } = props;
  const { t: commonT } = useTranslation("common");
  const handleOnAmountBlur = () => {
    setIsFocused(false);
    handleAmountChange("amount");
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsGridContainer, children: [
      /* @__PURE__ */ jsx(
        Field,
        {
          el: "fieldset",
          name: "amount",
          label: formUtils.getLabel("amount", "saleAmount"),
          errorMessage: formUtils.getErrorMessage("amount", errors, fieldProblems),
          children: (childProps) => /* @__PURE__ */ jsxs(
            InputGroup,
            {
              ...childProps,
              id: "currencyGroup",
              isFocused,
              isInvalid: Boolean(!valid.amount && errors.amount),
              children: [
                /* @__PURE__ */ jsx(
                  Select,
                  {
                    name: "currency",
                    "aria-label": commonT(($) => $["currency"]),
                    isMulti: false,
                    items: allowedCurrencies,
                    selected: data.amount?.currency,
                    placeholder: commonT(($) => $["select"]),
                    onChange: handleAmountChange("currency"),
                    minimal: true
                  }
                ),
                /* @__PURE__ */ jsx(
                  InputText,
                  {
                    ...childProps,
                    name: "amount",
                    value: data.amount?.value,
                    readonly: formUtils.isReadOnly("amount"),
                    onInput: handleAmountChange("amount"),
                    onBlur: handleOnAmountBlur,
                    "aria-required": true,
                    "aria-invalid": !valid.amount,
                    isValid: valid.amount,
                    onFocusHandler: () => setIsFocused(true)
                  }
                )
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "dateOfSourceEvent",
          label: formUtils.getLabel("dateOfSourceEvent", "dateOfSale"),
          errorMessage: formUtils.getErrorMessage("dateOfSourceEvent", errors, fieldProblems),
          isValid: valid.dateOfSourceEvent,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputDate,
            {
              ...childProps,
              name: "dateOfSourceEvent",
              value: data.dateOfSourceEvent,
              onInput: handleChangeFor("dateOfSourceEvent", "input"),
              onBlur: handleChangeFor("dateOfSourceEvent", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.dateOfSourceEvent,
              max: TODAY_DATE
            }
          )
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      Field,
      {
        name: "description",
        label: formUtils.getLabel("description", "propertyDescription"),
        errorMessage: formUtils.getErrorMessage("description", errors, fieldProblems),
        isValid: valid.description,
        children: (childProps) => /* @__PURE__ */ jsx(
          TextArea,
          {
            ...childProps,
            name: "description",
            value: data.description,
            maxLength: SOF_CHARACTERS_LIMIT,
            onInput: handleChangeFor("description"),
            onBlur: handleChangeFor("description"),
            "aria-invalid": !valid.description
          }
        )
      }
    )
  ] });
}
function AdditionalDataForBusiness(props) {
  const [isFocused, setIsFocused] = useState(false);
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor, handleAmountChange } = props;
  const { t: commonT } = useTranslation("common");
  const handleOnAmountBlur = () => {
    setIsFocused(false);
    handleAmountChange("amount");
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "amount",
        label: formUtils.getLabel("amount", "annualTurnover"),
        errorMessage: formUtils.getErrorMessage("amount", errors, fieldProblems),
        helper: commonT(($) => $["useFiguresFromTheMostRecentYearAvailable"]),
        helperPosition: "below",
        children: (childProps) => /* @__PURE__ */ jsxs(
          InputGroup,
          {
            ...childProps,
            id: "currencyGroup",
            isFocused,
            isInvalid: Boolean(!valid.amount && errors.amount),
            children: [
              /* @__PURE__ */ jsx(
                Select,
                {
                  name: "currency",
                  "aria-label": commonT(($) => $["currency"]),
                  isMulti: false,
                  items: allowedCurrencies,
                  selected: data.amount?.currency,
                  placeholder: commonT(($) => $["select"]),
                  onChange: handleAmountChange("currency"),
                  minimal: true
                }
              ),
              /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  name: "amount",
                  value: data.amount?.value,
                  readonly: formUtils.isReadOnly("amount"),
                  onInput: handleAmountChange("amount"),
                  onBlur: handleOnAmountBlur,
                  "aria-required": true,
                  "aria-invalid": !valid.amount,
                  isValid: valid.amount,
                  onFocusHandler: () => setIsFocused(true)
                }
              )
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      Field,
      {
        name: "description",
        label: formUtils.getLabel("description", "businessDescription"),
        errorMessage: formUtils.getErrorMessage("description", errors, fieldProblems),
        isValid: valid.description,
        children: (childProps) => /* @__PURE__ */ jsx(
          TextArea,
          {
            ...childProps,
            name: "description",
            value: data.description,
            maxLength: SOF_CHARACTERS_LIMIT,
            onInput: handleChangeFor("description"),
            onBlur: handleChangeFor("description"),
            "aria-invalid": !valid.description
          }
        )
      }
    )
  ] });
}
function AdditionalDataForCryptocurrency(props) {
  const { t: sofT } = useTranslation("sof");
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor } = props;
  return /* @__PURE__ */ jsx(
    Field,
    {
      name: "cryptocurrencyExchange",
      label: formUtils.getLabel("cryptocurrencyExchange", "cryptocurrencyExchange"),
      errorMessage: formUtils.getErrorMessage("cryptocurrencyExchange", errors, fieldProblems),
      isValid: valid.cryptocurrencyExchange,
      helper: sofT(($) => $["nameOfTheExchangeWhereTheCryptocurrencyWasHeldPriorToSale"]),
      helperPosition: "below",
      children: (childProps) => /* @__PURE__ */ jsx(
        InputText,
        {
          ...childProps,
          name: "cryptocurrencyExchange",
          value: data.cryptocurrencyExchange,
          readonly: formUtils.isReadOnly("cryptocurrencyExchange"),
          onInput: handleChangeFor("cryptocurrencyExchange", "input"),
          onBlur: handleChangeFor("cryptocurrencyExchange", "blur"),
          "aria-required": true,
          "aria-invalid": !valid.cryptocurrencyExchange,
          isValid: valid.cryptocurrencyExchange
        }
      )
    }
  );
}
const radioItems = [
  {
    id: "individual",
    name: "individual"
  },
  {
    id: "organization",
    name: "organization"
  }
];
function AdditionalDataOriginatorLegalEntity(props) {
  const { t: sofT } = useTranslation("sof");
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor, sourceOfFundsType } = props;
  const isDonations = useMemo(() => sourceOfFundsType === "donations", [sourceOfFundsType]);
  const countryTranslationKey = isDonations && data?.originatorType === "individual" ? "donorsCountryOfResidence" : data?.originatorType === "organization" ? "organizationsCountryOfOperation" : "decedentsCountryOfDeath";
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "originatorType",
        className: styles.sourceOfFundsUploadModalContentField,
        label: sofT(
          ($) => $[isDonations ? "whereDidThisGiftOrDonationComeFrom" : "whereDidThisInheritanceComeFrom"]
        ),
        errorMessage: formUtils.getErrorMessage("originatorType", errors, fieldProblems),
        isValid: valid.originatorType,
        children: (childProps) => /* @__PURE__ */ jsx(
          RadioGroup,
          {
            ...childProps,
            name: "originatorType",
            className: styles.sourceOfFundsUploadModalContentFieldRadioGroup,
            items: radioItems,
            value: data.originatorType,
            disabled: false,
            onChange: handleChangeFor("originatorType", "input"),
            "aria-required": true
          }
        )
      }
    ),
    data?.originatorType === "organization" && /* @__PURE__ */ jsx(
      Field,
      {
        name: "legalName",
        label: formUtils.getLabel("legalName", "organizationsLegalName"),
        errorMessage: formUtils.getErrorMessage("legalName", errors, fieldProblems),
        isValid: valid.legalName,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputText,
          {
            ...childProps,
            name: "legalName",
            value: data.legalName,
            readonly: formUtils.isReadOnly("legalName"),
            onInput: handleChangeFor("legalName", "input"),
            onBlur: handleChangeFor("legalName", "blur"),
            "aria-required": true,
            "aria-invalid": !valid.legalName,
            isValid: valid.legalName
          }
        )
      }
    ),
    data?.originatorType === "individual" && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "firstName",
          label: formUtils.getLabel(
            "firstName",
            isDonations ? "donorsLegalFirstName" : "decedentsLegalFirstName"
          ),
          errorMessage: formUtils.getErrorMessage("firstName", errors, fieldProblems),
          isValid: valid.firstName,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: "firstName",
              value: data.firstName,
              readonly: formUtils.isReadOnly("firstName"),
              onInput: handleChangeFor("firstName", "input"),
              onBlur: handleChangeFor("firstName", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.firstName,
              isValid: valid.firstName
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "lastName",
          label: formUtils.getLabel(
            "lastName",
            isDonations ? "donorsLegalLastName" : "decedentsLegalLastName"
          ),
          errorMessage: formUtils.getErrorMessage("lastName", errors, fieldProblems),
          isValid: valid.lastName,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: "lastName",
              value: data.lastName,
              readonly: formUtils.isReadOnly("lastName"),
              onInput: handleChangeFor("lastName", "input"),
              onBlur: handleChangeFor("lastName", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.lastName,
              isValid: valid.lastName
            }
          )
        }
      )
    ] }),
    data?.originatorType && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "relationship",
          label: formUtils.getLabel(
            "relationship",
            isDonations && data?.originatorType === "individual" ? "yourRelationshipToDonor" : data?.originatorType === "organization" ? "yourRelationshipToOrganization" : "yourRelationshipToDecedent"
          ),
          errorMessage: formUtils.getErrorMessage("relationship", errors, fieldProblems),
          isValid: valid.relationship,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: "relationship",
              value: data.relationship,
              readonly: formUtils.isReadOnly("relationship"),
              onInput: handleChangeFor("relationship", "input"),
              onBlur: handleChangeFor("relationship", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.relationship,
              isValid: valid.relationship
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        CountryField,
        {
          data: { country: data.country },
          valid: { country: valid.country },
          errors: {
            country: formUtils.getErrorMessage("country", errors, fieldProblems)
          },
          labels: {
            country: sofT(($) => $[countryTranslationKey])
          },
          readonly: formUtils.isReadOnly("country"),
          handleChangeFor
        }
      )
    ] })
  ] });
}
function AdditionalDataForDonation(props) {
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor } = props;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      AdditionalDataOriginatorLegalEntity,
      {
        formUtils,
        handleChangeFor,
        data,
        errors,
        valid,
        fieldProblems,
        sourceOfFundsType: "donations"
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsGridContainer, children: [
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "purpose",
          label: formUtils.getLabel("purpose", "reason"),
          errorMessage: formUtils.getErrorMessage("purpose", errors, fieldProblems),
          isValid: valid.purpose,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: "purpose",
              value: data.purpose,
              readonly: formUtils.isReadOnly("purpose"),
              onInput: handleChangeFor("purpose", "input"),
              onBlur: handleChangeFor("purpose", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.purpose,
              isValid: valid.purpose
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "dateOfFundsReceived",
          label: formUtils.getLabel("dateOfFundsReceived", "date"),
          errorMessage: formUtils.getErrorMessage("dateOfFundsReceived", errors, fieldProblems),
          isValid: valid.dateOfFundsReceived,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputDate,
            {
              ...childProps,
              name: "dateOfFundsReceived",
              value: formatDateForInput(data.dateOfFundsReceived),
              onInput: handleChangeFor("dateOfFundsReceived", "input"),
              onBlur: handleChangeFor("dateOfFundsReceived", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.dateOfFundsReceived,
              max: TODAY_DATE
            }
          )
        }
      )
    ] })
  ] });
}
function AdditionalDataForGambling(props) {
  const { t: commonT } = useTranslation("common");
  const [focusedInput, setFocusedInput] = useState();
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor, handleAmountChange } = props;
  const handleOnAmountBlur = () => {
    setFocusedInput(void 0);
    handleAmountChange("amount");
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      Field,
      {
        el: "fieldset",
        name: "amount",
        label: formUtils.getLabel("amount", "totalAmountWon"),
        errorMessage: formUtils.getErrorMessage("amount", errors, fieldProblems),
        children: (childProps) => /* @__PURE__ */ jsxs(
          InputGroup,
          {
            ...childProps,
            id: "currencyGroup",
            isFocused: focusedInput === "amount",
            isInvalid: Boolean(!valid.amount && errors.amount),
            children: [
              /* @__PURE__ */ jsx(
                Select,
                {
                  name: "currency",
                  "aria-label": commonT(($) => $["currency"]),
                  isMulti: false,
                  items: allowedCurrencies,
                  selected: data.amount?.currency,
                  placeholder: commonT(($) => $["select"]),
                  onChange: handleAmountChange("currency"),
                  minimal: true
                }
              ),
              /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  name: "amount",
                  value: data.amount?.value,
                  readonly: formUtils.isReadOnly("amount"),
                  onInput: handleAmountChange("amount"),
                  onBlur: handleOnAmountBlur,
                  "aria-required": true,
                  "aria-invalid": !valid.amount,
                  isValid: valid.amount,
                  onFocusHandler: () => setFocusedInput("amount")
                }
              )
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      Field,
      {
        name: "dateOfSourceEvent",
        label: formUtils.getLabel("dateOfSourceEvent", "dateOfWinning"),
        errorMessage: formUtils.getErrorMessage("dateOfSourceEvent", errors, fieldProblems),
        isValid: valid.dateOfSourceEvent,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputDate,
          {
            ...childProps,
            name: "dateOfSourceEvent",
            value: formatDateForInput(data.dateOfSourceEvent),
            onInput: handleChangeFor("dateOfSourceEvent", "input"),
            onBlur: handleChangeFor("dateOfSourceEvent", "blur"),
            "aria-required": true,
            "aria-invalid": !valid.dateOfSourceEvent,
            max: TODAY_DATE
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      Field,
      {
        name: "website",
        label: formUtils.getLabel("website", "gamblingEstablishmentWebsite"),
        errorMessage: formUtils.getErrorMessage("website", errors, fieldProblems),
        children: (childProps) => /* @__PURE__ */ jsx(
          InputGroup,
          {
            ...childProps,
            id: "websiteGroup",
            isFocused: focusedInput === "website",
            isInvalid: Boolean(!valid.website && errors.website),
            children: /* @__PURE__ */ jsx(
              InputText,
              {
                ...childProps,
                placeholder: "https://",
                name: "website",
                value: data.website,
                readonly: formUtils.isReadOnly("website"),
                onInput: handleChangeFor("website", "input"),
                onBlur: handleChangeFor("website", "blur"),
                "aria-required": true,
                "aria-invalid": !valid.website,
                isValid: valid.website,
                onFocusHandler: () => setFocusedInput("website")
              }
            )
          }
        )
      }
    )
  ] });
}
function AdditionalDataForInheritance(props) {
  const [isFocused, setIsFocused] = useState(false);
  const { formUtils, data, errors, valid, fieldProblems, handleChangeFor, handleAmountChange } = props;
  const { t: commonT } = useTranslation("common");
  const handleOnAmountBlur = () => {
    setIsFocused(false);
    handleAmountChange("amount");
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      AdditionalDataOriginatorLegalEntity,
      {
        formUtils,
        handleChangeFor,
        data,
        errors,
        valid,
        fieldProblems,
        sourceOfFundsType: "inheritance"
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsGridContainer, children: [
      /* @__PURE__ */ jsx(
        Field,
        {
          el: "fieldset",
          name: "amount",
          label: formUtils.getLabel("amount", "inheritanceAmount"),
          errorMessage: formUtils.getErrorMessage("amount", errors, fieldProblems),
          children: (childProps) => /* @__PURE__ */ jsxs(
            InputGroup,
            {
              ...childProps,
              id: "currencyGroup",
              isFocused,
              isInvalid: Boolean(!valid.amount && errors.amount),
              children: [
                /* @__PURE__ */ jsx(
                  Select,
                  {
                    name: "currency",
                    "aria-label": commonT(($) => $["currency"]),
                    isMulti: false,
                    items: allowedCurrencies ?? [],
                    selected: data.amount?.currency,
                    placeholder: commonT(($) => $["select"]),
                    onChange: handleAmountChange("currency"),
                    minimal: true
                  }
                ),
                /* @__PURE__ */ jsx(
                  InputText,
                  {
                    ...childProps,
                    name: "amount",
                    value: data.amount?.value,
                    readonly: formUtils.isReadOnly("amount"),
                    onInput: handleAmountChange("amount"),
                    onBlur: handleOnAmountBlur,
                    "aria-required": true,
                    "aria-invalid": !valid.amount,
                    isValid: valid.amount,
                    onFocusHandler: () => setIsFocused(true)
                  }
                )
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsx(
        Field,
        {
          name: "dateOfFundsReceived",
          label: formUtils.getLabel("dateOfFundsReceived", "inheritanceReceivedOn"),
          errorMessage: formUtils.getErrorMessage("dateOfFundsReceived", errors, fieldProblems),
          isValid: valid.dateOfFundsReceived,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputDate,
            {
              ...childProps,
              name: "dateOfFundsReceived",
              value: formatDateForInput(data.dateOfFundsReceived),
              onInput: handleChangeFor("dateOfFundsReceived", "input"),
              onBlur: handleChangeFor("dateOfFundsReceived", "blur"),
              "aria-required": true,
              "aria-invalid": !valid.dateOfFundsReceived,
              max: TODAY_DATE
            }
          )
        }
      )
    ] })
  ] });
}
const SOFFinancierModal = (props) => {
  const { t: sofT } = useTranslation("sof");
  const { t: commonT } = useTranslation("common");
  const { financier, handleModalClose, indexNumber, handleFinancierUpdate } = props;
  const [formData, setFormData] = useState(financier);
  const [formErrors, setFormErrors] = useState({});
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const handleInputUpdate = (key, e) => {
    const inputEl = e.target;
    setErrorMessage("");
    const value = inputEl?.value;
    let inputData = {
      [key]: value
    };
    if (["amount", "currency"].includes(key)) {
      const amountValue = {
        currency: key === "currency" ? value : formData?.amount?.currency,
        value: key === "currency" ? formData?.amount?.value : value
      };
      inputData = { amount: amountValue };
    }
    const data = {
      ...formData,
      ...inputData
    };
    setFormData(data);
    const errors = getInputErrors({ formErrors, data, key, value });
    setFormErrors(errors);
  };
  const handleOnAmountBlur = () => {
    setIsFocused(false);
    const errors = getInputErrors({
      formErrors,
      data: formData,
      key: "amount",
      value: formData?.amount?.value
    });
    setFormErrors(errors);
  };
  const allFieldsFilled = (data) => {
    return data?.firstName && data?.lastName && data?.location && data?.amount?.currency && !Number.isNaN(Number(data?.amount?.value));
  };
  const handleFinancierSave = () => {
    if (formData && allFieldsFilled(formData)) {
      handleFinancierUpdate({ formData, indexNumber });
      handleModalClose();
    } else {
      const fields = [
        "firstName",
        "lastName",
        "location",
        "amount"
      ];
      const errors = fields.reduce((acc, key) => {
        const value = key === "amount" ? formData?.amount?.value : formData?.[key];
        return {
          ...acc,
          ...getInputErrors({
            formErrors: void 0,
            data: formData,
            key,
            value
          })
        };
      }, {});
      setFormErrors(errors);
      setErrorMessage(sofT(($) => $["pleaseFillInAllFields"]));
    }
  };
  const handleFinancierDelete = async () => {
    handleFinancierUpdate({ indexNumber });
    handleModalClose();
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Modal, { onClose: handleModalClose, ariaLabel: sofT(($) => $["investorDetails"]), inset: true, children: /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsModal, children: [
      /* @__PURE__ */ jsx(
        Typography,
        {
          variant: "title-l",
          el: "h3",
          className: styles.sourceOfFundsGettingStartedHelpHeader,
          children: sofT(($) => $["investorDetails"])
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsSofFinancierForm, children: [
        errorMessage && /* @__PURE__ */ jsx(
          Alert,
          {
            title: sofT(($) => $["errorSubmittingData"]),
            variant: "error",
            className: styles.sourceOfFundsSofFinancierFormError,
            children: errorMessage
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsSofFinancierFormNameGroup, children: [
          /* @__PURE__ */ jsx(
            Field,
            {
              name: "firstName",
              label: commonT(($) => $["firstName"]),
              errorMessage: formErrors.firstName,
              isValid: !formErrors.firstName,
              children: (childProps) => /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  name: "firstName",
                  value: formData?.firstName,
                  onInput: (e) => handleInputUpdate("firstName", e),
                  onBlur: (e) => handleInputUpdate("firstName", e),
                  "aria-required": true,
                  "aria-invalid": Boolean(formErrors.firstName),
                  isValid: !formErrors.firstName
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            Field,
            {
              name: "lastName",
              label: commonT(($) => $["lastName"]),
              errorMessage: formErrors.lastName,
              isValid: !formErrors.lastName,
              children: (childProps) => /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  name: "lastName",
                  value: formData?.lastName,
                  onInput: (e) => handleInputUpdate("lastName", e),
                  onBlur: (e) => handleInputUpdate("lastName", e),
                  "aria-required": true,
                  "aria-invalid": Boolean(formErrors.lastName),
                  isValid: !formErrors.lastName
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          Field,
          {
            name: "location",
            label: sofT(($) => $["investorLocation"]),
            errorMessage: formErrors.location,
            isValid: !formErrors.location,
            helperPosition: "below",
            showErrorIconBottom: true,
            helper: sofT(($) => $["theCityAndCountryRegion"]),
            children: (childProps) => /* @__PURE__ */ jsx(
              InputText,
              {
                ...childProps,
                name: "location",
                value: formData?.location,
                onInput: (e) => handleInputUpdate("location", e),
                onBlur: (e) => handleInputUpdate("location", e),
                "aria-required": true,
                "aria-invalid": Boolean(formErrors.location),
                isValid: !formErrors.location
              }
            )
          }
        ),
        /* @__PURE__ */ jsx(
          Field,
          {
            el: "fieldset",
            name: "amount",
            label: sofT(($) => $["investmentAmount"]),
            errorMessage: formErrors.amount,
            isValid: !formErrors.amount,
            children: (childProps) => /* @__PURE__ */ jsxs(InputGroup, { ...childProps, id: "currencyGroup", isFocused, children: [
              /* @__PURE__ */ jsx(
                Select,
                {
                  minimal: true,
                  name: "currency",
                  "aria-label": commonT(($) => $["currency"]),
                  isMulti: false,
                  items: allowedCurrencies,
                  selected: formData?.amount?.currency,
                  placeholder: commonT(($) => $["select"]),
                  onChange: (e) => handleInputUpdate("currency", e)
                }
              ),
              /* @__PURE__ */ jsx(
                InputText,
                {
                  ...childProps,
                  name: "amount",
                  value: formData?.amount?.value,
                  onInput: (e) => handleInputUpdate("amount", e),
                  onBlur: handleOnAmountBlur,
                  "aria-required": true,
                  onFocusHandler: () => setIsFocused(true)
                }
              )
            ] })
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsFinancierFooter, children: [
        /* @__PURE__ */ jsx(Button, { onClick: handleFinancierSave, children: commonT(($) => $["save"]) }),
        Number.isFinite(indexNumber) && /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: () => setConfirmOpen(true), children: sofT(($) => $["deleteInvestorDetails"]) })
      ] })
    ] }) }),
    confirmOpen && /* @__PURE__ */ jsx(
      Confirm,
      {
        title: sofT(($) => $["areYouSureYouWantToDeleteThisInvestorDetails"]),
        confirmText: commonT(($) => $["delete"]),
        onConfirm: handleFinancierDelete,
        onCancel: () => setConfirmOpen(false),
        critical: true
      }
    )
  ] });
};
function AdditionalDataForThirdParty(props) {
  const [showFinancierModal, setShowFinancierModal] = useState(false);
  const [activeFinancier, setActiveFinancier] = useState();
  const [activeIndex, setActiveIndex] = useState();
  const { data, fieldProblems, errors, handleChangeFor, formUtils, valid } = props;
  const { t: sofT } = useTranslation("sof");
  const { i18n } = useI18nContext();
  const handleToggleFinancierModal = () => {
    setActiveFinancier(void 0);
    setActiveIndex(void 0);
    setShowFinancierModal(!showFinancierModal);
  };
  const handleShowUpdateFinancierModal = (index) => {
    if (!data.financiers) {
      return;
    }
    const financier = data.financiers[index];
    setActiveFinancier(financier);
    setActiveIndex(index);
    setShowFinancierModal(true);
  };
  const handleFinancierUpdate = ({
    formData,
    indexNumber
  }) => {
    const existingFinanciers = data.financiers || [];
    let newFinanciers = [];
    if (!formData) {
      if (indexNumber !== void 0) {
        newFinanciers = existingFinanciers.filter((_, index) => index !== indexNumber);
      }
    } else {
      newFinanciers = [...existingFinanciers, formData];
      if (Number.isFinite(indexNumber)) {
        newFinanciers = existingFinanciers.map(
          (existingFinancier, i) => i === indexNumber ? formData : existingFinancier
        );
      }
    }
    const financierEvent = {
      target: {
        name: "financiers",
        value: newFinanciers
      }
    };
    handleChangeFor("financiers")(financierEvent);
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    errors.financiers && !valid.financiers && /* @__PURE__ */ jsx(
      Alert,
      {
        title: i18n.get(
          formUtils.getErrorMessage("financiers", errors, fieldProblems)
        ),
        variant: "error",
        className: styles.sourceOfFundsSofFinancierFormError,
        children: sofT(($) => $["addAtLeastOneInvestor"])
      }
    ),
    data.financiers?.map((financier, index) => /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        onClick: () => handleShowUpdateFinancierModal(index),
        className: styles.sourceOfFundsThirdPartyFundingFinancierGroup,
        children: [
          /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAvatarGroup, children: [
            /* @__PURE__ */ jsx(Avatar, { iconName: "user", circle: true }),
            /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAddressGroup, children: [
              /* @__PURE__ */ jsxs(Typography, { el: "div", variant: "body-strongest", children: [
                financier.firstName,
                " ",
                financier.lastName
              ] }),
              /* @__PURE__ */ jsx(Typography, { el: "div", variant: "caption", children: financier.location })
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { children: financier.amount?.currency && financier.amount?.value ? formatAmountWithCurrency(
            financier.amount.value,
            financier.amount?.currency
          ) : "" })
        ]
      },
      index
    )),
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        className: styles.sourceOfFundsThirdPartyFundingFinancierGroup,
        onClick: handleToggleFinancierModal,
        children: /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAvatarGroup, children: [
          /* @__PURE__ */ jsx(Avatar, { iconName: "plus", variant: "tertiary", circle: true }),
          /* @__PURE__ */ jsx(Typography, { el: "div", variant: "body-strongest", children: sofT(($) => $["addInvestor"]) })
        ] })
      }
    ),
    showFinancierModal && /* @__PURE__ */ jsx(
      SOFFinancierModal,
      {
        financier: activeFinancier,
        indexNumber: activeIndex,
        handleModalClose: handleToggleFinancierModal,
        handleFinancierUpdate
      }
    )
  ] });
}
function SourceOfFundsAdditionalData(props) {
  const { t } = useTranslation("common");
  const { form } = useFormContext();
  const {
    handleChangeFor: multiFormHandleChangeFor,
    data: { additionalData: data, sourceOfFundsType },
    errors: { additionalData: errors },
    valid: { additionalData: valid },
    fieldProblems: { additionalData: fieldProblems }
  } = form;
  const handleChangeFor = useMemo(
    () => (key, mode) => multiFormHandleChangeFor(key, "additionalData", mode),
    [multiFormHandleChangeFor]
  );
  const handleAmountChange = (key) => (e) => {
    const rawValue = e.target.value;
    const updatedAmount = {
      ...data?.amount,
      ...key === "currency" ? { currency: rawValue } : { value: rawValue === "" ? void 0 : Number(rawValue) }
    };
    handleChangeFor("amount")({ target: { name: "amount", value: updatedAmount } });
  };
  const formUtils = createFormUtils(props, t);
  const additionalDataProps = {
    formUtils,
    handleChangeFor,
    data,
    errors,
    valid,
    fieldProblems,
    handleAmountChange
  };
  const renderSubForms = () => {
    switch (sourceOfFundsType?.type) {
      case "gamblingWinnings":
        return /* @__PURE__ */ jsx(AdditionalDataForGambling, { ...additionalDataProps });
      case "cryptocurrencyIncome":
        return /* @__PURE__ */ jsx(AdditionalDataForCryptocurrency, { ...additionalDataProps });
      case "business":
        return /* @__PURE__ */ jsx(AdditionalDataForBusiness, { ...additionalDataProps });
      case "assetSale":
        return /* @__PURE__ */ jsx(AdditionalDataForAssetSale, { ...additionalDataProps });
      case "thirdPartyFunding":
        return /* @__PURE__ */ jsx(AdditionalDataForThirdParty, { ...additionalDataProps });
      case "inheritance":
        return /* @__PURE__ */ jsx(AdditionalDataForInheritance, { ...additionalDataProps });
      case "donations":
        return /* @__PURE__ */ jsx(AdditionalDataForDonation, { ...additionalDataProps });
      default:
        return null;
    }
  };
  return /* @__PURE__ */ jsxs("form", { className: styles.sourceOfFundsAdditionalDataForm, children: [
    /* @__PURE__ */ jsx(
      ErrorPanel,
      {
        verificationErrors: props?.formVerificationErrors,
        validationErrors: props?.fieldValidationErrors,
        formUtils,
        id: "ariaErrorField"
      }
    ),
    renderSubForms()
  ] });
}
function SourceOfFundsType(props) {
  const { t } = useTranslation(["common", "sof"]);
  const { i18n } = useI18nContext();
  const {
    data: formData,
    categories,
    errors: formErrors,
    fieldValidationErrors: formFieldProblems
  } = props;
  const { form } = useFormContext();
  const { handleChangeFor } = form;
  const handleFieldChange = (fieldName, mode) => handleChangeFor(fieldName, "sourceOfFundsType", mode);
  const formUtils = createFormUtils(props, t);
  const categoryItems = [
    {
      value: "adyen",
      label: t(($) => $["transactionsOnThisPlatform"], { ns: "sof" }),
      icon: getIconById("adyen")
    },
    ...categories?.map((item) => ({
      value: item.id,
      label: t(($) => $[sofCategoryItemMapper[item.name]], { ns: "sof" }),
      icon: getIconById(item.id)
    })) ?? []
  ];
  const errorMessage = formUtils.getErrorMessage("type", formErrors, formFieldProblems);
  return /* @__PURE__ */ jsx(Field, { el: "fieldset", name: "type", children: () => /* @__PURE__ */ jsx(
    TileGroup,
    {
      name: "type",
      tiles: categoryItems,
      errorMessage: typeof errorMessage !== "boolean" ? i18n.get(errorMessage) : errorMessage,
      selected: formData?.type ? formData.type : [],
      onChange: handleFieldChange("type", "input")
    }
  ) });
}
function getIconById(id) {
  switch (id) {
    case "adyen":
      return "store";
    case "business":
      return "revenue-accelerate";
    case "assetSale":
      return "house";
    case "dividendIncome":
      return "graph-up";
    case "thirdPartyFunding":
      return "graph";
    case "employment":
      return "headquarter";
    case "donations":
      return "gift";
    case "inheritance":
      return "certificate";
    case "financialAid":
      return "capital";
    case "rentalIncome":
      return "house";
    case "royaltyIncome":
      return "cash-stack";
    case "pensionIncome":
      return "bank";
    case "insuranceSettlement":
      return "funds-in";
    case "cryptocurrencyIncome":
      return "coins";
    case "loans":
      return "capital";
    case "gamblingWinnings":
      return "cash-stack";
    default:
      return "contract";
  }
}
function SourceOfFunds(props) {
  const { activeForm, activeBusinessLine, sourceOfFundsType } = props;
  const { form } = useFormContext();
  const { data: formData, errors, valid, fieldProblems: fieldValidationErrors } = form;
  const { data: sourceOfFundsTypesData, isLoading } = useSourceOfFundsTypes();
  const { t: sofT } = useTranslation("sof");
  const pageHeadings = useMemo(
    () => getPageHeadings(sourceOfFundsType ?? "adyen"),
    [sourceOfFundsType]
  );
  return isLoading || !activeBusinessLine ? /* @__PURE__ */ jsx("div", { className: styles.sourceOfFundsWrapperLoading, children: /* @__PURE__ */ jsx(Loader, {}) }) : /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-form-wrapper", children: [
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsWrapperHeading, children: [
      /* @__PURE__ */ jsx(Typography, { el: "h1", variant: "title-l", children: activeForm?.formId === "additionalData" ? sofT(($) => $[pageHeadings.heading]) : sofT(($) => $["selectASourceOfFunding"], {
        type: getServiceTranslationSelectTitle(
          sofT,
          activeBusinessLine?.service || ""
        ).toLowerCase()
      }) }),
      /* @__PURE__ */ jsxs(Typography, { className: styles.sourceOfFundsWrapperDescription, children: [
        activeForm?.formId === "additionalData" && pageHeadings.description && sofT(($) => $[pageHeadings.description]),
        sourceOfFundsTypesData?.length === 0 && sofT(($) => $["noCategoriesAvailable"])
      ] })
    ] }),
    sofErrorMessage.value && /* @__PURE__ */ jsxs(
      Typography,
      {
        variant: "caption",
        color: "critical",
        "aria-live": "polite",
        className: "adyen-kyc-u-justify-content-center adyen-kyc-u-display-flex",
        children: [
          /* @__PURE__ */ jsx(Icon, { name: "field-error", className: "adyen-kyc-u-margin-right-2" }),
          /* @__PURE__ */ jsx("span", { children: sofErrorMessage.value })
        ]
      }
    ),
    activeForm?.formId === "sourceOfFundsType" && /* @__PURE__ */ jsx(
      SourceOfFundsType,
      {
        categories: sourceOfFundsTypesData,
        data: formData?.sourceOfFundsType,
        errors: errors?.sourceOfFundsType,
        valid: valid?.sourceOfFundsType,
        fieldValidationErrors: fieldValidationErrors?.sourceOfFundsType
      }
    ),
    activeForm?.formId === "additionalData" && /* @__PURE__ */ jsx(
      SourceOfFundsAdditionalData,
      {
        fieldValidationErrors: fieldValidationErrors?.additionalData
      }
    ),
    activeForm?.formId === "companySourceOfFunds" && /* @__PURE__ */ jsx("div", { children: sofT(($) => $["uploadADocument"]) })
  ] });
}
function SourceOfFundsGettingStartedCard(props) {
  const { id, title, onClick, isEdit, meta } = props;
  const { t: commonT } = useTranslation("common");
  return /* @__PURE__ */ jsxs(Card, { variant: "secondary", children: [
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsGettingStartedCardsCardHeader, children: [
      /* @__PURE__ */ jsx(Typography, { el: "h3", variant: "title", children: title }),
      isEdit ? /* @__PURE__ */ jsx(IconButton, { ariaLabel: "edit", icon: "edit", onClick, variant: "tertiary" }) : /* @__PURE__ */ jsx(
        Button,
        {
          variant: "primary",
          testId: "source-of-funds-getting-card-secondary-button",
          onClick,
          children: commonT(($) => $["start"])
        }
      )
    ] }),
    isEdit && meta?.length && /* @__PURE__ */ jsx("div", { className: styles.sourceOfFundsGettingStartedCardsCardBody, children: /* @__PURE__ */ jsx(
      StructuredList,
      {
        className: styles.sourceOfFundsGettingStartedCardsCardDescription,
        items: meta
      }
    ) })
  ] }, id);
}
const digitalWallet = lazy(() => import("./digital-wallet-Bx5YM1LY.js"));
const SourceOfFundsGettingStarted = ({
  handleGettingStartedClick,
  handleCancelClick,
  handleSourceOfFundsClick,
  businessLines,
  handleNavigateToUploadPage,
  problems,
  legalEntity,
  isSoFDocumentMissing
}) => {
  const { t: sofT } = useTranslation("sof");
  const { t: commonT } = useTranslation("common");
  const { i18n } = useI18nContext();
  const hasSourceOfFunds = businessLines?.some(
    (businessLine) => !isEmpty(businessLine.sourceOfFunds)
  );
  const { data: normalizedTasks } = useTaskStatus({
    refetchInterval: TASK_STATUS_POLLING_INTERVAL_MS
  });
  const sofDocuments = useMemo(
    () => legalEntity?.documentDetails?.filter((doc) => doc.type === "proofOfFundingOrWealthSource") ?? [],
    [legalEntity]
  );
  const mapBusinessLines = useCallback(
    (lines) => {
      const completedBusinessLines = businessLines.every((line) => line?.sourceOfFunds?.type);
      const cards = lines.map((line) => {
        const SoF = mapSourceOfFundToSourceOfFundsSchema(line);
        return {
          title: getServiceTranslation(sofT, line.service || ""),
          type: line?.sourceOfFunds?.type,
          isEdit: !!line?.sourceOfFunds?.type || !!line?.sourceOfFunds?.adyenProcessedFunds,
          onClick: () => handleSourceOfFundsClick(SoF, line),
          meta: [
            {
              term: sofT(($) => $["sourceOfFunds"]),
              details: getSofCardDetails(sofT, line?.sourceOfFunds)
            },
            ...getGettingStartedCardDetails(
              getAdditionalDataSchemaKeys(
                line?.sourceOfFunds?.type || "adyen",
                line?.sourceOfFunds?.originatorType
              ),
              sofT,
              line?.sourceOfFunds
            )
          ]
        };
      }).sort((a) => a?.type ? 1 : -1);
      const uploadCard = {
        title: getServiceTranslation(sofT),
        type: "",
        isEdit: !!sofDocuments?.length,
        onClick: handleNavigateToUploadPage,
        meta: sofDocuments?.length ? sofDocuments.map((doc) => ({
          term: sofT(($) => $["fileName"]),
          details: [
            doc?.fileName,
            /* @__PURE__ */ jsx(Typography, { color: "secondary", children: parseSOFDocumentDescription(sofT, doc?.description) || "" }, "docDescription")
          ]
        })) : []
      };
      if (completedBusinessLines && (isSoFDocumentMissing || sofDocuments?.length)) {
        if (uploadCard.meta?.length) {
          cards.push(uploadCard);
        } else {
          cards.unshift(uploadCard);
        }
      }
      return cards.map((item, index) => {
        return /* @__PURE__ */ jsx(
          SourceOfFundsGettingStartedCard,
          {
            id: index,
            isEdit: !!item.isEdit,
            title: item.title,
            onClick: item.onClick,
            meta: item.meta
          },
          index
        );
      });
    },
    [handleSourceOfFundsClick, i18n, sofDocuments]
  );
  const errorObjects = useMemo(
    () => getRelevantErrors(problems, SOF_INVALID_INPUT_ERROR_CODES),
    [problems]
  );
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: styles.sourceOfFundsGettingStarted,
      "data-testid": "source-of-funds-getting-started",
      children: [
        !hasSourceOfFunds && /* @__PURE__ */ jsx(
          LandingLayout,
          {
            media: /* @__PURE__ */ jsx(Image, { lazyLoadedImage: digitalWallet }),
            title: sofT(($) => $["fundingSourcesForFinancialProducts"]),
            description: sofT(($) => $["inTheNextStepWellCollectInformation"]),
            actions: /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  fullWidth: true,
                  testId: "source-of-funds-getting-primary-button",
                  onClick: handleGettingStartedClick,
                  children: sofT(($) => $["getStarted"])
                }
              ),
              handleCancelClick && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "tertiary",
                  fullWidth: true,
                  testId: "source-of-funds-getting-cancel-button",
                  onClick: handleCancelClick,
                  children: commonT(($) => $["backToTaskList"])
                }
              )
            ] })
          }
        ),
        hasSourceOfFunds && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Header,
            {
              title: sofT(($) => $["fundingSourcesForFinancialProducts"]),
              description: sofT(($) => $["addAllSourcesOfFundsBeingUsed"]),
              status: normalizedTasks?.SOURCE_OF_FUNDS?.status,
              align: "center"
            }
          ),
          errorObjects && errorObjects.map((errorObj, index) => {
            const uniqueActions = getUniqueRemediationActions(errorObj);
            const errorItems = errorObj.subErrors?.map((subError) => subError.message) || [];
            return /* @__PURE__ */ jsxs(
              Alert,
              {
                title: errorObj.message,
                className: styles.sourceOfFundsGettingStartedError,
                variant: "error",
                children: [
                  errorObj?.subErrors?.length && /* @__PURE__ */ jsx("ul", { children: errorItems.map((item, i) => /* @__PURE__ */ jsx("li", { children: item }, i)) }),
                  uniqueActions.length > 0 && /* @__PURE__ */ jsx("div", { className: styles.sourceOfFundsGettingStartedErrorActions, children: uniqueActions.filter((action) => action.code !== "1_519").map((action, i) => /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "tertiary",
                      testId: `remediate-action-${i}`,
                      onClick: handleNavigateToUploadPage,
                      children: action.message
                    },
                    `action-${i}`
                  )) })
                ]
              },
              `error-${index}`
            );
          }),
          /* @__PURE__ */ jsx("div", { className: styles.sourceOfFundsGettingStartedCards, children: /* @__PURE__ */ jsx(StackLayout, { children: mapBusinessLines(businessLines) }) }),
          handleCancelClick && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "secondary",
              testId: "source-of-funds-getting-return-button",
              onClick: handleCancelClick,
              children: commonT(($) => $["backToTaskList"])
            }
          )
        ] })
      ]
    }
  );
};
const SOFUploadModal = (props) => {
  const { showToast } = useToastContext();
  const logger2 = createLogger();
  const { t: sofT } = useTranslation("sof");
  const { t: commonT } = useTranslation("common");
  const { businessLines, handleModalClose, documentUtils } = props;
  const firstService = businessLines?.length === 1 ? businessLines?.[0]?.service : void 0;
  const [selectedService, setSelectedService] = useState(
    firstService
  );
  const [documentType, setDocumentType] = useState();
  const onRadioChange = (selectedId) => {
    setSelectedService(selectedId);
    setDocumentType(void 0);
  };
  const onDocumentTypeChange = (e) => {
    setDocumentType(e.target.value);
  };
  const serviceRadioItems = useMemo(() => {
    return businessLines.map((businessLine) => ({
      id: businessLine.service,
      name: sofT(($) => $[getServiceTranslationKey(businessLine?.service || "")])
    }));
  }, [businessLines, sofT]);
  const canUpload = useMemo(() => selectedService && documentType, [selectedService, documentType]);
  const selectedBusinessLineId = businessLines?.find((businessLine) => businessLine.service === selectedService)?.id || "";
  const documentLists = useMemo(() => {
    const selectedType = businessLines?.find(
      (businessLine) => businessLine.service === selectedService
    )?.sourceOfFunds?.type;
    if (selectedType) {
      const lists = getDocumentLists(selectedType);
      const items = lists.map((list) => ({
        id: list,
        name: sofT(($) => $[list])
      }));
      return items;
    }
    return [];
  }, [businessLines, sofT, selectedService]);
  const documentRequirements = useMemo(() => {
    return documentType ? getDocumentRequirements[documentType] : [];
  }, [documentType]);
  const onFileUpload = async (files) => {
    if (!canUpload) {
      showToast({ label: sofT(($) => $["unableToUploadDocument"]), variant: "error" });
      return;
    }
    const formattedDocument = await createDocumentRequest({
      entityId: selectedBusinessLineId,
      entityType: "businessLine",
      documentType: "proofOfFundingOrWealthSource",
      page1: files[0],
      description: `$SERVICE_NAME:${selectedService}--TYPE_NAME:${documentType}`
    });
    if (formattedDocument) {
      try {
        await documentUtils.uploadDocuments([formattedDocument], selectedBusinessLineId);
        showToast({
          label: sofT(($) => $["documentUploadedSuccessfully"]),
          variant: "success",
          duration: 1e4
        });
        handleModalClose();
      } catch (e) {
        logger2.log(e);
        showToast({ label: sofT(($) => $["unableToUploadDocument"]), variant: "error" });
      }
    }
  };
  return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
    Modal,
    {
      onClose: handleModalClose,
      ariaLabel: sofT(($) => $["uploadASupportingDocument"]),
      inset: true,
      children: /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsModal, children: [
        /* @__PURE__ */ jsx(Typography, { variant: "title-l", el: "h2", children: sofT(($) => $["uploadASupportingDocument"]) }),
        /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsUploadModalContent, children: [
          businessLines?.length > 1 ? /* @__PURE__ */ jsx(
            Field,
            {
              el: "fieldset",
              name: "service",
              className: styles.sourceOfFundsUploadModalContentField,
              label: sofT(($) => $["whatFinancialProductIsThisFor"]),
              children: (childProps) => /* @__PURE__ */ jsx(
                RadioGroup,
                {
                  ...childProps,
                  name: "service",
                  className: styles.sourceOfFundsUploadModalContentFieldRadioGroup,
                  items: serviceRadioItems,
                  value: selectedService,
                  disabled: false,
                  onChange: onRadioChange,
                  "aria-required": true
                }
              )
            }
          ) : null,
          selectedService && /* @__PURE__ */ jsx(
            Field,
            {
              name: "documentType",
              label: commonT(($) => $["documentType"]),
              "data-testid": "documentType",
              className: styles.sourceOfFundsUploadModalContentField,
              children: (childProps) => /* @__PURE__ */ jsx(
                Select,
                {
                  ...childProps,
                  name: "documentType",
                  placeholder: commonT(($) => $["selectOne"]),
                  selected: documentType,
                  items: documentLists,
                  onChange: onDocumentTypeChange
                }
              )
            }
          ),
          documentRequirements?.length ? /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsUploadModalContentRequirementsContainer, children: [
            /* @__PURE__ */ jsx(Typography, { variant: "body-strongest", el: "div", children: sofT(($) => $["documentShouldShow"]) }),
            /* @__PURE__ */ jsx("ul", { children: documentRequirements?.map((requirement) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Typography, { variant: "body-stronger", el: "div", children: sofT(($) => $[requirement]) }) }, requirement)) })
          ] }) : null,
          canUpload && /* @__PURE__ */ jsx(
            Dropzone,
            {
              disabled: !canUpload,
              onChange: onFileUpload,
              showMinimal: true,
              hidePageCount: true,
              maxSize: 4194304,
              enableTracking: true,
              name: "documentField",
              allowedFileTypes: ["JPG", "JPEG", "PNG", "PDF"]
            }
          )
        ] })
      ] })
    }
  ) });
};
const SourceOfFundsUpload = ({
  businessLines,
  documentUtils,
  legalEntity,
  handleNavigateToSummary
}) => {
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [docToDelete, setDocToDelete] = useState(void 0);
  const { showToast } = useToastContext();
  const logger2 = createLogger();
  const queryClient = useQueryClient();
  const { t: sofT } = useTranslation("sof");
  const { t: commonT } = useTranslation("common");
  const handleModalClose = async () => {
    setShowUploadModal(false);
    await queryClient.invalidateQueries({
      queryKey: ["legalEntity", legalEntity.id]
    });
  };
  const openUploadModal = () => {
    setShowUploadModal(true);
  };
  const documents = useMemo(
    () => legalEntity.documentDetails?.filter((doc) => doc.type === "proofOfFundingOrWealthSource") ?? [],
    [legalEntity]
  );
  const sourceOfFundsCategories = businessLines?.map((line) => line.sourceOfFunds?.type)?.filter(Boolean);
  const getTranslatedCategoryName = (categoryKey) => {
    const translationKey2 = sofCategoryItemMapper[categoryKey];
    if (!categoryKey || !translationKey2) {
      return "";
    }
    return sofT(($) => $[translationKey2]).toLowerCase();
  };
  let translationKey;
  let translationParams;
  if (sourceOfFundsCategories?.length > 1) {
    translationKey = "weNeedProofOfFundingForMultipleCategories";
    translationParams = {
      category1_name: getTranslatedCategoryName(sourceOfFundsCategories[0]),
      category2_name: getTranslatedCategoryName(sourceOfFundsCategories[1])
    };
  } else if (sourceOfFundsCategories?.length === 1) {
    translationKey = "weNeedProofOfFunding";
    translationParams = {
      category_name: getTranslatedCategoryName(sourceOfFundsCategories[0])
    };
  } else {
    translationKey = "weNeedProofOfFundingForNoCategory";
  }
  const handleFileDelete = async (documentId) => {
    if (documentUtils.deleteDocument) {
      try {
        await documentUtils.deleteDocument(documentId, legalEntity.id);
        await queryClient.invalidateQueries({
          queryKey: ["legalEntity", legalEntity.id]
        });
        showToast({
          label: sofT(($) => $["documentDeletedSuccessfully"]),
          variant: "success",
          duration: 1e4
        });
      } catch (e) {
        logger2.log(e);
        showToast({ label: sofT(($) => $["unableToDeleteDocument"]), variant: "error" });
      }
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsUploadList, children: [
    /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsUploadListHeading, children: [
      /* @__PURE__ */ jsx(Typography, { el: "h1", variant: "title-l", children: sofT(($) => $["supportingDocuments"]) }),
      /* @__PURE__ */ jsx(Typography, { className: styles.sourceOfFundsWrapperDescription, children: sofT(($) => $[translationKey], translationParams) })
    ] }),
    documents?.map((document) => /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingFinancierGroup, children: [
      /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAvatarGroup, children: [
        /* @__PURE__ */ jsx(Avatar, { iconName: "document", circle: true }),
        /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAddressGroup, children: [
          /* @__PURE__ */ jsx(Typography, { el: "div", variant: "body-strongest", children: document.fileName }),
          /* @__PURE__ */ jsx(Typography, { el: "div", variant: "caption", children: parseSOFDocumentDescription(sofT, document.description) })
        ] })
      ] }),
      /* @__PURE__ */ jsx(
        IconButton,
        {
          ariaLabel: commonT(($) => $["deleteDocument"]),
          variant: "tertiary",
          icon: "cross",
          onClick: () => setDocToDelete(document),
          testId: "source-of-funds-remove-button"
        }
      )
    ] }, document.id)),
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        className: styles.sourceOfFundsThirdPartyFundingFinancierGroup,
        onClick: openUploadModal,
        "data-testId": "source-of-funds-upload-button",
        children: /* @__PURE__ */ jsxs("div", { className: styles.sourceOfFundsThirdPartyFundingNameAvatarGroup, children: [
          /* @__PURE__ */ jsx(Avatar, { label: sofT(($) => $["addDocument"]), iconName: "plus", circle: true }),
          /* @__PURE__ */ jsx(Typography, { el: "div", variant: "body-strongest", children: sofT(($) => $["addDocument"]) })
        ] })
      }
    ),
    handleNavigateToSummary && /* @__PURE__ */ jsx("div", { className: styles.sourceOfFundsGettingStartedActions, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: handleNavigateToSummary, children: documents?.length > 0 ? commonT(($) => $["finish"]) : commonT(($) => $["cancel"]) }) }),
    !!docToDelete && /* @__PURE__ */ jsx(
      Confirm,
      {
        title: sofT(($) => $["areYouSureYouWantToDeleteThisDocument"], {
          documentName: docToDelete?.fileName || ""
        }),
        confirmText: commonT(($) => $["delete"]),
        onConfirm: () => handleFileDelete(docToDelete?.id),
        onCancel: () => setDocToDelete(void 0),
        critical: true
      }
    ),
    showUploadModal && /* @__PURE__ */ jsx(
      SOFUploadModal,
      {
        documentUtils,
        handleModalClose,
        businessLines
      }
    )
  ] });
};
function canParseUrl(url) {
  if (URL.canParse) {
    return URL.canParse(url);
  }
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
}
const sourceOfFundsTypeValidations = {};
const HAS_PROTOCOL_REGEX = /^https?:\/\//i;
const sourceOfFundsAdditionalDataValidations = {
  website: {
    modes: ["blur"],
    validate: (val) => !!val && canParseUrl(val),
    errorMessage: (val) => {
      if (val && !HAS_PROTOCOL_REGEX.test(val)) return "validationUrlMustStartWithHttpOrHttps";
      return "validationPleaseEnterAValidUrl";
    }
  },
  amount: {
    modes: ["blur"],
    validate: (amount) => amount?.value != null && !Number.isNaN(Number(amount.value)),
    errorMessage: "pleaseEnterAValidAmount"
  },
  dateOfSourceEvent: {
    modes: ["blur"],
    validate: (dateOfSourceEvent) => validateDateNotInTheFuture(dateOfSourceEvent),
    errorMessage: "dateCannotBeInTheFuture"
  },
  dateOfFundsReceived: {
    modes: ["blur"],
    validate: (dateOfFundsReceived) => validateDateNotInTheFuture(dateOfFundsReceived),
    errorMessage: "dateCannotBeInTheFuture"
  }
};
const logger = createLogger();
function SourceOfFundsDropin({
  country,
  problems,
  handleHomeClick
}) {
  const { data: legalEntity, isLoading: isLoadingRootLegalEntity } = useLegalEntity(ROOT_LE);
  const [loadingStatus, setLoadingStatus] = useState("success");
  const [activeBusinessLine, setActiveBusinessLine] = useState();
  const [activeSourceOfFund, setActiveSourceOfFund] = useState({
    sourceOfFundsType: {},
    additionalData: {}
  });
  const [allBusinessLines, setAllBusinessLines] = useState([]);
  const [gettingStarted, setGettingStarted] = useState(true);
  const [showUploadPage, setShowUploadPage] = useState(false);
  const [loading, setLoading] = useState(false);
  const { baseUrl, rootLegalEntityId } = useApiContext();
  const { t: sofT } = useTranslation("sof");
  const userEvents = useAnalyticsContext();
  const { showToast } = useToastContext();
  const { data: sofBusinessLines, isLoading: isLoadingBusinessLines } = useBusinessLines(ALLOWED_SOF_SERVICES);
  const { mutateAsync: createLegalEntity } = useCreateLegalEntity();
  const { mutateAsync: updateLegalEntity } = useUpdateLegalEntity();
  const { mutateAsync: updateSoFMutation } = useUpdateSourceOfFunds();
  const form = useMultiForm({
    requiredFields: getSourceOfFundsRequiredFields,
    rules: {
      sourceOfFundsType: sourceOfFundsTypeValidations,
      additionalData: sourceOfFundsAdditionalDataValidations
    },
    defaultData: activeSourceOfFund
  });
  const {
    data = activeSourceOfFund,
    setFormData,
    requiredFields,
    isValid,
    triggerValidation
  } = form;
  const isSoFDocumentMissing = useMemo(
    () => legalEntity?.problems?.some(
      (problem) => problem?.verificationErrors?.some(
        (verificationError) => verificationError?.code === MISSING_DATA_SOF_UPLOAD_CODE
      )
    ) ?? false,
    [legalEntity?.problems]
  );
  const idsToFetch = sofBusinessLines?.map((businessLine) => businessLine.sourceOfFunds?.originatorLegalEntityId).filter((id) => Boolean(id)) ?? [];
  const legalEntityResults = useLegalEntities(idsToFetch, {
    staleTime: 5 * 60 * 1e3
    // 5 minutes
  });
  const areLegalEntitiesLoading = legalEntityResults.some((result) => result.isLoading);
  const normalizedBusinessLines = useMemo(() => {
    if (!sofBusinessLines) {
      return null;
    }
    return sofBusinessLines.map((businessLine, index) => {
      const result = legalEntityResults[index];
      let updatedBusinessLine = { ...businessLine };
      if (result && result.data) {
        updatedBusinessLine = parseOriginatorDetails(result.data, updatedBusinessLine);
      } else if (result && result.isError) {
        logger.error(`Error fetching legal entity for BL ${businessLine.id}:`, result.error);
        showToast({ label: sofT(($) => $["unableToLoadRelatedEntity"]), variant: "error" });
      }
      if (updatedBusinessLine.sourceOfFunds?.adyenProcessedFunds) {
        updatedBusinessLine.sourceOfFunds.type = "adyen";
      }
      return updatedBusinessLine;
    });
  }, [
    sofBusinessLines,
    // This is because the result of useQueries is not referentially stable, even though the individual query results are, so eslint complains
    // Also, this is generally safe, since this is typically what React Query returns
    JSON.stringify(
      legalEntityResults.map((r) => ({
        data: r.data,
        isError: r.isError,
        error: r.error,
        isLoading: r.isLoading
      }))
    )
  ]);
  useEffect(() => {
    if (sofBusinessLines && !areLegalEntitiesLoading && normalizedBusinessLines) {
      clearSofErrorMessage();
      setLoading(true);
      try {
        if (normalizedBusinessLines.length) {
          const firstBusinessLine = normalizedBusinessLines[0];
          const sourceOfFundsMap = normalizedBusinessLines.map(
            (businessLine) => mapSourceOfFundToSourceOfFundsSchema(businessLine)
          );
          if (firstBusinessLine) {
            setActiveBusinessLine(firstBusinessLine);
            const mappedSof = sourceOfFundsMap[0];
            setActiveSourceOfFund(mappedSof);
            setAllBusinessLines(normalizedBusinessLines);
            if (mappedSof?.sourceOfFundsType) {
              setFormData("sourceOfFundsType", mappedSof.sourceOfFundsType);
            }
            if (mappedSof?.additionalData) {
              setFormData("additionalData", mappedSof.additionalData);
            }
          }
        }
      } catch (error) {
        showToast({ label: sofT(($) => $["unableToLoadRelatedEntity"]), variant: "error" });
        logger.error(error);
      } finally {
        setLoading(false);
      }
    }
  }, [sofBusinessLines, areLegalEntitiesLoading, normalizedBusinessLines, sofT, logger]);
  useEffect(() => {
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
  }, [userEvents]);
  const sourceOfFundsRequiredForms = useMemo(
    () => getSourceOfFundsRequiredForms(data?.sourceOfFundsType),
    [data?.sourceOfFundsType]
  );
  const forms = useMemo(() => {
    const requiredForms = getRequiredForms(
      sourceOfFundsRequiredForms,
      requiredFields,
      void 0,
      true
    );
    return addValidityToForms(requiredForms, isValid, problems);
  }, [sourceOfFundsRequiredForms, requiredFields, isValid, problems]);
  const createOrUpdateOriginator = async (additionalData, prevAdditionalData) => {
    let originatorLegalEntityId;
    const sofOriginator = parseSofOriginatorPayload(additionalData);
    if (additionalData?.originatorLegalEntityId && additionalData?.originatorType === prevAdditionalData?.originatorType) {
      try {
        sofOriginator.id = additionalData?.originatorLegalEntityId;
        if (sofOriginator.type) {
          delete sofOriginator.type;
        }
        const patchLegalEntity = {
          ...sofOriginator,
          id: sofOriginator.id
        };
        const le = await updateLegalEntity(patchLegalEntity);
        originatorLegalEntityId = le?.id;
      } catch (e) {
        logger.log("Error updating  originator legal entity", e);
      }
    } else {
      try {
        const le = await createLegalEntity(sofOriginator);
        originatorLegalEntityId = le?.id;
      } catch (e) {
        logger.log("Error creating  originator legal entity", e);
      }
    }
    return originatorLegalEntityId;
  };
  const handleSubmit = useCallback(async () => {
    const sofData = { ...data };
    const sofType = sofData?.sourceOfFundsType?.type;
    if (!sofType || !activeBusinessLine?.id) {
      return;
    }
    const eventsAdditionalData = {};
    setLoadingStatus("loading");
    const { additionalData } = sofData;
    const sofPayload = getSourceOfFundsPayload(sofType, additionalData);
    if (sofType === "donations" || sofType === "inheritance") {
      try {
        sofPayload.originatorLegalEntityId = await createOrUpdateOriginator(
          additionalData,
          activeSourceOfFund?.additionalData
        );
      } catch (e) {
        setSofErrorMessage(e?.message || sofT(($) => $["errorUpdatingSourceOfFunds"]));
        logger.log("Error updating source of funds", e);
      }
      eventsAdditionalData.originatorType = additionalData?.originatorType ?? "";
    }
    if (sofType === "thirdPartyFunding") {
      eventsAdditionalData.financiers = `${additionalData?.financiers?.length || 0} investor(s)`;
    }
    const sofMutationPayload = {
      ...sofPayload,
      businessLineId: activeBusinessLine.id
    };
    try {
      await updateSoFMutation(sofMutationPayload);
      userEvents.addTaskEvent("Success", {
        actionType: "submit",
        returnValue: sofType,
        additionalData: eventsAdditionalData
      });
      setGettingStarted(true);
      setShowUploadPage(false);
      setActiveSourceOfFund({ sourceOfFundsType: {}, additionalData: {} });
      gotoFormByFormIndex(0);
      setSofErrorMessage("");
      showToast({ label: sofT(($) => $["successAddedFundingSources"]), variant: "success" });
      handleHomeClick?.();
    } catch (e) {
      setSofErrorMessage(sofT(($) => $["errorUpdatingSourceOfFunds"]));
      logger.log("Error updating source of funds", e);
    }
    setLoadingStatus("success");
  }, [data, activeSourceOfFund, handleHomeClick]);
  const handleGettingStarted = useCallback(() => {
    setGettingStarted(!gettingStarted);
  }, [gettingStarted]);
  const handleSourceOfFundsClick = (SoF, businessLine) => {
    setActiveBusinessLine(businessLine);
    setActiveSourceOfFund(SoF);
    setGettingStarted(false);
  };
  const { handleNextClick, activeForm, gotoFormByFormIndex, steps, handleBackClick } = useFormComposer({
    problems,
    forms,
    onSubmit: handleSubmit,
    triggerValidation
  });
  const documentUtils = documentApiUtils({
    baseUrl: baseUrl.value,
    rootLegalEntityId: rootLegalEntityId.value
  });
  const handleNavigateToSummary = async () => {
    setShowUploadPage(false);
    setGettingStarted(true);
  };
  const handleNavigateToUploadPage = () => {
    setShowUploadPage(true);
  };
  return /* @__PURE__ */ jsx("div", { className: styles.sourceOfFunds, children: loading || isLoadingRootLegalEntity || isLoadingBusinessLines || areLegalEntitiesLoading ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsxs(Fragment, { children: [
    gettingStarted && !showUploadPage && legalEntity && /* @__PURE__ */ jsx(
      SourceOfFundsGettingStarted,
      {
        handleCancelClick: handleHomeClick,
        handleGettingStartedClick: handleGettingStarted,
        businessLines: allBusinessLines,
        problems: legalEntity?.problems,
        handleSourceOfFundsClick,
        handleNavigateToUploadPage,
        legalEntity,
        isSoFDocumentMissing
      }
    ),
    showUploadPage && legalEntity && /* @__PURE__ */ jsx(
      SourceOfFundsUpload,
      {
        businessLines: allBusinessLines,
        documentUtils,
        legalEntity,
        handleNavigateToSummary
      }
    ),
    !gettingStarted && !showUploadPage && /* @__PURE__ */ jsx(FormContextProvider, { form, children: /* @__PURE__ */ jsx(
      FormFlow,
      {
        forms,
        disableNextButton: !activeForm.isValid,
        activeForm,
        gotoFormByFormIndex,
        handleBackClick: steps.current === 0 ? handleGettingStarted : handleBackClick,
        handleCancelClick: handleHomeClick,
        handleNextClick,
        loadingStatus,
        currentStep: steps.current,
        totalSteps: steps.total,
        children: /* @__PURE__ */ jsx(
          SourceOfFunds,
          {
            country,
            activeForm,
            activeBusinessLine,
            sourceOfFundsType: data?.sourceOfFundsType?.type,
            data: activeSourceOfFund
          }
        )
      }
    ) })
  ] }) });
}
const SourceOfFundsPage = ({ onSubmit, handleHomeClick }) => {
  const { data: rootLe } = useLegalEntity(ROOT_LE);
  const capabilityProblems = useCapabilityProblems();
  const { i18n } = useTranslation();
  addResourceBundles(i18n, [
    { ns: "sof", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../tasks/SourceOfFundsDropin/language/bg-BG.json": () => import("./bg-BG-BvLl6gaB.js"), "../tasks/SourceOfFundsDropin/language/cs-CZ.json": () => import("./cs-CZ-hT5w5It6.js"), "../tasks/SourceOfFundsDropin/language/da-DK.json": () => import("./da-DK-DZwlENGe.js"), "../tasks/SourceOfFundsDropin/language/de-DE.json": () => import("./de-DE-DXR3EpEc.js"), "../tasks/SourceOfFundsDropin/language/el-GR.json": () => import("./el-GR-DtFE64KX.js"), "../tasks/SourceOfFundsDropin/language/en-US.json": () => import("./en-US-CozY33On.js"), "../tasks/SourceOfFundsDropin/language/es-ES.json": () => import("./es-ES-yMXcOjDL.js"), "../tasks/SourceOfFundsDropin/language/et-EE.json": () => import("./et-EE-C8RrUpLm.js"), "../tasks/SourceOfFundsDropin/language/fi-FI.json": () => import("./fi-FI-xqnQ38yC.js"), "../tasks/SourceOfFundsDropin/language/fr-FR.json": () => import("./fr-FR-BSynpexF.js"), "../tasks/SourceOfFundsDropin/language/hr-HR.json": () => import("./hr-HR-D5V7g9H2.js"), "../tasks/SourceOfFundsDropin/language/hu-HU.json": () => import("./hu-HU-hbVM6tMS.js"), "../tasks/SourceOfFundsDropin/language/it-IT.json": () => import("./it-IT-C_651bEP.js"), "../tasks/SourceOfFundsDropin/language/ja-JP.json": () => import("./ja-JP-CvNJvxkQ.js"), "../tasks/SourceOfFundsDropin/language/lt-LT.json": () => import("./lt-LT-Ci357QYQ.js"), "../tasks/SourceOfFundsDropin/language/lv-LV.json": () => import("./lv-LV-Dxe-A5vo.js"), "../tasks/SourceOfFundsDropin/language/nl-NL.json": () => import("./nl-NL-JChnFdCY.js"), "../tasks/SourceOfFundsDropin/language/no-NO.json": () => import("./no-NO--OoWld_l.js"), "../tasks/SourceOfFundsDropin/language/pl-PL.json": () => import("./pl-PL-DtJ3sgVO.js"), "../tasks/SourceOfFundsDropin/language/pt-BR.json": () => import("./pt-BR-C0I_kTQ6.js"), "../tasks/SourceOfFundsDropin/language/pt-PT.json": () => import("./pt-PT-Bf4IV7wp.js"), "../tasks/SourceOfFundsDropin/language/ro-RO.json": () => import("./ro-RO-4j2I7YM7.js"), "../tasks/SourceOfFundsDropin/language/sk-SK.json": () => import("./sk-SK-C5Qmv4E6.js"), "../tasks/SourceOfFundsDropin/language/sl-SI.json": () => import("./sl-SI-BZpXMHiG.js"), "../tasks/SourceOfFundsDropin/language/sv-SE.json": () => import("./sv-SE-DsPdegWB.js") }), `../tasks/SourceOfFundsDropin/language/${lang}.json`, 5) }
  ]);
  if (!rootLe) {
    return /* @__PURE__ */ jsx(Loader, {});
  }
  const problems = capabilityProblems ? getProblemsForEntity(capabilityProblems, EntityTypes.LEGAL_ENTITY, rootLe.id) : void 0;
  return /* @__PURE__ */ jsx(
    SourceOfFundsDropin,
    {
      legalEntityResponse: rootLe,
      country: getLegalEntityCountry(rootLe),
      problems,
      onSubmit,
      handleHomeClick
    }
  );
};
export {
  SourceOfFundsPage
};
