;
{
  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] = "f086a946-32f9-4cbe-8482-893d8c52d9c5", e._sentryDebugIdIdentifier = "sentry-dbid-f086a946-32f9-4cbe-8482-893d8c52d9c5");
  } catch (e) {
  }
}
;
import { b as useApiContext, $ as httpPost, k as httpGet, a3 as createLogger, u as useTranslation, p as useAnalyticsContext, v as useExperimentsContext, ah as getLanguageCode, V as Button, o as LegalEntityTypes, P as getOwnSignatories, N as doesLegalEntityRequiresLegalRepresentative, O as getLegalRepresentative, a as addResourceBundles, c as useLegalEntity, L as Loader, j as TaskTypes, R as ROOT_LE, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsx, jsxs, Fragment } from "preact/jsx-runtime";
import { useState, useEffect, useCallback } from "preact/hooks";
import { useMutation, useQuery, skipToken } from "@tanstack/preact-query";
import { a as useInvalidateRootLegalEntity, u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { u as useTermsOfServiceStatus, a as useTermsOfServiceAcceptanceInfos } from "./useTermsOfServiceStatus-BV9TFHKl.js";
import { C as Checkbox } from "./Checkbox-CyQM2V4n.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { L as LoaderWrapper } from "./LoaderWrapper-Dr1uK-LS.js";
import { M as MaybeModal } from "./MaybeModal-C21jAgAp.js";
import { P as ProgressBar } from "./ProgressBar-B7gTQncy.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { E as EndStateLayout } from "./EndStateLayout-BNxISx6G.js";
import { a as Alert } from "./Alert-CpDg47bv.js";
import { F as FormNavigation } from "./FormNavigation-BJzGPCsX.js";
import { d as downloadFile } from "./file-CiG1D0zy.js";
import { g as getLegalEntityNameBasedOnType } from "./getName-CiCWopsp.js";
import { l as localizeDateString } from "./localizeDateString-pCDWhd0r.js";
import { C as ContractViewer } from "./ContractViewer-DcQHIGMU.js";
const acceptTermsOfService = async (legalEntityId, baseUrl, termsOfServiceDocumentId, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/termsOfService/accept`
    },
    {
      ...data,
      legalEntityReference: legalEntityId,
      termsOfServiceDocumentId
    }
  );
};
const useAcceptTermsOfService = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  const invalidateRootLegalEntity = useInvalidateRootLegalEntity();
  return useMutation({
    mutationFn: (data) => acceptTermsOfService(
      rootLegalEntityId.value,
      baseUrl.value,
      data.termsOfServiceDocumentId,
      data
    ),
    onSuccess: async () => {
      await invalidateRootLegalEntity();
    },
    ...options
  });
};
const getAcceptedTermsOfService = async (legalEntityId, baseUrl, termsOfServiceAcceptanceReference, documentFormat) => {
  return httpGet({
    baseUrl,
    path: `legalEntities/${legalEntityId}/termsOfService/acceptedTermsOfServiceDocument/${termsOfServiceAcceptanceReference}?documentformat=${documentFormat} `
  });
};
const useAcceptedTermsOfService = (termsOfServiceAcceptanceReference, documentFormat, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["acceptedTermsOfService", termsOfServiceAcceptanceReference, documentFormat],
    queryFn: termsOfServiceAcceptanceReference ? () => getAcceptedTermsOfService(
      rootLegalEntityId.value,
      baseUrl.value,
      termsOfServiceAcceptanceReference,
      documentFormat
    ) : skipToken,
    ...options
  });
};
const getTermsOfService = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/termsOfService`
    },
    data
  );
};
const useTermsOfService = (data, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["termsOfService", data],
    queryFn: () => getTermsOfService(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const tosSignedAlert = "adyen-kyc-tos-signed-alert";
const tosContainer = "adyen-kyc-tos-container";
const tosContent = "adyen-kyc-tos-content";
const tosActions = "adyen-kyc-tos-actions";
const styles = {
  tosSignedAlert,
  tosContainer,
  tosContent,
  tosActions
};
const logger$1 = createLogger();
const FALLBACK_LANGUAGE_CODE$1 = "en";
const useServiceAgreement = ({
  handleServiceAgreementIsNotAvailableInThatLanguage,
  acceptanceId,
  serviceAgreementType,
  language
}) => {
  const [agreementLanguage, setAgreementLanguage] = useState(language);
  useEffect(() => {
    if (agreementLanguage !== language) {
      setAgreementLanguage(language);
    }
  }, [language]);
  const {
    data: unAcceptedServiceAgreement,
    isSuccess: isUnAcceptedServiceAgreementSuccess,
    isError,
    error
  } = useTermsOfService(
    {
      language: agreementLanguage,
      type: serviceAgreementType,
      termsOfServiceDocumentFormat: "JSON"
    },
    { enabled: !acceptanceId }
  );
  const { data: acceptedServiceAgreement, isSuccess: isAcceptedServiceAgreementSuccess } = useAcceptedTermsOfService(acceptanceId, "JSON");
  if (isUnAcceptedServiceAgreementSuccess || isAcceptedServiceAgreementSuccess) {
    const termsOfService = unAcceptedServiceAgreement ?? acceptedServiceAgreement;
    const documentId = unAcceptedServiceAgreement?.termsOfServiceDocumentId ?? acceptedServiceAgreement?.termsOfServiceAcceptanceReference;
    if (termsOfService?.document && documentId) {
      const contract = JSON.parse(
        decodeURIComponent(escape(window.atob(termsOfService.document)))
      );
      return {
        loading: "success",
        serviceAgreement: {
          id: documentId,
          contract
        }
      };
    }
  }
  if (isError) {
    if (agreementLanguage !== FALLBACK_LANGUAGE_CODE$1) {
      handleServiceAgreementIsNotAvailableInThatLanguage();
      setAgreementLanguage(FALLBACK_LANGUAGE_CODE$1);
    } else {
      logger$1.error(error);
    }
    return {
      loading: "success",
      serviceAgreement: void 0
    };
  }
  return {
    loading: "loading",
    serviceAgreement: void 0
  };
};
const serviceAgreementValidationRules = {
  signer: { modes: ["blur"], validate: (signer) => !!signer, errorMessage: "fieldIsRequired" },
  acceptServiceAgreement: {
    modes: ["blur"],
    validate: (acceptServiceAgreement) => !!acceptServiceAgreement,
    errorMessage: "fieldIsRequired"
  }
};
const serviceAgreementTypesTranslationMapping = {
  adyenForPlatformsManage: "paymentProcessingTerms",
  adyenIssuing: "accountHolderTerms",
  adyenForPlatformsAdvanced: "paymentProcessingTerms",
  adyenCapital: "capitalUserTerms",
  adyenAccount: "businessAccountTerms",
  adyenCard: "cardUserTerms",
  adyenFranchisee: "franchiseesTAndCs",
  adyenPccr: "pccr",
  adyenChargeCard: "chargeCardUserAgreement"
};
const logger = createLogger();
const FALLBACK_LANGUAGE_CODE = "en";
function ServiceAgreementDropin({
  legalEntityResponse,
  handleAddSigner,
  handleSign,
  serviceAgreementTypes,
  serviceAgreementAcceptanceInfos,
  asEmbedded = false,
  asModal = false,
  handleCloseClick,
  showInitialBackButton = false,
  onComplete
}) {
  const { t, i18n } = useTranslation(["contract", "common"]);
  const userEvents = useAnalyticsContext();
  const { showToast } = useToastContext();
  const { isExperimentEnabled } = useExperimentsContext();
  const isAgeVerificationEnabled = isExperimentEnabled("EnableAgeVerification");
  const { rootLegalEntityId, baseUrl } = useApiContext();
  const [loadingStatus, setLoadingStatus] = useState();
  const signedForms = serviceAgreementAcceptanceInfos.map((serviceAgreementAcceptanceInfo) => ({
    formId: serviceAgreementAcceptanceInfo.id,
    serviceAgreementType: serviceAgreementAcceptanceInfo.type,
    acceptanceId: serviceAgreementAcceptanceInfo.id,
    createdAt: serviceAgreementAcceptanceInfo.createdAt,
    formName: serviceAgreementTypesTranslationMapping[serviceAgreementAcceptanceInfo.type],
    isValid: true
  }));
  const formsToBeSigned = serviceAgreementTypes.map((serviceAgreementType) => ({
    formId: serviceAgreementType,
    serviceAgreementType,
    formName: serviceAgreementTypesTranslationMapping[serviceAgreementType],
    isValid: false
  }));
  const forms = [...signedForms, ...formsToBeSigned];
  const [activeFormIndex, setActiveFormIndex] = useState(0);
  const [activeForm, setActiveForm] = useState(forms[activeFormIndex]);
  const [hasFinished, setHasFinished] = useState(false);
  const canSign = serviceAgreementTypes.includes(activeForm.serviceAgreementType) && !activeForm.acceptanceId;
  const isFirstStep = activeFormIndex === 0;
  const isLastStep = activeFormIndex === forms.length - 1;
  const showSignedAlert = !!activeForm.acceptanceId;
  const { refetch: downloadAcceptedTermsAsPdf } = useAcceptedTermsOfService(
    activeForm.acceptanceId,
    "PDF",
    {
      enabled: false
    }
  );
  const handleServiceAgreementIsNotAvailableInThatLanguage = useCallback(() => {
    showToast({
      label: t(($) => $["failedToGetServiceAgreementInSelectedLanguageFallbackToEn"]),
      variant: "error"
    });
  }, [t, showToast]);
  const { loading: contractLoadingStatus, serviceAgreement } = useServiceAgreement({
    handleServiceAgreementIsNotAvailableInThatLanguage,
    acceptanceId: activeForm.acceptanceId,
    serviceAgreementType: activeForm.serviceAgreementType,
    language: getLanguageCode(i18n.language)
  });
  const { handleChangeFor, triggerValidation, data, valid, isValid, errors } = useForm({
    schema: ["signer", "acceptServiceAgreement"],
    rules: serviceAgreementValidationRules
  });
  const getSigners = () => {
    if (legalEntityResponse.type === LegalEntityTypes.ORGANIZATION) {
      return getOwnSignatories(legalEntityResponse).map(({ legalEntityId: id, name }) => ({
        id: id ?? "",
        name: name ?? ""
      }));
    }
    if (isAgeVerificationEnabled && doesLegalEntityRequiresLegalRepresentative(legalEntityResponse)) {
      const legalRepresentative = getLegalRepresentative(legalEntityResponse);
      return legalRepresentative ? [{ id: legalRepresentative.legalEntityId, name: legalRepresentative.name }] : [];
    }
    return [
      {
        id: legalEntityResponse.id,
        name: `${legalEntityResponse.individual?.name.firstName ?? ""} ${legalEntityResponse.individual?.name.lastName ?? ""}`
      }
    ];
  };
  const signers = getSigners();
  const handleSignClick = async () => {
    const baseTracking = {
      actionType: "sign"
    };
    triggerValidation();
    if (loadingStatus === "loading" || !serviceAgreement || !data.signer) return;
    if (isValid) {
      try {
        setLoadingStatus("loading");
        await handleSign(legalEntityResponse.id, serviceAgreement.id, { acceptedBy: data.signer });
        setLoadingStatus("success");
        showToast({
          label: t(($) => $["serviceAgreementSignedSuccessfully"]),
          variant: "success"
        });
        userEvents.addTaskEvent("Success", baseTracking);
        data.acceptServiceAgreement = false;
        data.signer = void 0;
      } catch (e) {
        setLoadingStatus("success");
        showToast({ label: t(($) => $["signingFailed"]), variant: "error" });
        userEvents.addTaskEvent("Encountered error", {
          ...baseTracking,
          returnType: e?.errorCode || "backend",
          returnValue: e?.title ?? e?.message
        });
      }
    } else {
      userEvents.addTaskEvent("Encountered error", {
        ...baseTracking,
        returnType: "validation",
        returnValue: Object.entries(valid).filter(([, value]) => !value).map(([key]) => key)
      });
    }
  };
  const handleExpandSection = useCallback((title) => {
    userEvents.addFieldEvent("Clicked accordion", {
      actionType: "open",
      field: title
    });
  }, []);
  useEffect(() => {
    if (!serviceAgreementAcceptanceInfos.length) return;
    gotoForm(serviceAgreementAcceptanceInfos.length - 1);
  }, [serviceAgreementAcceptanceInfos]);
  useEffect(() => {
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
    const initialFormIndex = forms.length === signedForms.length ? 0 : signedForms.length;
    gotoForm(initialFormIndex);
  }, []);
  useEffect(() => {
    userEvents.updateSharedEventProperties({ page: activeForm?.formName });
  }, [activeForm]);
  const gotoForm = (index) => {
    setActiveForm(forms[index]);
    setActiveFormIndex(index);
  };
  const onDownloadAcceptedTermsOfServiceDocument = async () => {
    const { isError, isSuccess, data: data2 } = await downloadAcceptedTermsAsPdf();
    if (isSuccess && data2.document) {
      await downloadFile(
        data2.document,
        `${t(($) => $[activeForm.formName], { ns: "common" })}.pdf`
      );
    }
    if (isError) {
      showToast({
        label: t(($) => $["failedToDownloadAcceptedServiceAgreementDocument"]),
        variant: "error"
      });
    }
  };
  const onDownloadUnacceptedTermsOfServiceDocument = async () => {
    const languageCode = getLanguageCode(i18n.language);
    const requestAndDownload = async (languageCode2) => {
      const response = await getTermsOfService(rootLegalEntityId.value, baseUrl.value, {
        type: activeForm.serviceAgreementType,
        language: languageCode2,
        termsOfServiceDocumentFormat: "PDF"
      });
      if (!response.document) {
        throw new Error(`No terms Of service document found in response`);
      }
      await downloadFile(
        response.document,
        `${t(($) => $[activeForm.formName], { ns: "common" })}.pdf`
      );
    };
    try {
      const availableLanguages = ["fr", "en"];
      if (availableLanguages.includes(i18n.language)) {
        await requestAndDownload(languageCode);
      }
      await requestAndDownload("en");
    } catch {
      if (languageCode !== FALLBACK_LANGUAGE_CODE) {
        await requestAndDownload(FALLBACK_LANGUAGE_CODE).catch(logger.error);
        return;
      }
      showToast({
        label: t(($) => $["failedToDownloadServiceAgreementDocument"]),
        variant: "error"
      });
    }
  };
  const isIndividual = legalEntityResponse.type === "individual";
  const addSignerAlert = handleAddSigner && /* @__PURE__ */ jsx(
    Alert,
    {
      variant: signers.length ? "info" : "warning",
      className: "adyen-kyc-u-margin-top-16",
      title: t(($) => $[signers.length ? "isYourNameMissingFromSigners" : "thereAreNoSigners"]),
      children: /* @__PURE__ */ jsx(Button, { onClick: handleAddSigner, variant: "link", children: t(($) => $["addYourselfAsSigner"]) })
    }
  );
  const getSignedName = (acceptanceId) => {
    if (!acceptanceId) return "";
    const signatory = serviceAgreementAcceptanceInfos.find(({ id }) => id === acceptanceId);
    const legalEntitySignatory = legalEntityResponse.entityAssociations?.find(
      ({ legalEntityId }) => legalEntityId === signatory?.acceptedBy
    );
    return legalEntitySignatory?.name ?? getLegalEntityNameBasedOnType(legalEntityResponse);
  };
  const signedAlert = showSignedAlert && /* @__PURE__ */ jsx(
    Alert,
    {
      variant: "success",
      className: styles.tosSignedAlert,
      title: t(($) => $["signedByOn"], {
        date: localizeDateString(activeForm.createdAt, i18n.language) ?? "",
        signer: getSignedName(activeForm.acceptanceId)
      })
    }
  );
  const sidebar = /* @__PURE__ */ jsx(
    LoaderWrapper,
    {
      status: loadingStatus,
      formOpacityWhenLoading: 0.3,
      showSpinner: false,
      className: "adyen-kyc-dropin__sidebar-wrapper",
      children: /* @__PURE__ */ jsx(
        FormNavigation,
        {
          forms,
          activeForm,
          gotoForm,
          taskName: "signServiceAgreement",
          className: "adyen-kyc-u-margin-bottom-24"
        }
      )
    }
  );
  const content = /* @__PURE__ */ jsxs(
    LoaderWrapper,
    {
      status: loadingStatus,
      formOpacityWhenLoading: 0.3,
      showSpinner: false,
      className: "adyen-kyc-form-container",
      children: [
        /* @__PURE__ */ jsxs(
          LoaderWrapper,
          {
            status: contractLoadingStatus,
            formOpacityWhenLoading: 0.3,
            showSpinner: false,
            children: [
              serviceAgreement && /* @__PURE__ */ jsxs(Fragment, { children: [
                signedAlert,
                /* @__PURE__ */ jsx(
                  ContractViewer,
                  {
                    contract: serviceAgreement.contract,
                    onExpandSection: handleExpandSection,
                    showSectionNumbering: true
                  }
                ),
                /* @__PURE__ */ jsx("div", { className: "adyen-kyc-u-margin-top-16", children: signedAlert }),
                /* @__PURE__ */ jsx("div", { className: "adyen-kyc-u-margin-y-16", children: /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "secondary",
                    onClick: activeForm?.acceptanceId ? onDownloadAcceptedTermsOfServiceDocument : onDownloadUnacceptedTermsOfServiceDocument,
                    icon: "download",
                    children: t(($) => $["downloadAsPdf"])
                  }
                ) })
              ] }),
              !forms.length && /* @__PURE__ */ jsx(Alert, { variant: "info", title: t(($) => $["nothingNeedsToBeSigned"]) })
            ]
          }
        ),
        canSign && /* @__PURE__ */ jsxs(Fragment, { children: [
          !!signers.length && /* @__PURE__ */ jsx(
            Field,
            {
              name: "signer",
              label: t(($) => $["signer"]),
              className: "adyen-kyc-u-margin-top-32 adyen-kyc-u-width-half",
              errorMessage: errors.signer?.errorMessage,
              isValid: valid.signer,
              dataTestId: "signer",
              children: (childProps) => /* @__PURE__ */ jsx(
                Select,
                {
                  ...childProps,
                  onChange: handleChangeFor("signer", "blur"),
                  name: "signer",
                  placeholder: t(($) => $["selectSigner"]),
                  selected: data.signer,
                  items: signers
                }
              )
            }
          ),
          !isIndividual && addSignerAlert,
          /* @__PURE__ */ jsx(
            Field,
            {
              name: "acceptServiceAgreement",
              className: "adyen-kyc-u-margin-top-16",
              errorMessage: errors.acceptServiceAgreement?.errorMessage,
              isValid: valid.acceptServiceAgreement,
              children: (childProps) => /* @__PURE__ */ jsx(
                Checkbox,
                {
                  ...childProps,
                  label: t(($) => $["iHaveReadAndIAcceptTheseTerms"]),
                  checked: data.acceptServiceAgreement ?? false,
                  name: "acceptServiceAgreement",
                  onChange: handleChangeFor("acceptServiceAgreement")
                }
              )
            }
          )
        ] })
      ]
    }
  );
  const currentStep = signedForms.length;
  const totalSteps = forms.length;
  const handleClick = () => {
    if (canSign) {
      handleSignClick();
    } else if (!isLastStep) {
      gotoForm(activeFormIndex + 1);
    } else {
      setHasFinished(true);
    }
  };
  const handleFinishClick = () => {
    handleCloseClick();
    onComplete?.();
  };
  const endScreen = hasFinished && /* @__PURE__ */ jsx(
    EndStateLayout,
    {
      title: t(($) => $["serviceAgreementSignedAndDated"]),
      action: /* @__PURE__ */ jsx(Button, { onClick: handleFinishClick, fullWidth: true, children: t(($) => $["finish"], { ns: "common" }) })
    }
  );
  const progress = Math.floor(currentStep / (totalSteps - 1) * 100);
  return /* @__PURE__ */ jsx(MaybeModal, { inline: !asModal, onClose: handleCloseClick, children: /* @__PURE__ */ jsxs("div", { className: styles.tosContainer, children: [
    /* @__PURE__ */ jsxs("article", { className: styles.tosContent, children: [
      !asEmbedded && sidebar,
      endScreen || content
    ] }),
    !hasFinished && /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(
        ProgressBar,
        {
          ariaLabel: t(($) => $["progress"], { ns: "common" }),
          progress
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: styles.tosActions, children: [
        isFirstStep ? showInitialBackButton && /* @__PURE__ */ jsx(Button, { onClick: handleCloseClick, variant: "secondary", children: t(($) => $["cancel"], { ns: "common" }) }) : /* @__PURE__ */ jsx(
          Button,
          {
            icon: "chevron-left",
            onClick: () => {
              gotoForm(activeFormIndex - 1);
            },
            variant: "secondary",
            children: t(($) => $["back"], { ns: "common" })
          }
        ),
        /* @__PURE__ */ jsx(Button, { variant: canSign ? "primary" : "secondary", onClick: handleClick, children: canSign ? t(($) => $["signAndContinue"]) : t(($) => $["continue"], { ns: "common" }) })
      ] })
    ] })
  ] }) });
}
function AcceptTermsOfServiceComponent({
  legalEntityId,
  modalView = false,
  asEmbedded = true,
  /* triggered when X button clicked, or at the end, on Finish button click */
  onClose,
  onComplete,
  onUnmount,
  /* triggered on every document signed, typically multiple times */
  onAccept,
  handleAddSigner
}) {
  if (!legalEntityId) {
    throw new Error("Must provide at-least a legalEntityId");
  }
  const { i18n } = useTranslation();
  addResourceBundles(i18n, [
    { ns: "common", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../../../language/locales/bg-BG.json": () => import("./bg-BG-6XzbmxcW.js"), "../../../language/locales/cs-CZ.json": () => import("./cs-CZ-C6vEQ8P9.js"), "../../../language/locales/da-DK.json": () => import("./da-DK-DzcTI92X.js"), "../../../language/locales/de-DE.json": () => import("./de-DE-dPfrbCii.js"), "../../../language/locales/el-GR.json": () => import("./el-GR-Dazirlmt.js"), "../../../language/locales/en-US.instructions.json": () => import("./en-US.instructions-Ddr7AO05.js"), "../../../language/locales/en-US.json": () => import("./StoreProvider-CqQrndhS.js").then((n) => n.bF), "../../../language/locales/es-ES.json": () => import("./es-ES--IvNed_Q.js"), "../../../language/locales/et-EE.json": () => import("./et-EE-CsTXSlnY.js"), "../../../language/locales/fi-FI.json": () => import("./fi-FI-BUixKfXH.js"), "../../../language/locales/fr-FR.json": () => import("./fr-FR-BM-qNLci.js"), "../../../language/locales/hr-HR.json": () => import("./hr-HR-BF74vdPD.js"), "../../../language/locales/hu-HU.json": () => import("./hu-HU-DYhMVR_c.js"), "../../../language/locales/it-IT.json": () => import("./it-IT-D63gRTDc.js"), "../../../language/locales/ja-JP.json": () => import("./ja-JP-DL0IjTzn.js"), "../../../language/locales/lt-LT.json": () => import("./lt-LT-BX8dOAzK.js"), "../../../language/locales/lv-LV.json": () => import("./lv-LV-dA8yYdKe.js"), "../../../language/locales/nl-NL.json": () => import("./nl-NL-KQ6bciOb.js"), "../../../language/locales/no-NO.json": () => import("./no-NO-Ds3VioxT.js"), "../../../language/locales/pl-PL.json": () => import("./pl-PL-BgbxWHGE.js"), "../../../language/locales/pt-BR.json": () => import("./pt-BR-Ct4s4jXV.js"), "../../../language/locales/pt-PT.json": () => import("./pt-PT-DBEsmXQX.js"), "../../../language/locales/ro-RO.json": () => import("./ro-RO-C00Ig8CL.js"), "../../../language/locales/sk-SK.json": () => import("./sk-SK-BbJWayDh.js"), "../../../language/locales/sl-SI.json": () => import("./sl-SI-hxwQIw_i.js"), "../../../language/locales/sv-SE.json": () => import("./sv-SE-0PQ-U1u6.js") }), `../../../language/locales/${lang}.json`, 6) },
    { ns: "contract", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../../Contract/language/bg-BG.json": () => import("./bg-BG-K7feXvEc.js"), "../../Contract/language/cs-CZ.json": () => import("./cs-CZ-CYQO0o5V.js"), "../../Contract/language/da-DK.json": () => import("./da-DK-CGWvmdkq.js"), "../../Contract/language/de-DE.json": () => import("./de-DE-DHDJhahG.js"), "../../Contract/language/el-GR.json": () => import("./el-GR-DHNlnOwf.js"), "../../Contract/language/en-US.json": () => import("./en-US-DoiQhi0j.js"), "../../Contract/language/es-ES.json": () => import("./es-ES-CxnsKEh4.js"), "../../Contract/language/et-EE.json": () => import("./et-EE-BQixWUEV.js"), "../../Contract/language/fi-FI.json": () => import("./fi-FI-57-xkioo.js"), "../../Contract/language/fr-FR.json": () => import("./fr-FR-BxiX8Zfi.js"), "../../Contract/language/hr-HR.json": () => import("./hr-HR-BynZTNSB.js"), "../../Contract/language/hu-HU.json": () => import("./hu-HU-BtRIDozk.js"), "../../Contract/language/it-IT.json": () => import("./it-IT-masgjk9F.js"), "../../Contract/language/ja-JP.json": () => import("./ja-JP-vv3-YsHU.js"), "../../Contract/language/lt-LT.json": () => import("./lt-LT-2BMif2Bk.js"), "../../Contract/language/lv-LV.json": () => import("./lv-LV-CHdEDRVO.js"), "../../Contract/language/nl-NL.json": () => import("./nl-NL-D1b5RUJ0.js"), "../../Contract/language/no-NO.json": () => import("./no-NO-Dkh4SWbB.js"), "../../Contract/language/pl-PL.json": () => import("./pl-PL-BkGihn5Q.js"), "../../Contract/language/pt-BR.json": () => import("./pt-BR-BRdIEO2O.js"), "../../Contract/language/pt-PT.json": () => import("./pt-PT-BfL7qUzo.js"), "../../Contract/language/ro-RO.json": () => import("./ro-RO-C2yBVFht.js"), "../../Contract/language/sk-SK.json": () => import("./sk-SK-C74EF23u.js"), "../../Contract/language/sl-SI.json": () => import("./sl-SI-CvUzNn9Z.js"), "../../Contract/language/sv-SE.json": () => import("./sv-SE-BsLkPEzn.js") }), `../../Contract/language/${lang}.json`, 5) },
    { ns: "ui", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "../../ui/language/bg-BG.json": () => import("./bg-BG-zZhDshGi.js"), "../../ui/language/cs-CZ.json": () => import("./cs-CZ-Ck22NTT9.js"), "../../ui/language/da-DK.json": () => import("./da-DK-DQ4ZYSea.js"), "../../ui/language/de-DE.json": () => import("./de-DE-CkbOZ6S_.js"), "../../ui/language/el-GR.json": () => import("./el-GR-DudORw4U.js"), "../../ui/language/en-US.json": () => import("./en-US-CjjPhkB5.js"), "../../ui/language/es-ES.json": () => import("./es-ES-BAolMrZ0.js"), "../../ui/language/et-EE.json": () => import("./et-EE-BOIrYrz9.js"), "../../ui/language/fi-FI.json": () => import("./fi-FI-D8WrLxxq.js"), "../../ui/language/fr-FR.json": () => import("./fr-FR-Beljeilc.js"), "../../ui/language/hr-HR.json": () => import("./hr-HR-lIHN6Yl2.js"), "../../ui/language/hu-HU.json": () => import("./hu-HU-CWdwNCev.js"), "../../ui/language/it-IT.json": () => import("./it-IT-5a7NHVFo.js"), "../../ui/language/ja-JP.json": () => import("./ja-JP-DSvZhFNY.js"), "../../ui/language/lt-LT.json": () => import("./lt-LT-CgalYpUh.js"), "../../ui/language/lv-LV.json": () => import("./lv-LV-aAd9SEqx.js"), "../../ui/language/nl-NL.json": () => import("./nl-NL-CmURERx_.js"), "../../ui/language/no-NO.json": () => import("./no-NO-qyqWODMp.js"), "../../ui/language/pl-PL.json": () => import("./pl-PL-q9azN24o.js"), "../../ui/language/pt-BR.json": () => import("./pt-BR-BxoOF8jB.js"), "../../ui/language/pt-PT.json": () => import("./pt-PT-pIChDwiI.js"), "../../ui/language/ro-RO.json": () => import("./ro-RO-DRsaNX9j.js"), "../../ui/language/sk-SK.json": () => import("./sk-SK-7-enbO1N.js"), "../../ui/language/sl-SI.json": () => import("./sl-SI-DTvJT7fC.js"), "../../ui/language/sv-SE.json": () => import("./sv-SE-N-Hqwcjq.js") }), `../../ui/language/${lang}.json`, 5) }
  ]);
  const [stepsData, setStepsData] = useState({
    unAcceptedTermsOfServiceTypes: [],
    acceptedTermsOfServices: []
  });
  const { data: legalEntity } = useLegalEntity(ROOT_LE);
  const { data: serviceAgreementStatus, isLoading: isStatusLoading } = useTermsOfServiceStatus();
  const { data: serviceAgreementAcceptanceInfos, isLoading: isAcceptanceInfoLoading } = useTermsOfServiceAcceptanceInfos();
  const { mutateAsync: acceptTermsOfService2 } = useAcceptTermsOfService();
  const handleOnClose = () => {
    if (modalView) {
      onUnmount?.();
    }
    onClose?.();
  };
  const handleSign = useCallback(
    async (legalEntityId2, termsOfServiceDocumentId, signedBy) => {
      const acceptedTermsOfService = await acceptTermsOfService2({
        acceptedBy: signedBy.acceptedBy,
        legalEntityReference: legalEntityId2,
        termsOfServiceDocumentId
      });
      const paramAllowList = {
        type: acceptedTermsOfService.type,
        acceptedBy: acceptedTermsOfService.acceptedBy,
        id: acceptedTermsOfService.id,
        language: acceptedTermsOfService.language,
        termsOfServiceDocumentId: acceptedTermsOfService.termsOfServiceDocumentId
      };
      const { acceptedTermsOfServices } = stepsData;
      acceptedTermsOfServices.push(paramAllowList);
      const unAcceptedTos = serviceAgreementStatus?.termsOfServiceTypes?.filter(
        (tosType) => tosType !== acceptedTermsOfService.type
      ) ?? [];
      const newStepsData = {
        unAcceptedTermsOfServiceTypes: unAcceptedTos,
        acceptedTermsOfServices
      };
      setStepsData(newStepsData);
      onAccept?.(newStepsData);
    },
    [onAccept, stepsData, acceptTermsOfService2, serviceAgreementStatus?.termsOfServiceTypes]
  );
  const handleOnComplete = () => {
    onComplete?.(stepsData);
  };
  return isStatusLoading || isAcceptanceInfoLoading || !legalEntity ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsx(
    ServiceAgreementDropin,
    {
      taskType: TaskTypes.SERVICE_AGREEMENT,
      legalEntityResponse: legalEntity,
      serviceAgreementTypes: serviceAgreementStatus?.termsOfServiceTypes ?? [],
      serviceAgreementAcceptanceInfos: serviceAgreementAcceptanceInfos?.data ?? [],
      handleSign,
      asEmbedded,
      asModal: modalView,
      handleCloseClick: handleOnClose,
      showInitialBackButton: !!onClose,
      onComplete: handleOnComplete,
      handleAddSigner
    }
  );
}
export {
  AcceptTermsOfServiceComponent
};
