;
{
  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] = "7ca4988d-8c7f-48ba-9d71-e21455c3b1cc", e._sentryDebugIdIdentifier = "sentry-dbid-7ca4988d-8c7f-48ba-9d71-e21455c3b1cc");
  } catch (e) {
  }
}
;
import { b as useApiContext, $ as httpPost, ai as isEmpty, u as useTranslation, p as useAnalyticsContext, aj as getOwnDecisionMakers, o as LegalEntityTypes, j as TaskTypes, V as Button, a as addResourceBundles, c as useLegalEntity, L as Loader, R as ROOT_LE, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsxs, Fragment, jsx } from "preact/jsx-runtime";
import { useState, useCallback, useEffect, useMemo } from "preact/hooks";
import { u as useSalesChannels, a as usePciStatus } from "./useSalesChannels-AHAIg4Dn.js";
import { useQuery, useMutation } from "@tanstack/preact-query";
import { a as useInvalidateRootLegalEntity, u as useToastContext } from "./useToastContext-CPvuqSMm.js";
import { M as MaybeModal } from "./MaybeModal-C21jAgAp.js";
import { E as EndStateLayout } from "./EndStateLayout-BNxISx6G.js";
import { C as Card } from "./Card-OQuFzmxm.js";
import { C as Checkbox } from "./Checkbox-CyQM2V4n.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { D as DetailViewLayout } from "./DetailViewLayout-Z9cuUp4X.js";
import { C as ContractViewer } from "./ContractViewer-DcQHIGMU.js";
const getPciTemplate = async (legalEntityId, baseUrl, data) => {
  const filteredData = {
    ...data,
    additionalSalesChannels: data.additionalSalesChannels?.filter(
      (channel) => channel !== "payByLink"
    )
  };
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/pci/generatePciTemplates`
    },
    filteredData
  );
};
const usePciTemplate = (data, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["pciTemplate", data],
    queryFn: () => getPciTemplate(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const signPci = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/pci/signPciTemplates`
    },
    data
  );
};
const useSignPci = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  const invalidateRootLegalEntity = useInvalidateRootLegalEntity();
  return useMutation({
    mutationFn: (data) => signPci(rootLegalEntityId.value, baseUrl.value, data),
    onSuccess: async () => {
      await invalidateRootLegalEntity();
    },
    ...options
  });
};
const pciValidationRules = {
  signer: {
    modes: ["blur"],
    validate: (signer) => !isEmpty(signer),
    errorMessage: "fieldIsRequired"
  },
  acceptPci: {
    modes: ["blur"],
    validate: (acceptPci) => !!acceptPci,
    errorMessage: "fieldIsRequired"
  }
};
const PciFields = ["signer", "acceptPci"];
function PciDropin({
  legalEntityResponse,
  pciTemplateResponse,
  handleHomeClick,
  handleSign,
  taskType = TaskTypes.PCI_DSS,
  asModal = false,
  needsSigning = true,
  handleCloseClick
}) {
  const { t } = useTranslation(["contract", "common"]);
  const userEvents = useAnalyticsContext();
  const { showToast } = useToastContext();
  const [isLoading, setIsLoading] = useState(false);
  const { handleChangeFor, triggerValidation, data, valid, isValid, errors } = useForm({
    schema: PciFields,
    rules: pciValidationRules
  });
  const { pciTemplateReferences } = pciTemplateResponse;
  const pciQuestionnaire = JSON.parse(
    decodeURIComponent(escape(window.atob(pciTemplateResponse.content)))
  );
  const uniqueEntityAssociations = [
    ...new Map(
      getOwnDecisionMakers(legalEntityResponse).map((entityAssociation) => [
        entityAssociation.legalEntityId,
        entityAssociation
      ])
    ).values()
  ];
  const signers = legalEntityResponse.type === LegalEntityTypes.ORGANIZATION ? uniqueEntityAssociations.filter(
    (ea) => Boolean(ea.legalEntityId && ea.name)
  ).map(({ legalEntityId: id, name }) => ({ id, name })) : [
    {
      id: legalEntityResponse.id,
      name: `${legalEntityResponse.individual?.name.firstName ?? ""} ${legalEntityResponse.individual?.name.lastName ?? ""}`
    }
  ];
  const handleSignClick = async () => {
    if (isLoading) return;
    const baseTracking = {
      actionType: "sign",
      label: "sign"
    };
    triggerValidation();
    if (isValid) {
      try {
        setIsLoading(true);
        await handleSign(legalEntityResponse.id, { signedBy: data.signer, pciTemplateReferences });
        setIsLoading(false);
        showToast({ label: t(($) => $["pciSignedSuccessfully"]), variant: "success" });
        userEvents.addTaskEvent("Success", baseTracking);
        goHome();
      } catch (e) {
        setIsLoading(false);
        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 goHome = () => {
    userEvents.addPageEvent("Clicked button", {
      actionType: "back",
      label: "finishLater"
    });
    handleHomeClick();
  };
  const handleExpandSection = useCallback((title) => {
    userEvents.addFieldEvent("Clicked accordion", {
      actionType: "open",
      field: title
    });
  }, []);
  useEffect(() => {
    userEvents.updateBaseTrackingPayload({ task: taskType });
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
  }, []);
  const acceptPciLabel = `${t(($) => $["acknowledgePciRequirements"])} ${t(($) => $["basedOnTheAboveSignatory"])}`;
  const actions = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Button, { onClick: handleSignClick, fullWidth: true, disabled: isLoading, children: t(($) => $["sign"], { ns: "common" }) }),
    /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: goHome, fullWidth: true, children: t(($) => $["finishLater"], { ns: "common" }) })
  ] });
  return /* @__PURE__ */ jsx(MaybeModal, { inline: !asModal, onClose: handleCloseClick, inset: true, children: !needsSigning ? /* @__PURE__ */ jsx(
    EndStateLayout,
    {
      title: t(($) => $["agreementSigned"], { ns: "common" }),
      description: t(($) => $["pciDssSelfServiceQuestionnaireSignedSuccessfully"]),
      action: handleCloseClick && /* @__PURE__ */ jsx(Button, { onClick: handleCloseClick, fullWidth: true, children: t(($) => $["finish"], { ns: "common" }) })
    }
  ) : /* @__PURE__ */ jsxs(
    DetailViewLayout,
    {
      title: t(($) => $["pciDssSelfServiceQuestionnaire"]),
      compact: asModal,
      actions,
      children: [
        /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(ContractViewer, { contract: pciQuestionnaire, onExpandSection: handleExpandSection }) }),
        /* @__PURE__ */ jsx(
          Field,
          {
            name: "signer",
            label: t(($) => $["signatory"], { ns: "common" }),
            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
              }
            )
          }
        ),
        /* @__PURE__ */ jsx(
          Field,
          {
            name: "acceptPci",
            errorMessage: errors.acceptPci?.errorMessage,
            isValid: valid.acceptPci,
            showErrorIconBottom: true,
            children: (childProps) => /* @__PURE__ */ jsx(
              Checkbox,
              {
                ...childProps,
                label: acceptPciLabel,
                checked: data.acceptPci ?? false,
                name: "acceptPci",
                onChange: handleChangeFor("acceptPci")
              }
            )
          }
        )
      ]
    }
  ) });
}
function SignPCIComponent({
  modalView = false,
  onClose,
  onSigned,
  onUnmount,
  selectedSalesChannels
}) {
  const additionalSalesChannels = useSalesChannels();
  const { t, i18n } = useTranslation(["contract", "common"]);
  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: "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) },
    { 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) }
  ]);
  const {
    data: legalEntityData,
    isError: isLegalEntityError,
    isLoading: isLegalEntityLoading
  } = useLegalEntity(ROOT_LE);
  const allSalesChannels = useMemo(() => {
    return [.../* @__PURE__ */ new Set([...additionalSalesChannels, ...selectedSalesChannels ?? []])];
  }, [additionalSalesChannels, selectedSalesChannels]);
  const { data: pciTemplateData, isLoading: isPciTemplateDataLoading } = usePciTemplate({
    additionalSalesChannels: allSalesChannels,
    language: i18n.language.substring(0, 2) ?? "en"
  });
  const {
    data: pciStatusData,
    isLoading: isPciStatusLoading,
    isError: isPciStatusError
  } = usePciStatus({
    additionalSalesChannels: allSalesChannels
  });
  const signPci2 = useSignPci();
  const handleOnClose = () => {
    if (modalView) {
      onUnmount?.();
    }
    onClose?.();
  };
  if (isLegalEntityLoading || isPciStatusLoading || isPciTemplateDataLoading || !legalEntityData || !pciTemplateData) {
    return /* @__PURE__ */ jsx(Loader, {});
  }
  if (isLegalEntityError || isPciStatusError) {
    return /* @__PURE__ */ jsx(MaybeModal, { inline: !modalView, onClose: handleOnClose, children: /* @__PURE__ */ jsx(
      EndStateLayout,
      {
        title: t(($) => $["nothingNeedsToBeSigned"]),
        description: t(($) => $["pciDoesNotNeedSigningOrHasBeenSigned"], { ns: "common" }),
        action: /* @__PURE__ */ jsx(Button, { onClick: handleOnClose, fullWidth: true, children: t(($) => $["finish"], { ns: "common" }) })
      }
    ) });
  }
  return /* @__PURE__ */ jsx(
    PciDropin,
    {
      taskType: TaskTypes.PCI_DSS,
      legalEntityResponse: legalEntityData,
      pciTemplateResponse: pciTemplateData,
      handleHomeClick: handleOnClose,
      handleSign: async (_legalEntityId, signedBy) => {
        await signPci2.mutateAsync(signedBy);
        onUnmount?.();
        onSigned?.();
      },
      handleCloseClick: handleOnClose,
      asModal: modalView,
      needsSigning: Boolean(pciStatusData?.signingRequired)
    }
  );
}
export {
  SignPCIComponent
};
