import { m as re, u as oe, a as Me, R as Ue, V as Pe, y as Re, b as _, U as _e, z as $e, J as xe, aw as Z, W as O, G, L as Ve, a3 as qe, a1 as Ge, a2 as Je, h as ie, _ as J, j as Ke } from "./StoreProvider-CBB99upB.js";
import { jsx as a } from "../../../../../preact@10.29.0/node_modules/preact/jsx-runtime/dist/jsxRuntime.module.js";
import { useState as E, useCallback as W, useEffect as R, useMemo as We } from "../../../../../preact@10.29.0/node_modules/preact/hooks/dist/hooks.module.js";
import { useQuery as ce } from "../../../../../@tanstack_preact-query@5.95.2_preact@10.29.0/node_modules/@tanstack/preact-query/build/modern/useQuery.js";
import { useMutation as He } from "../../../../../@tanstack_preact-query@5.95.2_preact@10.29.0/node_modules/@tanstack/preact-query/build/modern/useMutation.js";
import { a as ze, u as Ye } from "./useToastContext-C2BAjZxO.js";
import { u as Qe, a as Ze } from "./useTermsOfServiceStatus-CABu0vXO.js";
import { C as Xe } from "./Card-OQuFzmxm.js";
import { C as en } from "./Checkbox-DmYVTVOD.js";
import { F as X } from "./Field-CPoHG0G-.js";
import { L as K } from "./LoaderWrapper-BL7Hc_DC.js";
import { M as nn } from "./MaybeModal-7NGTfxO6.js";
import { P as an } from "./ProgressBar-B7gTQncy.js";
import { S as tn } from "./Select-seF9rM5K.js";
import { u as sn } from "./useForm-BQDytQRR.js";
import { E as rn } from "./EndStateLayout-DVisdSEd.js";
import { F as on } from "./FormNavigation-yD8USwyG.js";
import { d as ee } from "./file-CiG1D0zy.js";
import { g as cn } from "./getName-CdgtxRvu.js";
import { l as ln } from "./localizeDateString-D2nDwdFu.js";
import { C as dn } from "./ContractViewer-DcQHIGMU.js";
import { Fragment as ne } from "../../../../../preact@10.29.0/node_modules/preact/dist/preact.module.js";
import { skipToken as gn } from "../../../../../@tanstack_query-core@5.95.2/node_modules/@tanstack/query-core/build/modern/utils.js";
try {
  let n = typeof window < "u" ? window : typeof global < "u" ? global : typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : {}, s = new n.Error().stack;
  s && (n._sentryDebugIds = n._sentryDebugIds || {}, n._sentryDebugIds[s] = "d1a4eeb8-bdc4-47ac-9a92-322028e0ea4a", n._sentryDebugIdIdentifier = "sentry-dbid-d1a4eeb8-bdc4-47ac-9a92-322028e0ea4a");
} catch {
}
const mn = async (n, s, c, o) => ie(
  {
    baseUrl: s,
    path: `legalEntities/${n}/termsOfService/accept`
  },
  {
    ...o,
    legalEntityReference: n,
    termsOfServiceDocumentId: c
  }
), un = (n) => {
  const { rootLegalEntityId: s, baseUrl: c } = _(), o = ze();
  return He({
    mutationFn: (l) => mn(
      s.value,
      c.value,
      l.termsOfServiceDocumentId,
      l
    ),
    onSuccess: async () => {
      await o();
    },
    ...n
  });
}, pn = async (n, s, c, o) => Ke({
  baseUrl: s,
  path: `legalEntities/${n}/termsOfService/acceptedTermsOfServiceDocument/${c}?documentformat=${o} `
}), le = (n, s, c) => {
  const { rootLegalEntityId: o, baseUrl: l } = _();
  return ce({
    queryKey: ["acceptedTermsOfService", n, s],
    queryFn: n ? () => pn(
      o.value,
      l.value,
      n,
      s
    ) : gn,
    ...c
  });
}, de = async (n, s, c) => ie(
  {
    baseUrl: s,
    path: `legalEntities/${n}/termsOfService`
  },
  c
), fn = (n, s) => {
  const { rootLegalEntityId: c, baseUrl: o } = _();
  return ce({
    queryKey: ["termsOfService", n],
    queryFn: () => de(c.value, o.value, n),
    ...s
  });
}, yn = "adyen-kyc-tos-signed-alert", vn = "adyen-kyc-tos-container", Sn = "adyen-kyc-tos-content", hn = "adyen-kyc-tos-signer-field", An = "adyen-kyc-tos-actions", D = {
  tosSignedAlert: yn,
  tosContainer: vn,
  tosContent: Sn,
  tosSignerField: hn,
  tosActions: An
}, Tn = re(), ae = "en", Cn = ({
  handleServiceAgreementIsNotAvailableInThatLanguage: n,
  acceptanceId: s,
  serviceAgreementType: c,
  language: o
}) => {
  const [l, T] = E(o);
  R(() => {
    l !== o && T(o);
  }, [o]);
  const {
    data: S,
    isSuccess: h,
    isError: j,
    error: A
  } = fn(
    {
      language: l,
      type: c,
      termsOfServiceDocumentFormat: "JSON"
    },
    { enabled: !s }
  ), { data: t, isSuccess: y } = le(s, "JSON"), d = We(() => {
    const u = S ?? t, C = S?.termsOfServiceDocumentId ?? t?.termsOfServiceAcceptanceReference;
    if (u?.document && C) {
      const I = JSON.parse(
        decodeURIComponent(escape(window.atob(u.document)))
      );
      return {
        loading: "success",
        serviceAgreement: {
          id: C,
          contract: I
        }
      };
    }
  }, [t, S]);
  return (h || y) && d ? d : j ? (l !== ae ? (n(), T(ae)) : Tn.error(A), {
    loading: "success",
    serviceAgreement: void 0
  }) : {
    loading: "loading",
    serviceAgreement: void 0
  };
}, bn = {
  signer: { modes: ["blur"], validate: (n) => !!n, errorMessage: "fieldIsRequired" },
  acceptServiceAgreement: {
    modes: ["blur"],
    validate: (n) => !!n,
    errorMessage: "fieldIsRequired"
  }
}, te = {
  adyenForPlatformsManage: "paymentProcessingTerms",
  adyenIssuing: "accountHolderTerms",
  adyenForPlatformsAdvanced: "paymentProcessingTerms",
  adyenCapital: "capitalUserTerms",
  adyenAccount: "businessAccountTerms",
  adyenCard: "cardUserTerms",
  adyenFranchisee: "franchiseesTAndCs",
  adyenPccr: "pccr",
  adyenChargeCard: "chargeCardUserAgreement"
}, On = re(), se = "en";
function En({
  legalEntityResponse: n,
  handleAddSigner: s,
  handleSign: c,
  serviceAgreementTypes: o,
  serviceAgreementAcceptanceInfos: l,
  asEmbedded: T = !1,
  asModal: S = !1,
  handleCloseClick: h,
  showInitialBackButton: j = !1,
  onComplete: A
}) {
  const { t, i18n: y } = oe(["contract", "common"]), d = $e(), { showToast: u } = Ye(), { isExperimentEnabled: C } = xe(), I = C("EnableAgeVerification"), { rootLegalEntityId: B, baseUrl: $ } = _(), [L, F] = E(), g = l.map((e) => ({
    formId: e.id,
    serviceAgreementType: e.type,
    acceptanceId: e.id,
    createdAt: e.createdAt,
    formName: te[e.type],
    isValid: !0
  })), N = o.map((e) => ({
    formId: e,
    serviceAgreementType: e,
    formName: te[e],
    isValid: !1
  })), v = [...g, ...N], [m, x] = E(0), [i, H] = E(v[m]), [w, V] = E(!1), M = o.includes(i.serviceAgreementType) && !i.acceptanceId, ge = m === 0, me = m === v.length - 1, ue = !!i.acceptanceId, { refetch: pe } = le(
    i.acceptanceId,
    "PDF",
    {
      enabled: !1
    }
  ), fe = W(() => {
    u({
      label: t((e) => e.failedToGetServiceAgreementInSelectedLanguageFallbackToEn),
      variant: "error"
    });
  }, [t, u]), { loading: ye, serviceAgreement: U } = Cn({
    handleServiceAgreementIsNotAvailableInThatLanguage: fe,
    acceptanceId: i.acceptanceId,
    serviceAgreementType: i.serviceAgreementType,
    language: Z(y.language)
  }), { handleChangeFor: z, triggerValidation: ve, data: b, valid: q, isValid: Se, errors: Y } = sn({
    schema: ["signer", "acceptServiceAgreement"],
    rules: bn
  }), P = (() => {
    if (n.type === Ve.ORGANIZATION)
      return qe(n).map(({ legalEntityId: e, name: r }) => ({
        id: e ?? "",
        name: r ?? ""
      }));
    if (I && Ge(n)) {
      const e = Je(n);
      return e ? [{ id: e.legalEntityId, name: e.name }] : [];
    }
    return [
      {
        id: n.id,
        name: `${n.individual?.name.firstName ?? ""} ${n.individual?.name.lastName ?? ""}`
      }
    ];
  })(), he = async () => {
    const e = {
      actionType: "sign"
    };
    if (ve(), !(L === "loading" || !U || !b.signer))
      if (Se)
        try {
          F("loading"), await c(n.id, U.id, { acceptedBy: b.signer }), F("success"), u({
            label: t((r) => r.serviceAgreementSignedSuccessfully),
            variant: "success"
          }), d.addTaskEvent("Success", e), b.acceptServiceAgreement = !1, b.signer = void 0;
        } catch (r) {
          F("success"), u({ label: t((p) => p.signingFailed), variant: "error" }), d.addTaskEvent("Encountered error", {
            ...e,
            returnType: r?.errorCode || "backend",
            returnValue: r?.title ?? r?.message
          });
        }
      else
        d.addTaskEvent("Encountered error", {
          ...e,
          returnType: "validation",
          returnValue: Object.entries(q).filter(([, r]) => !r).map(([r]) => r)
        });
  }, Ae = W((e) => {
    d.addFieldEvent("Clicked accordion", {
      actionType: "open",
      field: e
    });
  }, []);
  R(() => {
    l.length && k(l.length - 1);
  }, [l]), R(() => {
    d.addTaskEvent("Landed on page", {
      actionType: "start"
    });
    const e = v.length === g.length ? 0 : g.length;
    k(e);
  }, []), R(() => {
    d.updateSharedEventProperties({ page: i?.formName });
  }, [i]);
  const k = (e) => {
    H(v[e]), x(e);
  }, Te = async () => {
    const { isError: e, isSuccess: r, data: p } = await pe();
    r && p.document && await ee(
      p.document,
      `${t((f) => f[i.formName], { ns: "common" })}.pdf`
    ), e && u({
      label: t((f) => f.failedToDownloadAcceptedServiceAgreementDocument),
      variant: "error"
    });
  }, Ce = async () => {
    const e = Z(y.language), r = async (p) => {
      const f = await de(B.value, $.value, {
        type: i.serviceAgreementType,
        language: p,
        termsOfServiceDocumentFormat: "PDF"
      });
      if (!f.document)
        throw new Error("No terms Of service document found in response");
      await ee(
        f.document,
        `${t((Be) => Be[i.formName], { ns: "common" })}.pdf`
      );
    };
    try {
      ["fr", "en"].includes(y.language) && await r(e), await r("en");
    } catch {
      if (e !== se) {
        await r(se).catch(On.error);
        return;
      }
      u({
        label: t((p) => p.failedToDownloadServiceAgreementDocument),
        variant: "error"
      });
    }
  }, be = n.type === "individual", Oe = s && /* @__PURE__ */ a(
    G,
    {
      variant: P.length ? "info" : "warning",
      className: "adyen-kyc-u-margin-top-16",
      title: t((e) => e[P.length ? "isYourNameMissingFromSigners" : "thereAreNoSigners"]),
      children: /* @__PURE__ */ a(O, { onClick: s, variant: "link", children: t((e) => e.addYourselfAsSigner) })
    }
  ), Ee = (e) => {
    if (!e) return "";
    const r = l.find(({ id: f }) => f === e);
    return n.entityAssociations?.find(
      ({ legalEntityId: f }) => f === r?.acceptedBy
    )?.name ?? cn(n);
  }, Q = ue && /* @__PURE__ */ a(
    G,
    {
      variant: "success",
      className: D.tosSignedAlert,
      title: t((e) => e.signedByOn, {
        date: ln(i.createdAt, y.language) ?? "",
        signer: Ee(i.acceptanceId)
      })
    }
  ), je = /* @__PURE__ */ a(
    K,
    {
      status: L,
      formOpacityWhenLoading: 0.3,
      showSpinner: !1,
      className: "adyen-kyc-dropin__sidebar-wrapper",
      children: /* @__PURE__ */ a(
        on,
        {
          forms: v,
          activeForm: i,
          gotoForm: k,
          taskName: "signServiceAgreement",
          className: "adyen-kyc-u-margin-bottom-24"
        }
      )
    }
  ), Ie = /* @__PURE__ */ a(
    K,
    {
      status: L,
      formOpacityWhenLoading: 0.3,
      showSpinner: !1,
      className: "adyen-kyc-form-container",
      children: [
        /* @__PURE__ */ a(
          K,
          {
            status: ye,
            formOpacityWhenLoading: 0.3,
            showSpinner: !1,
            children: [
              U && /* @__PURE__ */ a(ne, { children: [
                /* @__PURE__ */ a("div", { className: "adyen-kyc-u-margin-bottom-16", children: Q }),
                /* @__PURE__ */ a(Xe, { children: /* @__PURE__ */ a(
                  dn,
                  {
                    contract: U.contract,
                    onExpandSection: Ae,
                    showSectionNumbering: !0
                  }
                ) }),
                /* @__PURE__ */ a("div", { className: "adyen-kyc-u-margin-top-16", children: Q }),
                /* @__PURE__ */ a("div", { className: "adyen-kyc-u-margin-y-16", children: /* @__PURE__ */ a(
                  O,
                  {
                    variant: "secondary",
                    onClick: i?.acceptanceId ? Te : Ce,
                    icon: "download",
                    children: t((e) => e.downloadAsPdf)
                  }
                ) })
              ] }),
              !v.length && /* @__PURE__ */ a(G, { variant: "info", title: t((e) => e.nothingNeedsToBeSigned) })
            ]
          }
        ),
        M && /* @__PURE__ */ a(ne, { children: [
          !!P.length && /* @__PURE__ */ a(
            X,
            {
              name: "signer",
              label: t((e) => e.signer),
              className: D.tosSignerField,
              errorMessage: Y.signer?.errorMessage,
              isValid: q.signer,
              dataTestId: "signer",
              children: (e) => /* @__PURE__ */ a(
                tn,
                {
                  ...e,
                  onChange: z("signer", "blur"),
                  name: "signer",
                  placeholder: t((r) => r.selectSigner),
                  selected: b.signer,
                  items: P
                }
              )
            }
          ),
          !be && Oe,
          /* @__PURE__ */ a(
            X,
            {
              name: "acceptServiceAgreement",
              className: "adyen-kyc-u-margin-top-16",
              errorMessage: Y.acceptServiceAgreement?.errorMessage,
              isValid: q.acceptServiceAgreement,
              children: (e) => /* @__PURE__ */ a(
                en,
                {
                  ...e,
                  label: t((r) => r.iHaveReadAndIAcceptTheseTerms),
                  checked: b.acceptServiceAgreement ?? !1,
                  name: "acceptServiceAgreement",
                  onChange: z("acceptServiceAgreement")
                }
              )
            }
          )
        ] })
      ]
    }
  ), Le = g.length, Fe = v.length, Ne = () => {
    M ? he() : me ? V(!0) : k(m + 1);
  }, we = () => {
    h(), A?.();
  }, ke = w && /* @__PURE__ */ a(
    rn,
    {
      title: t((e) => e.serviceAgreementSignedAndDated),
      action: /* @__PURE__ */ a(O, { onClick: we, fullWidth: !0, children: t((e) => e.finish, { ns: "common" }) })
    }
  ), De = Math.floor(Le / (Fe - 1) * 100);
  return /* @__PURE__ */ a(nn, { inline: !S, onClose: h, children: /* @__PURE__ */ a("div", { className: D.tosContainer, children: [
    /* @__PURE__ */ a("div", { className: D.tosContent, children: [
      !T && je,
      ke || Ie
    ] }),
    !w && /* @__PURE__ */ a("div", { children: [
      /* @__PURE__ */ a(
        an,
        {
          ariaLabel: t((e) => e.progress, { ns: "common" }),
          progress: De
        }
      ),
      /* @__PURE__ */ a("div", { className: D.tosActions, children: [
        ge ? j && /* @__PURE__ */ a(O, { onClick: h, variant: "secondary", children: t((e) => e.cancel, { ns: "common" }) }) : /* @__PURE__ */ a(
          O,
          {
            icon: "chevron-left",
            onClick: () => {
              k(m - 1);
            },
            variant: "secondary",
            children: t((e) => e.back, { ns: "common" })
          }
        ),
        /* @__PURE__ */ a(O, { variant: M ? "primary" : "secondary", onClick: Ne, children: M ? t((e) => e.sign, { ns: "common" }) : t((e) => e.continue, { ns: "common" }) })
      ] })
    ] })
  ] }) });
}
function Yn({
  legalEntityId: n,
  modalView: s = !1,
  asEmbedded: c = !0,
  /* triggered when X button clicked, or at the end, on Finish button click */
  onClose: o,
  onComplete: l,
  onUnmount: T,
  /* triggered on every document signed, typically multiple times */
  onAccept: S,
  handleAddSigner: h
}) {
  if (!n)
    throw new Error("Must provide at-least a legalEntityId");
  const { i18n: j } = oe();
  Me(j, [
    { ns: "common", importFn: (g) => J(/* @__PURE__ */ Object.assign({ "../../../language/locales/da-DK.json": () => import("./da-DK-Cv6XUSoW.js"), "../../../language/locales/de-DE.json": () => import("./de-DE-BplDsJEb.js"), "../../../language/locales/en-US.instructions.json": () => import("./en-US.instructions-CfIM2SRF.js"), "../../../language/locales/en-US.json": () => import("./StoreProvider-CBB99upB.js").then((N) => N.bT), "../../../language/locales/es-ES.json": () => import("./es-ES-DRsix_Xn.js"), "../../../language/locales/fi-FI.json": () => import("./fi-FI-BftTiz0c.js"), "../../../language/locales/fr-FR.json": () => import("./fr-FR-C6jxjXAI.js"), "../../../language/locales/it-IT.json": () => import("./it-IT-CXlaZNIj.js"), "../../../language/locales/ja-JP.json": () => import("./ja-JP-A6ArIIZ8.js"), "../../../language/locales/nl-NL.json": () => import("./nl-NL-BwWFlBOs.js"), "../../../language/locales/no-NO.json": () => import("./no-NO-JWsSd7iY.js"), "../../../language/locales/pt-BR.json": () => import("./pt-BR-BJOww8U1.js"), "../../../language/locales/sl-SI.json": () => import("./sl-SI-BfO3xEJx.js"), "../../../language/locales/sv-SE.json": () => import("./sv-SE-CMLKzwtj.js") }), `../../../language/locales/${g}.json`, 6) },
    { ns: "contract", importFn: (g) => J(/* @__PURE__ */ Object.assign({ "../../Contract/language/da-DK.json": () => import("./da-DK-CLdNh9JT.js"), "../../Contract/language/de-DE.json": () => import("./de-DE-BT5g7ZXC.js"), "../../Contract/language/en-US.json": () => import("./en-US-CgakND3H.js"), "../../Contract/language/es-ES.json": () => import("./es-ES-4FS7NoE7.js"), "../../Contract/language/fi-FI.json": () => import("./fi-FI-XpnJRPgt.js"), "../../Contract/language/fr-FR.json": () => import("./fr-FR-TqAhPvzz.js"), "../../Contract/language/it-IT.json": () => import("./it-IT-D-jYXj6V.js"), "../../Contract/language/ja-JP.json": () => import("./ja-JP-8yMqZqF2.js"), "../../Contract/language/nl-NL.json": () => import("./nl-NL-Jhr-ICkK.js"), "../../Contract/language/no-NO.json": () => import("./no-NO-BH6DId3q.js"), "../../Contract/language/pt-BR.json": () => import("./pt-BR-4Iozxvfr.js"), "../../Contract/language/sl-SI.json": () => import("./sl-SI-Y9h1ht45.js"), "../../Contract/language/sv-SE.json": () => import("./sv-SE-DFSm22oQ.js") }), `../../Contract/language/${g}.json`, 5) },
    { ns: "ui", importFn: (g) => J(/* @__PURE__ */ Object.assign({ "../../ui/language/da-DK.json": () => import("./da-DK-DQ4ZYSea.js"), "../../ui/language/de-DE.json": () => import("./de-DE-CkbOZ6S_.js"), "../../ui/language/en-US.json": () => import("./en-US-B-qSAb-7.js"), "../../ui/language/es-ES.json": () => import("./es-ES-BAolMrZ0.js"), "../../ui/language/fi-FI.json": () => import("./fi-FI-D8WrLxxq.js"), "../../ui/language/fr-FR.json": () => import("./fr-FR-Beljeilc.js"), "../../ui/language/it-IT.json": () => import("./it-IT-5a7NHVFo.js"), "../../ui/language/ja-JP.json": () => import("./ja-JP-DSvZhFNY.js"), "../../ui/language/nl-NL.json": () => import("./nl-NL-CmURERx_.js"), "../../ui/language/no-NO.json": () => import("./no-NO-qyqWODMp.js"), "../../ui/language/pt-BR.json": () => import("./pt-BR-BxoOF8jB.js"), "../../ui/language/sl-SI.json": () => import("./sl-SI-DTvJT7fC.js"), "../../ui/language/sv-SE.json": () => import("./sv-SE-N-Hqwcjq.js") }), `../../ui/language/${g}.json`, 5) }
  ]);
  const [A, t] = E({
    unAcceptedTermsOfServiceTypes: [],
    acceptedTermsOfServices: []
  }), { data: y } = Ue(_e), { data: d, isLoading: u } = Qe(), { data: C, isLoading: I } = Ze(), { mutateAsync: B } = un(), $ = () => {
    s && T?.(), o?.();
  }, L = W(
    async (g, N, v) => {
      const m = await B({
        acceptedBy: v.acceptedBy,
        legalEntityReference: g,
        termsOfServiceDocumentId: N
      }), x = {
        type: m.type,
        acceptedBy: m.acceptedBy,
        id: m.id,
        language: m.language,
        termsOfServiceDocumentId: m.termsOfServiceDocumentId
      }, { acceptedTermsOfServices: i } = A;
      i.push(x);
      const w = {
        unAcceptedTermsOfServiceTypes: d?.termsOfServiceTypes?.filter(
          (V) => V !== m.type
        ) ?? [],
        acceptedTermsOfServices: i
      };
      t(w), S?.(w);
    },
    [S, A, B, d?.termsOfServiceTypes]
  ), F = () => {
    l?.(A);
  };
  return u || I || !y ? /* @__PURE__ */ a(Pe, {}) : /* @__PURE__ */ a(
    En,
    {
      taskType: Re.SERVICE_AGREEMENT,
      legalEntityResponse: y,
      serviceAgreementTypes: d?.termsOfServiceTypes ?? [],
      serviceAgreementAcceptanceInfos: C?.data ?? [],
      handleSign: L,
      asEmbedded: c,
      asModal: s,
      handleCloseClick: $,
      showInitialBackButton: !!o,
      onComplete: F,
      handleAddSigner: h
    }
  );
}
export {
  Yn as AcceptTermsOfServiceComponent
};
