;
{
  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] = "cbb7c8e0-bb6d-43c7-ac77-4a757a67b02b", e._sentryDebugIdIdentifier = "sentry-dbid-cbb7c8e0-bb6d-43c7-ac77-4a757a67b02b");
  } catch (e) {
  }
}
;
import { ax as DecisionMakerTypes, aH as drop, ab as cloneObject, u as useTranslation, c as useLegalEntity, V as Button, L as Loader, z as Typography, p as useAnalyticsContext, a as addResourceBundles, R as ROOT_LE, y as useGetTaskStatus, v as useExperimentsContext, a8 as EntityTypes, bm as DATA_MISSING_DECISION_MAKER_ERROR_CODE_MAPPING, aj as getOwnDecisionMakers, bc as getAvailableDecisionMakerRoleTypes, j as TaskTypes, aI as getAllowedDecisionMakerRoles, aB as Trans, q as TaskStatuses, _ as __variableDynamicImportRuntimeHelper, o as LegalEntityTypes } from "./StoreProvider-CqQrndhS.js";
import { jsxs, Fragment, jsx } from "preact/jsx-runtime";
import { useState, useMemo, useEffect } from "preact/hooks";
import { u as useScenarios } from "./useScenarios-CcJjvY9u.js";
import { u as useUpdateLegalEntity } from "./useUpdateLegalEntity-CcNBhTXa.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import { L as List } from "./List-BAzyC6sw.js";
import { L as ListItem } from "./ListItem-Dn466mBk.js";
import { M as Modal } from "./Modal-1lLoobr9.js";
import { u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { u as useDataMissingRemediations } from "./useDataMissingRemediations-D45Aol7Y.js";
import { S as StackLayout } from "./unincorporated-partnership-MeN1dp53.js";
import { a as Alert } from "./Alert-CpDg47bv.js";
import { C as ContextGuidance } from "./ContextGuidance-BESxqmbz.js";
import { A as ActionBar } from "./ActionBar-DPfNdSxA.js";
import { D as DropinLayout } from "./DropinLayout-CBP_cHLC.js";
import { E as EntityAssociation } from "./EntityAssociation-BABkwZ5a.js";
import { E as EntityGuidanceStatus, i as iconStatus } from "./EntityGuidanceStatus-gPHo-N2L.js";
import { T as TaskVerificationStatus } from "./TaskVerificationStatus-C19Z4x3D.js";
import { G as GuidanceQuestionValues, m as mapLegalEntityToIndividualOnfidoSchema, i as individualFormDefaultData } from "./mapLegalEntityToIndividualSchema-HzmhX3DC.js";
import { u as useCapabilityProblems } from "./getProblemsForEntity-C1PgQbDM.js";
import { a as getTrustedEntityAssociations } from "./getTrustedFields-C5-mXl-l.js";
import { S as StructuredList } from "./StructuredList-BNLhk_zV.js";
import { D as DetailViewLayout } from "./DetailViewLayout-Z9cuUp4X.js";
import { C as Confirm } from "./Confirm-BeimUgOe.js";
import { m as mapAddressLabels } from "./utils-DmjdHPet.js";
import { a as datasetUtilities } from "./datasetUtil-BHQp0-xL.js";
import { l as localizeDateString } from "./localizeDateString-pCDWhd0r.js";
import { lazy } from "preact/compat";
import { I as Image } from "./Image-C0SMWMbc.js";
import { L as LandingLayout } from "./LandingLayout-B4GiCZLB.js";
const BENEFICIAL_OWNER_ROLES = [
  DecisionMakerTypes.OWNER,
  DecisionMakerTypes.CONTROLLING_PERSON,
  DecisionMakerTypes.DIRECTOR
];
const getDecisionMakerDescription = (types, t) => {
  const isSignatory = types.includes(DecisionMakerTypes.SIGNATORY);
  const isBeneficialOwner = types.some((type) => BENEFICIAL_OWNER_ROLES.includes(type));
  return [isSignatory && t(($) => $.signatory), isBeneficialOwner && t(($) => $.beneficialOwner)].filter(Boolean).join(", ");
};
const isManualVerificationOrExistingDoc = (idVerificationMethod) => idVerificationMethod === "manualVerification" || idVerificationMethod === "existingDocument";
const formatFileSummaryData = (data, locale) => {
  const { idVerificationMethod, proofOfNationalId, proofOfResidency, proofOfRelationship } = data;
  const proofOfNationalIdFile = proofOfNationalId?.proofOfNationalId?.[0];
  const proofOfResidencyFile = proofOfResidency?.proofOfResidency?.[0];
  const proofOfRelationshipFile = proofOfRelationship?.proofOfRelationship?.[0];
  const idDocument = {
    idDocumentType: idVerificationMethod?.idDocument?.idDocumentType,
    uploadedDate: idVerificationMethod?.idDocument?.modificationDate ? localizeDateString(idVerificationMethod?.idDocument?.modificationDate ?? "", locale) : void 0
  };
  return {
    // Format the ID document if it exists.
    ...idDocument?.idDocumentType && {
      idDocument
    },
    // Include proof of national ID file name if it exists.
    ...proofOfNationalIdFile && {
      proofOfNationalId: {
        fileName: proofOfNationalIdFile.name
      }
    },
    // Include proof of residency file name if it exists.
    ...proofOfResidencyFile && {
      proofOfResidency: {
        fileName: proofOfResidencyFile.name
      }
    },
    // Include proof of relationship file name if it exists.
    ...proofOfRelationshipFile && {
      proofOfRelationship: {
        fileName: proofOfRelationshipFile.name
      }
    }
  };
};
const formatDataForSummary = (dataToFormat, locale, commonT) => {
  if (!dataToFormat) return {};
  const datasetUtils = datasetUtilities(locale);
  let formattedSummaryData = cloneObject(dataToFormat);
  if (formattedSummaryData?.basicDetails?.phoneNumber) {
    formattedSummaryData.basicDetails.phoneNumber = formattedSummaryData.basicDetails.phoneNumber.number;
  }
  if (formattedSummaryData.additionalPersonalDetails?.country) {
    formattedSummaryData.additionalPersonalDetails.country = datasetUtils.getCountryName(
      formattedSummaryData.additionalPersonalDetails.country
    );
  }
  if (formattedSummaryData.additionalPersonalDetails?.nationality) {
    formattedSummaryData.additionalPersonalDetails.nationality = datasetUtils.getCountryName(
      formattedSummaryData.additionalPersonalDetails.nationality
    );
  }
  if (formattedSummaryData.additionalPersonalDetails) {
    formattedSummaryData.address = mapAddressLabels(
      formattedSummaryData.additionalPersonalDetails,
      datasetUtils
    );
  }
  if (formattedSummaryData.basicDetails?.accountHolder) {
    formattedSummaryData.basicDetails.accountHolder = commonT(
      ($) => $[formattedSummaryData.basicDetails.accountHolder]
    );
  }
  if (formattedSummaryData.additionalPersonalDetails?.birthDate) {
    formattedSummaryData.additionalPersonalDetails.birthDate = localizeDateString(
      formattedSummaryData.additionalPersonalDetails.birthDate,
      locale
    );
  }
  if (isManualVerificationOrExistingDoc(
    formattedSummaryData.idVerificationMethod?.idVerificationMethod
  ) || formattedSummaryData.proofOfResidency) {
    const fileSummaryData = formatFileSummaryData(dataToFormat, locale);
    formattedSummaryData = { ...formattedSummaryData, ...fileSummaryData };
    formattedSummaryData.manualIdUpload = { ...formattedSummaryData.idDocument };
    formattedSummaryData.idVerificationMethod.idDocument = { ...formattedSummaryData.idDocument };
  }
  if (formattedSummaryData.additionalPersonalDetails?.taxInformation) {
    const taxInformationByNationality = formattedSummaryData.additionalPersonalDetails.taxInformation.find(
      (taxId) => taxId.country === dataToFormat.additionalPersonalDetails?.nationality
    );
    if (taxInformationByNationality) {
      delete formattedSummaryData.additionalPersonalDetails.taxInformation;
      formattedSummaryData.additionalPersonalDetails[taxInformationByNationality.type] = taxInformationByNationality.number;
    }
    if (!taxInformationByNationality) {
      const taxInformationByCountry = formattedSummaryData.additionalPersonalDetails.taxInformation.find(
        (taxId) => taxId.country === dataToFormat.additionalPersonalDetails?.country
      );
      if (taxInformationByCountry) {
        delete formattedSummaryData.additionalPersonalDetails.taxInformation;
        formattedSummaryData.additionalPersonalDetails[taxInformationByCountry.type] = taxInformationByCountry.number;
      }
    }
  }
  if (formattedSummaryData?.signatoryQuestionnaire) {
    formattedSummaryData.signatoryQuestionnaire = dataToFormat?.signatoryQuestionnaire?.isSignatory === GuidanceQuestionValues.YES ? [commonT(($) => $["signatorySummaryLabel"])] : [];
  }
  if (formattedSummaryData?.uboQuestionnaire) {
    const roleFieldToLabelMap = {
      isOwner: "ownerSummaryLabel",
      isControllingPerson: "controllingPersonSummaryLabel",
      isDirector: "directorSummaryLabel"
    };
    formattedSummaryData.uboQuestionnaire = Object.keys(roleFieldToLabelMap).flatMap(
      (field) => dataToFormat?.uboQuestionnaire?.[field] === GuidanceQuestionValues.YES ? [commonT(($) => $[roleFieldToLabelMap[field]])] : []
    );
  }
  return formattedSummaryData;
};
const getOmittedKeysForSummary = (data, taskType) => [
  // Omit 'role' if the task is for a decision maker.
  ...["role"],
  // Omit 'idNumber' if the user is exempt from providing it.
  ...data?.additionalPersonalDetails?.idNumberExempt ? ["idNumber"] : [],
  // Omit 'idVerificationMethod' if manual verification was used.
  ...isManualVerificationOrExistingDoc(data?.idVerificationMethod?.idVerificationMethod) ? ["idVerificationMethod"] : [],
  "address",
  "manualIdUpload"
];
const getSummaryData = (data, locale, commonT, taskType) => {
  const summaryData = formatDataForSummary(data, locale, commonT);
  const omittedKeys = getOmittedKeysForSummary(data)?.filter(Boolean);
  return {
    ...drop(...omittedKeys).from(summaryData),
    basicDetails: drop("firstName", "lastName", "role", "nomineeShareholder").from(
      summaryData.basicDetails
    ),
    additionalPersonalDetails: drop("idNumberExempt").from(summaryData.additionalPersonalDetails),
    idDocument: summaryData.idVerificationMethod?.idDocument
  };
};
const getStructuredListItems = (data, commonT) => {
  if (typeof data !== "object" || data === null || Array.isArray(data)) {
    return [];
  }
  return Object.entries(data).filter(
    ([itemKey, itemValue]) => itemValue != null && itemValue !== "" && !["nomineeDirector", "nomineeShareholder"].includes(itemKey) && (!Array.isArray(itemValue) || itemValue.length > 0)
  ).map(([itemKey, itemValue]) => ({
    term: commonT(($) => $[itemKey]),
    details: Array.isArray(itemValue) ? itemValue.join(", ") : commonT(($) => $[itemValue]) || String(itemValue),
    type: Array.isArray(itemValue) ? "list" : "text"
  }));
};
const DecisionMakerDetails = ({
  decisionMaker,
  parentLegalEntity,
  handleClose,
  handleDelete,
  handleEdit
}) => {
  const { t: commonT, i18n } = useTranslation("common");
  const { t: individualT } = useTranslation("individual");
  const [confirmOpen, setConfirmOpen] = useState(false);
  const { data: legalEntity, isLoading: isLegalEntityLoading } = useLegalEntity(
    decisionMaker.reference
  );
  const isTrusted = getTrustedEntityAssociations(parentLegalEntity).some(
    (ea) => ea.reference === decisionMaker.reference
  );
  const formattedSummary = useMemo(() => {
    if (legalEntity) {
      const individualOnfidoSchema = mapLegalEntityToIndividualOnfidoSchema(
        legalEntity,
        false,
        true,
        parentLegalEntity
      );
      return getSummaryData(
        individualOnfidoSchema,
        i18n.language,
        commonT
      );
    }
  }, [legalEntity, parentLegalEntity, i18n, commonT]);
  const actions = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Button, { onClick: handleEdit, variant: "primary", fullWidth: true, children: commonT(($) => $["editDetails"]) }),
    /* @__PURE__ */ jsx(
      Button,
      {
        onClick: () => setConfirmOpen(true),
        variant: "secondary",
        fullWidth: true,
        disabled: isTrusted,
        children: commonT(($) => $["delete"])
      }
    )
  ] });
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Modal, { onClose: handleClose, ariaLabel: commonT(($) => $["individualDetails"]), inset: true, children: /* @__PURE__ */ jsx(DetailViewLayout, { title: commonT(($) => $["individualDetails"]), actions, children: isLegalEntityLoading || !legalEntity ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsxs(StackLayout, { gap: "medium", children: [
      /* @__PURE__ */ jsx(
        ListItem,
        {
          accessory: /* @__PURE__ */ jsx(TaskVerificationStatus, { status: decisionMaker.status }),
          avatar: { iconName: "user", circle: true },
          title: decisionMaker.name,
          description: getDecisionMakerDescription(decisionMaker.types, individualT)
        }
      ),
      formattedSummary && Object.entries(formattedSummary).map(([key, value]) => {
        const items = getStructuredListItems(value, commonT);
        if (items.length === 0) {
          return null;
        }
        return /* @__PURE__ */ jsxs(List, { variant: "grouped-secondary", children: [
          /* @__PURE__ */ jsx(Typography, { variant: "title", children: individualT(($) => $[key]) }),
          /* @__PURE__ */ jsx(StructuredList, { items })
        ] }, key);
      }).filter(Boolean)
    ] }) }) }),
    confirmOpen && /* @__PURE__ */ jsx(
      Confirm,
      {
        title: commonT(($) => $["deleteItem"], { item: decisionMaker.name }),
        description: commonT(($) => $["thisActionIsPermanent"]),
        onConfirm: handleDelete,
        confirmText: commonT(($) => $["delete"]),
        onCancel: () => setConfirmOpen(false),
        critical: true
      }
    )
  ] });
};
const decisionMakersGettingStarted = "adyen-kyc-decision-makers-getting-started";
const styles = {
  decisionMakersGettingStarted
};
const DecisionMakersModalContent = () => {
  const { t } = useTranslation("individual");
  return /* @__PURE__ */ jsxs("div", { className: styles.decisionMakersGettingStartedModal, children: [
    /* @__PURE__ */ jsx(Typography, { variant: "title-l", el: "h3", className: "adyen-kyc-u-margin-bottom-40", children: t(($) => $["moreAboutOwnersAndDecisionMakers"]) }),
    /* @__PURE__ */ jsx(Typography, { variant: "body-strongest", el: "h4", className: "adyen-kyc-u-margin-bottom-12", children: t(($) => $["ownersAndDecisionMakersDescriptionQ1"]) }),
    /* @__PURE__ */ jsx(Typography, { el: "p", className: "adyen-kyc-u-margin-bottom-32", children: t(($) => $["ownersAndDecisionMakersDescriptionA1"]) }),
    /* @__PURE__ */ jsx(
      Alert,
      {
        title: t(($) => $["ownersDescriptionAlertTitle"]),
        icon: false,
        className: "adyen-kyc-u-margin-bottom-32",
        children: t(($) => $["ownersAndDecisionMakersDescriptionAlertContent"])
      }
    ),
    /* @__PURE__ */ jsx(Typography, { variant: "body-strongest", el: "h4", className: "adyen-kyc-u-margin-bottom-12", children: t(($) => $["ownersAndDecisionMakersDescriptionQ2"]) }),
    /* @__PURE__ */ jsx(Typography, { el: "p", children: t(($) => $["ownersAndDecisionMakersDescriptionA2P1"]) }),
    /* @__PURE__ */ jsx(Typography, { el: "p", className: "adyen-kyc-u-margin-bottom-32", children: t(($) => $["ownersAndDecisionMakersDescriptionA2P2"]) }),
    /* @__PURE__ */ jsx(
      Alert,
      {
        title: t(($) => $["ownersDescriptionAlertTitle"]),
        icon: false,
        className: "adyen-kyc-u-margin-bottom-32",
        children: t(($) => $["ownersDescriptionAlertContent"])
      }
    ),
    /* @__PURE__ */ jsx(Typography, { variant: "body-strongest", el: "h4", className: "adyen-kyc-u-margin-bottom-12", children: t(($) => $["ownersAndDecisionMakersDescriptionQ3"]) }),
    /* @__PURE__ */ jsx(Typography, { el: "p", className: "adyen-kyc-u-margin-bottom-32", children: t(($) => $["ownersAndDecisionMakersDescriptionA3"]) }),
    /* @__PURE__ */ jsx(Typography, { variant: "body-strongest", el: "h4", className: "adyen-kyc-u-margin-bottom-12", children: t(($) => $["ownersAndDecisionMakersDescriptionQ4"]) }),
    /* @__PURE__ */ jsx(Typography, { el: "p", className: "adyen-kyc-u-margin-bottom-32", children: t(($) => $["ownersAndDecisionMakersDescriptionA4"]) })
  ] });
};
const decisionMakerGroup = lazy(() => import("./decision-makers-group-DrvpnEqj.js"));
const DecisionMakersGettingStarted = ({
  addDecisionMakerOnClick,
  handleCancelClick
}) => {
  const { t: commonT } = useTranslation("common");
  const { t: individualT } = useTranslation("individual");
  const userEvents = useAnalyticsContext();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const openModal = () => {
    userEvents.addPageEvent("Opened modal", {
      actionType: "open",
      label: "decisionMakersGettingStartedModal"
    });
    setIsModalOpen(true);
  };
  const closeModal = () => {
    userEvents.addPageEvent("Closed modal", {
      actionType: "close",
      label: "decisionMakersGettingStartedModal"
    });
    setIsModalOpen(false);
  };
  return /* @__PURE__ */ jsxs("div", { className: styles.decisionMakersGettingStarted, children: [
    /* @__PURE__ */ jsx(
      LandingLayout,
      {
        media: /* @__PURE__ */ jsx(Image, { lazyLoadedImage: decisionMakerGroup }),
        title: individualT(($) => $["ownersAndDecisionMakers"]),
        description: individualT(($) => $["ownersAndDecisionMakersDescription"]),
        helpAction: /* @__PURE__ */ jsx(Button, { variant: "link", onClick: openModal, fullWidth: true, children: commonT(($) => $["learnMore"]) }),
        actions: /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              fullWidth: true,
              testId: "decision-makers-getting-started-primary-button",
              onClick: addDecisionMakerOnClick,
              children: commonT(($) => $["gettingStarted"])
            }
          ),
          handleCancelClick && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "tertiary",
              fullWidth: true,
              testId: "decision-makers-getting-started-cancel-button",
              onClick: handleCancelClick,
              children: commonT(($) => $["finishLater"])
            }
          )
        ] })
      }
    ),
    isModalOpen && /* @__PURE__ */ jsx(
      Modal,
      {
        onClose: closeModal,
        ariaLabel: individualT(($) => $["moreAboutOwnersAndDecisionMakers"]),
        inset: true,
        children: /* @__PURE__ */ jsx(DecisionMakersModalContent, {})
      }
    )
  ] });
};
const signatoryMissingAlert = {
  type: "single",
  code: "2_124",
  titleKey: "authorizedSignatoryMissing",
  descriptionKey: "addAtLeastOneAuthorizedSignatory",
  actionKey: "addAuthorizedSignatory"
};
const beneficialOwnersMissingAlert = {
  type: "grouped",
  codes: ["2_123", "2_151", "2_185"],
  titleKey: "beneficialOwnersMissing",
  actionKey: "addBeneficialOwner",
  detailKeys: {
    "2_123": "addAllBeneficialOwners",
    "2_151": "addAtLeastOneBeneficialOwnerControllingPerson",
    "2_185": "addAtLeastOneDirector"
  }
};
const decisionMakerRemediationAlerts = [
  signatoryMissingAlert,
  beneficialOwnersMissingAlert
];
const RemediationAlertItem = ({ config, activeCodes, onAction }) => {
  const { t } = useTranslation("individual");
  const isVisible = useMemo(() => {
    if (config.type === "single") {
      return activeCodes.includes(config.code);
    }
    return config.codes.some((code) => activeCodes.includes(code));
  }, [activeCodes, config]);
  const activeGroupedDetails = useMemo(() => {
    if (config.type !== "grouped") {
      return [];
    }
    return config.codes.filter((code) => activeCodes.includes(code)).map((code) => config.detailKeys[code]);
  }, [activeCodes, config]);
  if (!isVisible) {
    return null;
  }
  return /* @__PURE__ */ jsxs(
    Alert,
    {
      className: "adyen-kyc-decision-makers__warning",
      title: t(($) => $[config.titleKey]),
      variant: "warning",
      children: [
        config.type === "single" && /* @__PURE__ */ jsx("p", { children: t(($) => $[config.descriptionKey]) }),
        config.type === "grouped" && (activeGroupedDetails.length > 1 ? /* @__PURE__ */ jsx("ul", { children: activeGroupedDetails.map((key) => /* @__PURE__ */ jsx("li", { children: t(($) => $[key]) }, key)) }) : /* @__PURE__ */ jsx("p", { children: t(($) => $[activeGroupedDetails[0]]) })),
        /* @__PURE__ */ jsx(Button, { variant: "link", onClick: onAction, children: t(($) => $[config.actionKey]) })
      ]
    }
  );
};
const RemediationAlerts = ({ activeCodes, onAction }) => /* @__PURE__ */ jsx(Fragment, { children: decisionMakerRemediationAlerts.map((config) => /* @__PURE__ */ jsx(
  RemediationAlertItem,
  {
    config,
    activeCodes,
    onAction
  },
  config.type === "single" ? config.code : config.titleKey
)) });
const DecisionMakers = (props) => {
  const { data, isLoading } = useLegalEntity(ROOT_LE);
  const { i18n } = useTranslation();
  addResourceBundles(i18n, [
    { ns: "individual", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../../language/bg-BG.json": () => import("./bg-BG-wMYXZGDQ.js"), "../../language/cs-CZ.json": () => import("./cs-CZ-bkbdzIkF.js"), "../../language/da-DK.json": () => import("./da-DK-DvZ431fC.js"), "../../language/de-DE.json": () => import("./de-DE-0uSzhWg5.js"), "../../language/el-GR.json": () => import("./el-GR-CWWBcvDM.js"), "../../language/en-US.json": () => import("./en-US-cVpRgdC8.js"), "../../language/es-ES.json": () => import("./es-ES-B7dt4cn7.js"), "../../language/et-EE.json": () => import("./et-EE-D_3GB-yT.js"), "../../language/fi-FI.json": () => import("./fi-FI-REMsyTSr.js"), "../../language/fr-FR.json": () => import("./fr-FR-CvHWmim-.js"), "../../language/hr-HR.json": () => import("./hr-HR-LO3oO8yb.js"), "../../language/hu-HU.json": () => import("./hu-HU-DEKBPTur.js"), "../../language/it-IT.json": () => import("./it-IT-BeX7-OcD.js"), "../../language/ja-JP.json": () => import("./ja-JP-B3wVYIJU.js"), "../../language/lt-LT.json": () => import("./lt-LT-3niAR3rI.js"), "../../language/lv-LV.json": () => import("./lv-LV-K-KFPny2.js"), "../../language/nl-NL.json": () => import("./nl-NL-CM5U8ODq.js"), "../../language/no-NO.json": () => import("./no-NO-BQL_M1pn.js"), "../../language/pl-PL.json": () => import("./pl-PL-DC_lIAnp.js"), "../../language/pt-BR.json": () => import("./pt-BR-AZ3roErF.js"), "../../language/pt-PT.json": () => import("./pt-PT-DVKtHjIY.js"), "../../language/ro-RO.json": () => import("./ro-RO-CHcD-PGb.js"), "../../language/sk-SK.json": () => import("./sk-SK-s9Xm01UD.js"), "../../language/sl-SI.json": () => import("./sl-SI-C0wSbuau.js"), "../../language/sv-SE.json": () => import("./sv-SE-DtKjf4Go.js") }), `../../language/${lang}.json`, 4) }
  ]);
  if (isLoading || !data) {
    return /* @__PURE__ */ jsx(Loader, {});
  }
  return /* @__PURE__ */ jsx(DecisionMakersInner, { ...props, legalEntity: data });
};
const DecisionMakersInner = ({
  legalEntity,
  onNavigateToIndividual,
  navigateBackToTaskList
}) => {
  const getTaskStatus = useGetTaskStatus();
  const { t: commonT } = useTranslation("common");
  const { t: individualT } = useTranslation("individual");
  const userEvents = useAnalyticsContext();
  const { isExperimentEnabled } = useExperimentsContext();
  const { showToast } = useToastContext();
  const isRevampedDecisionMakersTaskPageEnabled = isExperimentEnabled(
    "EnableRevampedDecisionMakersTaskPage"
  );
  const [showDecisionMakerModal, setShowDecisionMakerModal] = useState(false);
  const [selectedDecisionMaker, setSelectedDecisionMaker] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const openModal = () => {
    userEvents.addPageEvent("Opened modal", {
      actionType: "open",
      label: "decisionMakersDescriptionModal"
    });
    setIsModalOpen(true);
  };
  const closeModal = () => {
    userEvents.addPageEvent("Closed modal", {
      actionType: "close",
      label: "decisionMakersDescriptionModal"
    });
    setIsModalOpen(false);
  };
  const openDecisionMakerModal = (decisionMaker) => {
    userEvents.addPageEvent("Opened modal", {
      actionType: "open",
      label: "viewDecisionMakerModal"
    });
    setShowDecisionMakerModal(true);
    setSelectedDecisionMaker(decisionMaker);
  };
  const closeDecisionMakerModal = () => {
    userEvents.addPageEvent("Closed modal", {
      actionType: "close",
      label: "viewDecisionMakerModal"
    });
    setShowDecisionMakerModal(false);
    setSelectedDecisionMaker(null);
  };
  const capabilityProblems = useCapabilityProblems();
  const decisionMakerRemediationCodes = useMemo(() => {
    const missingData = capabilityProblems?.[EntityTypes.LEGAL_ENTITY]?.[legalEntity.id]?.missingData ?? [];
    const remediationCodes = missingData.flatMap((error) => {
      const remediation = DATA_MISSING_DECISION_MAKER_ERROR_CODE_MAPPING[error.code];
      return remediation ? [remediation] : [];
    });
    return [...new Set(remediationCodes)];
  }, [capabilityProblems, legalEntity.id]);
  const updateLegalEntity = useUpdateLegalEntity();
  const decisionMakers = getOwnDecisionMakers(legalEntity);
  const registeredCountry = legalEntity.organization.registeredAddress.country;
  const { data: scenarios } = useScenarios(registeredCountry, LegalEntityTypes.INDIVIDUAL);
  const availableDecisionMakers = getAvailableDecisionMakerRoleTypes(registeredCountry, scenarios);
  const translationKeys = {
    home: "goBackToTaskList"
  };
  const { remediationMessages } = useDataMissingRemediations({
    legalEntityId: legalEntity.id,
    problems: capabilityProblems ?? {}
  });
  const mappedDecisionMakers = decisionMakers?.reduce(
    (mappedDecisionMakers2, decisionMaker) => {
      if (!decisionMaker.legalEntityId) return mappedDecisionMakers2;
      const mappedDecisionMaker = mappedDecisionMakers2[decisionMaker.legalEntityId];
      const decisionMakerType = decisionMaker.type;
      mappedDecisionMakers2[decisionMaker.legalEntityId] = {
        reference: decisionMaker.legalEntityId,
        types: mappedDecisionMaker ? [...mappedDecisionMaker.types, decisionMakerType] : [decisionMakerType],
        status: getTaskStatus(TaskTypes.DECISION_MAKER, decisionMaker.legalEntityId),
        name: decisionMaker.name ?? "",
        legalEntityType: decisionMaker.entityType,
        problems: capabilityProblems?.LegalEntity?.[decisionMaker.legalEntityId]
      };
      return mappedDecisionMakers2;
    },
    {}
  );
  const uniqueDecisionMakers = mappedDecisionMakers ? Object.values(mappedDecisionMakers) : [];
  const trustedEntityAssociations = getTrustedEntityAssociations(legalEntity);
  const isActionNeeded = (dm) => dm.status === TaskStatuses.ERROR || dm.status === TaskStatuses.DETAILS_REQUIRED;
  const isComplete = (dm) => dm.status === TaskStatuses.FINISHED || dm.status === TaskStatuses.PROCESSING;
  const isSignatory = (dm) => dm.types.includes(DecisionMakerTypes.SIGNATORY);
  const actionNeededDecisionMakers = uniqueDecisionMakers.filter(isActionNeeded);
  const completeDecisionMakers = uniqueDecisionMakers.filter(isComplete);
  const actionNeededSignatories = actionNeededDecisionMakers.filter(isSignatory);
  const actionNeededBeneficialOwners = actionNeededDecisionMakers.filter((dm) => !isSignatory(dm));
  const completeSignatories = completeDecisionMakers.filter(isSignatory);
  const completeBeneficialOwners = completeDecisionMakers.filter((dm) => !isSignatory(dm));
  const showWarning = Boolean(remediationMessages.DECISION_MAKER && uniqueDecisionMakers.length);
  useEffect(() => {
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
  }, [userEvents]);
  useEffect(() => {
    if (showWarning) {
      userEvents.addTaskEvent("Encountered error", {
        task: TaskTypes.DECISION_MAKER_OVERVIEW,
        actionType: "alert",
        returnValue: "missingDecisionMaker"
      });
    }
  }, [remediationMessages.DECISION_MAKER, showWarning, userEvents]);
  const uniqueDecisionMakersPerType = (roleType) => uniqueDecisionMakers.filter(({ types }) => types.includes(roleType)).length;
  const allowedDecisionMakerTypes = getAllowedDecisionMakerRoles(
    legalEntity,
    TaskTypes.DECISION_MAKER,
    scenarios
  );
  const haveMaxDecisionMakers = allowedDecisionMakerTypes.length === 0;
  const getDecisionMakerTrackingParams = (decisionMaker) => ({
    task: TaskTypes.DECISION_MAKER_OVERVIEW,
    associatedLegalEntityId: decisionMaker.reference,
    associatedLegalEntityType: decisionMaker.legalEntityType,
    roles: decisionMaker.types
  });
  const addDecisionMakerOnClick = () => {
    onNavigateToIndividual();
  };
  const onRemediationAction = () => {
    const SIGNATORY_MISSING_CODE = "2_124";
    const DIRECTOR_MISSING_CODE = "2_185";
    if (decisionMakerRemediationCodes.length === 1) {
      const remediationCode = decisionMakerRemediationCodes[0];
      switch (remediationCode) {
        case SIGNATORY_MISSING_CODE:
          individualFormDefaultData.value = {
            signatoryQuestionnaire: { isSignatory: GuidanceQuestionValues.YES }
          };
          break;
        case DIRECTOR_MISSING_CODE:
          individualFormDefaultData.value = {
            uboQuestionnaire: {
              isDirector: GuidanceQuestionValues.YES,
              isOwner: null,
              isControllingPerson: null
            }
          };
          break;
      }
    }
    onNavigateToIndividual();
  };
  const editDecisionMaker = (decisionMaker) => {
    onNavigateToIndividual(decisionMaker.reference);
    userEvents.addTaskEvent("Clicked button", {
      ...getDecisionMakerTrackingParams(decisionMaker),
      actionType: "edit"
    });
  };
  const deleteDecisionMaker = async (decisionMaker) => {
    try {
      const updatedEntityAssociations = {
        entityAssociations: (legalEntity.entityAssociations ?? []).filter(
          (entityAssociation) => entityAssociation.legalEntityId !== decisionMaker.reference
        )
      };
      await updateLegalEntity.mutateAsync({ ...updatedEntityAssociations, id: legalEntity.id });
      const remainingDecisionMakers = decisionMakers.filter(
        (curr) => curr.legalEntityId !== decisionMaker.reference
      );
      userEvents.addTaskEvent("Clicked button", {
        ...getDecisionMakerTrackingParams(decisionMaker),
        actionType: "remove",
        remainingDecisionMakers
      });
      showToast({
        variant: "success",
        label: individualT(($) => $["successFullyRemovedDecisionMaker"])
      });
      closeDecisionMakerModal();
    } catch {
      showToast({ variant: "error", label: individualT(($) => $["failedToRemoveDecisionMaker"]) });
    }
  };
  const renderDecisionMakerItem = (decisionMaker) => {
    const description = getDecisionMakerDescription(decisionMaker.types, individualT);
    return /* @__PURE__ */ jsx(
      ListItem,
      {
        accessory: /* @__PURE__ */ jsx(TaskVerificationStatus, { status: decisionMaker.status }),
        avatar: { iconName: "user", circle: true },
        title: decisionMaker.name,
        action: { onClick: () => openDecisionMakerModal(decisionMaker), disclosure: true },
        description
      },
      decisionMaker.reference
    );
  };
  const renderDecisionMakersList = (decisionMakers2) => {
    if (decisionMakers2.length === 0) {
      return null;
    }
    return /* @__PURE__ */ jsx(List, { variant: "grouped-primary", padding: "small", dividers: false, children: decisionMakers2.map(renderDecisionMakerItem) });
  };
  const decisionMakerSections = useMemo(
    () => [
      {
        key: "actionNeeded",
        title: commonT(($) => $["actionNeeded"]),
        signatories: actionNeededSignatories,
        beneficialOwners: actionNeededBeneficialOwners
      },
      {
        key: "complete",
        title: commonT(($) => $["complete"]),
        signatories: completeSignatories,
        beneficialOwners: completeBeneficialOwners
      }
    ],
    [
      commonT,
      actionNeededSignatories,
      actionNeededBeneficialOwners,
      completeSignatories,
      completeBeneficialOwners
    ]
  );
  if (isRevampedDecisionMakersTaskPageEnabled && uniqueDecisionMakers.length === 0) {
    return /* @__PURE__ */ jsx(
      DecisionMakersGettingStarted,
      {
        handleCancelClick: () => navigateBackToTaskList(),
        addDecisionMakerOnClick
      }
    );
  }
  return /* @__PURE__ */ jsx(
    DropinLayout,
    {
      content: /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-decision-makers adyen-kyc-u-width-full", children: [
        isRevampedDecisionMakersTaskPageEnabled ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsxs(StackLayout, { gap: "medium", children: [
            /* @__PURE__ */ jsx(
              Header,
              {
                title: individualT(($) => $["ownersAndDecisionMakers"]),
                description: individualT(($) => $["ownersAndDecisionMakersDescription"]),
                status: getTaskStatus(TaskTypes.DECISION_MAKER_OVERVIEW),
                align: "center",
                children: /* @__PURE__ */ jsx(Button, { slot: "actions", variant: "link", onClick: openModal, children: commonT(($) => $["learnMore"]) })
              }
            ),
            showWarning && /* @__PURE__ */ jsx(
              RemediationAlerts,
              {
                activeCodes: decisionMakerRemediationCodes,
                onAction: onRemediationAction
              }
            )
          ] }),
          /* @__PURE__ */ jsxs(StackLayout, { gap: "small", children: [
            decisionMakerSections.map((section) => {
              if (section.signatories.length === 0 && section.beneficialOwners.length === 0) {
                return null;
              }
              return /* @__PURE__ */ jsx(List, { padding: "none", dividers: false, header: section.title, children: /* @__PURE__ */ jsxs(StackLayout, { gap: "small", children: [
                renderDecisionMakersList(section.signatories),
                renderDecisionMakersList(section.beneficialOwners)
              ] }) }, section.key);
            }),
            /* @__PURE__ */ jsx(List, { variant: "grouped-primary", padding: "small", dividers: false, children: /* @__PURE__ */ jsx(
              ListItem,
              {
                avatar: { iconName: "plus", circle: true },
                title: commonT(($) => $["addNew"]),
                action: { onClick: addDecisionMakerOnClick }
              }
            ) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "secondary",
                onClick: () => {
                  userEvents.addTaskEvent("Clicked button", {
                    task: TaskTypes.DECISION_MAKER_OVERVIEW,
                    actionType: "back",
                    label: translationKeys.home,
                    noOfDecisionMakers: decisionMakers.length
                  });
                  navigateBackToTaskList();
                },
                fullWidth: true,
                children: commonT(($) => $[translationKeys.home])
              }
            )
          ] })
        ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Header,
            {
              title: commonT(($) => $["decisionMaker"]),
              description: individualT(($) => $["decisionMakerDescription"])
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "adyen-kyc-decision-makers__container", children: availableDecisionMakers.map(({ roleType, min }) => /* @__PURE__ */ jsx(
            EntityGuidanceStatus,
            {
              country: registeredCountry,
              currentTask: TaskTypes.DECISION_MAKER_OVERVIEW,
              entityLabel: roleType,
              status: iconStatus(uniqueDecisionMakersPerType(roleType), min)
            },
            roleType
          )) }),
          /* @__PURE__ */ jsx(
            ContextGuidance,
            {
              title: individualT(($) => $["whatIsTheDifferenceBetweenTheseRoles"]),
              content: /* @__PURE__ */ jsx("ul", { className: "adyen-kyc-guidance-list", children: availableDecisionMakers.map(({ roleType }) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(
                Trans,
                {
                  t: individualT,
                  i18nKey: ($) => $[`${roleType === DecisionMakerTypes.CONTROLLING_PERSON ? "controllingPerson" : roleType === DecisionMakerTypes.OWNER ? "owner" : roleType}GuideDescription`]
                }
              ) }, roleType)) }),
              titleId: "whatIsTheDifferenceBetweenTheseRoles",
              contentId: "differenceBetweenAnOwnerControllingPersonAndSignatory"
            }
          ),
          showWarning && /* @__PURE__ */ jsx(
            Alert,
            {
              className: "adyen-kyc-decision-makers__warning",
              title: remediationMessages.DECISION_MAKER,
              variant: "warning"
            }
          ),
          /* @__PURE__ */ jsxs(StackLayout, { children: [
            uniqueDecisionMakers.map((decisionMaker) => /* @__PURE__ */ jsx(
              EntityAssociation,
              {
                types: decisionMaker.types,
                name: decisionMaker.name,
                status: decisionMaker.status,
                onNavigateToEntity: () => editDecisionMaker(decisionMaker),
                problems: decisionMaker?.problems,
                deleteEntity: () => {
                  deleteDecisionMaker(decisionMaker);
                },
                isDeleteDisabled: (trustedEntityAssociations ?? []).some(
                  (ea) => ea.reference === decisionMaker.reference
                )
              },
              decisionMaker.reference
            )),
            /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-decision-makers__actions", children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "secondary",
                  icon: "plus",
                  onClick: addDecisionMakerOnClick,
                  disabled: haveMaxDecisionMakers,
                  fullWidth: true,
                  children: individualT(($) => $["addDecisionMaker"])
                }
              ),
              /* @__PURE__ */ jsx(
                ActionBar,
                {
                  onHome: () => {
                    userEvents.addTaskEvent("Clicked button", {
                      task: TaskTypes.DECISION_MAKER_OVERVIEW,
                      actionType: "back",
                      label: translationKeys.home,
                      noOfDecisionMakers: decisionMakers.length
                    });
                    navigateBackToTaskList();
                  },
                  homeButtonLabel: commonT(($) => $[translationKeys.home])
                }
              )
            ] })
          ] })
        ] }),
        showDecisionMakerModal && selectedDecisionMaker && /* @__PURE__ */ jsx(
          DecisionMakerDetails,
          {
            handleClose: closeDecisionMakerModal,
            handleDelete: () => deleteDecisionMaker(selectedDecisionMaker),
            handleEdit: () => editDecisionMaker(selectedDecisionMaker),
            decisionMaker: selectedDecisionMaker,
            parentLegalEntity: legalEntity
          }
        ),
        isModalOpen && /* @__PURE__ */ jsx(
          Modal,
          {
            onClose: closeModal,
            ariaLabel: individualT(($) => $["moreAboutOwnersAndDecisionMakers"]),
            inset: true,
            children: /* @__PURE__ */ jsx(DecisionMakersModalContent, {})
          }
        )
      ] })
    }
  );
};
export {
  DecisionMakers
};
