;
{
  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] = "ba3aff3b-6e00-43dd-aaa1-cd5274752112", e._sentryDebugIdIdentifier = "sentry-dbid-ba3aff3b-6e00-43dd-aaa1-cd5274752112");
  } catch (e) {
  }
}
;
import { b as useApiContext, k as httpGet, z as Typography, u as useTranslation, aB as Trans, r as Icon, V as Button, t as IconButton, H as TASK_STATUS_POLLING_INTERVAL_MS, ai as isEmpty$1, a as addResourceBundles, p as useAnalyticsContext, c as useLegalEntity, L as Loader, R as ROOT_LE, a3 as createLogger, _ as __variableDynamicImportRuntimeHelper } from "./StoreProvider-CqQrndhS.js";
import { jsx, jsxs, Fragment } from "preact/jsx-runtime";
import { useState, useRef, useEffect, useMemo, useCallback } from "preact/hooks";
import { a as useInvalidateRootLegalEntity } from "./useToastContext-CPvuqSMm.js";
import { u as useUpdateLegalEntity } from "./useUpdateLegalEntity-CcNBhTXa.js";
import { useQuery } from "@tanstack/preact-query";
import { u as useFormContext, F as FormContextProvider, a as FormFlow } from "./useFormContext-LfOXbOKX.js";
import { g as getRequiredForms, a as addValidityToForms, u as useFormComposer } from "./dropinUtils-G5Ua27s3.js";
import { u as useMultiForm } from "./useMultiForm-XT1CUuQs.js";
import { signal } from "@preact/signals";
import { a as getFormProps } from "./getProps-Cc3J2-z9.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import { L as Link } from "./Link-BEM0XOtr.js";
import { R as RadioGroup } from "./RadioGroup-jkgDMvvX.js";
import { a as Alert } from "./Alert-CpDg47bv.js";
import { lazy } from "preact/compat";
import { u as useTaskStatus } from "./useTaskStatus-mjcLNZSC.js";
import { C as Card } from "./Card-OQuFzmxm.js";
import { I as Image } from "./Image-C0SMWMbc.js";
import { S as StructuredList } from "./StructuredList-BNLhk_zV.js";
import { L as LandingLayout } from "./LandingLayout-B4GiCZLB.js";
import { i as isEmpty } from "./isEmpty-vwqWRDI4.js";
const getTaxClassification = async (legalEntityId, baseUrl) => {
  return httpGet({
    baseUrl,
    path: `legalEntities/${legalEntityId}/taxclassification`
  });
};
const useTaxClassification = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["taxClassification"],
    queryFn: () => getTaxClassification(rootLegalEntityId.value, baseUrl.value),
    ...options
  });
};
const taxClassificationErrorMessage = signal(void 0);
const setTaxClassificationErrorMessage = (message) => {
  taxClassificationErrorMessage.value = message;
};
const clearTaxClassificationErrorMessage = () => {
  taxClassificationErrorMessage.value = void 0;
};
const taxReportingDropin = "adyen-kyc-tax-reporting-dropin";
const radioCaption = "adyen-kyc-radio-caption";
const taxReportingDropinGettingStarted = "adyen-kyc-tax-reporting-dropin-getting-started";
const taxReportingDropinFormContainer = "adyen-kyc-tax-reporting-dropin-form-container";
const summary = "adyen-kyc-summary";
const summaryTaxStatusCardHeader = "adyen-kyc-summary-tax-status-card--header";
const summaryTaxStatusCardBody = "adyen-kyc-summary-tax-status-card--body";
const styles = {
  taxReportingDropin,
  radioCaption,
  taxReportingDropinGettingStarted,
  taxReportingDropinFormContainer,
  summary,
  summaryTaxStatusCardHeader,
  summaryTaxStatusCardBody
};
const taxReportingForms = {
  taxClassification: {
    formId: "taxClassification",
    formName: "chooseATaxReportingClassificationOption",
    fields: ["type"]
  }
};
const taxReportingRequiredFields = {
  taxClassification: ["type"]
};
const taxReportingOptions = {
  nonFinancialActive: "yourBusinessReceivesTheMajorityOfItsIncomeThroughActiveIncome",
  nonFinancialPassive: "yourBusinessGeneratesMoreThanHalfOfItsRevenueAsPassiveIncome",
  nonFinancialNonReportable: "yourBusinessIsAPublicListedEntity",
  financialNonReportable: "yourBusinessIsAFinancialInstitution"
};
const getTaxStatusSummary = (t, taxReportingClassification) => {
  const taxStatusDescription = taxReportingClassification?.taxClassification?.type ? taxReportingClassification.taxClassification.type : void 0;
  return taxStatusDescription ? [
    {
      term: t(($) => $["status"]),
      details: t(($) => $[taxStatusDescription])
    },
    {
      term: t(($) => $["description"]),
      details: t(($) => $[taxReportingOptions[taxStatusDescription]])
    }
  ] : [];
};
const getTaxOptionsRadioItems = (t, taxRecommendationData, taxReportingClassification) => {
  const businessType = taxRecommendationData?.businessType;
  const allowedTypes = getSupportedTaxClassificationTypes(businessType);
  const allowedTaxReportingOptionKeys = allowedTypes.filter(
    (key) => key in taxReportingOptions
  );
  const taxOptionsWithoutRecommendationKeys = allowedTaxReportingOptionKeys.filter(
    (key) => key !== taxRecommendationData?.type
  );
  const taxReportingOptionKeysToShow = taxRecommendationData?.type && !taxReportingClassification?.type ? taxOptionsWithoutRecommendationKeys : allowedTaxReportingOptionKeys;
  return taxReportingOptionKeysToShow.map((key) => {
    const value = taxReportingOptions[key];
    return {
      id: key,
      name: t(($) => $[key]),
      content: /* @__PURE__ */ jsx(Typography, { variant: "body", color: "secondary", className: styles.radioCaption, children: t(($) => $[value]) })
    };
  });
};
const getRecommendedTaxOptionsRadioItems = (t, showRecommendation, taxRecommendationData) => {
  const taxRecommendationType = taxRecommendationData?.type ? taxRecommendationData.type : void 0;
  return showRecommendation && taxRecommendationType ? [
    {
      id: taxRecommendationType,
      name: t(($) => $[taxRecommendationType]),
      content: /* @__PURE__ */ jsx(Typography, { variant: "body", color: "secondary", className: styles.radioCaption, children: t(($) => $[taxReportingOptions[taxRecommendationType]]) })
    }
  ] : [];
};
const getSupportedTaxClassificationTypes = (businessType) => {
  const publicCompanyTypes = [
    "listedPublicCompany",
    "subsidiaryOfListedPublicCompany",
    "governmentalOrganization",
    "internationalOrganization"
  ];
  if (!businessType) {
    return [];
  }
  if (publicCompanyTypes.includes(businessType)) {
    return ["nonFinancialNonReportable"];
  }
  if (businessType === "financialInstitution") {
    return ["financialNonReportable"];
  } else if (businessType === "other") {
    return ["nonFinancialActive", "nonFinancialPassive"];
  } else {
    return [];
  }
};
function TaxReportingClassificationForm({
  data,
  taxReportingClassification,
  taxRecommendationData,
  errors
}) {
  const { t: taxReportingT } = useTranslation("taxReporting");
  const { t: commonT } = useTranslation("common");
  const { form } = useFormContext();
  const { handleChangeFor } = form;
  const showRecommendation = taxRecommendationData?.type && !taxReportingClassification?.type;
  const taxOptionsRadioItems = getTaxOptionsRadioItems(
    taxReportingT,
    taxRecommendationData,
    taxReportingClassification
  );
  const recommendedTaxOptionRadioItems = getRecommendedTaxOptionsRadioItems(
    taxReportingT,
    showRecommendation,
    taxRecommendationData
  );
  const handleFieldChange = (fieldName, mode) => handleChangeFor(fieldName, "taxClassification", mode);
  const typeErrorMessage = errors?.type?.errorMessage;
  return /* @__PURE__ */ jsxs("form", { className: "tax-reporting", children: [
    /* @__PURE__ */ jsx(Header, { title: taxReportingT(($) => $["taxStatusSelfCertification"]), children: /* @__PURE__ */ jsx(
      Trans,
      {
        slot: "description",
        t: commonT,
        i18nKey: ($) => $["chooseTheTaxStatusWhichBestRepresentsYourBusiness"],
        components: {
          el1: /* @__PURE__ */ jsx(
            Link,
            {
              inline: true,
              external: true,
              href: "https://www.irs.gov/businesses/corporations/foreign-account-tax-compliance-act-fatca#:~:text=The%20Foreign%20Account%20Tax%20Compliance,to%20withholding%20on%20withholdable%20payments.",
              children: "text"
            }
          ),
          el2: /* @__PURE__ */ jsx(
            Link,
            {
              inline: true,
              external: true,
              href: "https://www.oecd.org/en/publications/standard-for-automatic-exchange-of-financial-account-information-in-tax-matters-second-edition_9789264267992-en.html",
              children: "text"
            }
          )
        }
      }
    ) }),
    typeErrorMessage && /* @__PURE__ */ jsx(
      Alert,
      {
        variant: "error",
        title: commonT(($) => $[typeErrorMessage])
      }
    ),
    showRecommendation ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Typography, { variant: "body-stronger", children: taxReportingT(($) => $["recommendedForYourBusiness"]) }),
      /* @__PURE__ */ jsx(Field, { el: "fieldset", name: "type", children: (childProps) => /* @__PURE__ */ jsx(
        RadioGroup,
        {
          ...childProps,
          name: "type",
          items: recommendedTaxOptionRadioItems,
          value: data?.type,
          onChange: handleFieldChange("type", "input")
        }
      ) }),
      taxOptionsRadioItems.length ? /* @__PURE__ */ jsx(Typography, { variant: "body-stronger", children: commonT(($) => $[taxOptionsRadioItems.length === 1 ? "other" : "otherOptions"]) }) : null
    ] }) : null,
    /* @__PURE__ */ jsx(Field, { el: "fieldset", name: "type", children: (childProps) => /* @__PURE__ */ jsx(
      RadioGroup,
      {
        ...childProps,
        name: "type",
        items: taxOptionsRadioItems,
        value: data?.type,
        onChange: handleFieldChange("type", "input")
      }
    ) })
  ] });
}
const taxClassificationFormID = taxReportingForms.taxClassification.formId;
function TaxReporting(props) {
  const { form } = useFormContext();
  const { errors, valid, fieldProblems: fieldValidationErrors } = form;
  const { activeForm: propActiveForm, taxReportingClassification, taxRecommendationData } = props;
  const classificationFormProps = getFormProps(props, taxClassificationFormID);
  const renderActiveForm = (activeForm) => /* @__PURE__ */ jsx(Fragment, { children: activeForm?.formId === taxClassificationFormID && /* @__PURE__ */ jsx("div", { className: styles.taxReportingDropinFormContainer, children: /* @__PURE__ */ jsx(
    TaxReportingClassificationForm,
    {
      ...classificationFormProps,
      taxReportingClassification,
      taxRecommendationData,
      errors: errors?.taxClassification,
      valid: valid?.taxClassification,
      fieldValidationErrors: fieldValidationErrors?.taxClassification
    }
  ) }) });
  return /* @__PURE__ */ jsxs("div", { className: "tax-reporting", children: [
    taxClassificationErrorMessage.value && /* @__PURE__ */ jsxs(
      Typography,
      {
        variant: "caption",
        color: "critical",
        "aria-live": "polite",
        className: "adyen-kyc-u-justify-content-center adyen-kyc-u-display-flex",
        children: [
          /* @__PURE__ */ jsx(Icon, { name: "field-error" }),
          " ",
          /* @__PURE__ */ jsx("div", { children: taxClassificationErrorMessage.value })
        ]
      }
    ),
    renderActiveForm(propActiveForm)
  ] });
}
const usCheckAccount = lazy(() => import("./tax-reporting-graph-hgoilCHZ.js"));
const TaxReportingGettingStarted = ({
  handleToggleFormVisible,
  handleCancelClick,
  taxReportingClassification
}) => {
  const { t: taxReportingT } = useTranslation("taxReporting");
  const { t: commonT } = useTranslation("common");
  const { data: normalizedTasks } = useTaskStatus({
    refetchInterval: TASK_STATUS_POLLING_INTERVAL_MS
  });
  const hasTaxReportingClassification = !isEmpty(
    taxReportingClassification?.taxClassification?.type
  );
  const taxStatusSummary = getTaxStatusSummary(taxReportingT, taxReportingClassification);
  return /* @__PURE__ */ jsxs("div", { className: styles.taxReportingDropinGettingStarted, children: [
    !hasTaxReportingClassification && /* @__PURE__ */ jsx(
      LandingLayout,
      {
        media: /* @__PURE__ */ jsx(Image, { lazyLoadedImage: usCheckAccount }),
        title: taxReportingT(($) => $["taxStatusSelfCertification"]),
        description: taxReportingT(($) => $["toUnderstandIfYourBankAccountDetailsAreReportable"]),
        actions: /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(Button, { fullWidth: true, onClick: handleToggleFormVisible, children: commonT(($) => $["gettingStarted"]) }),
          handleCancelClick && /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: handleCancelClick, fullWidth: true, children: commonT(($) => $["backToTaskList"]) })
        ] })
      }
    ),
    hasTaxReportingClassification && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx(
          Header,
          {
            title: taxReportingT(($) => $["selfCertifiedTaxStatus"]),
            description: taxReportingT(($) => $["noFurtherActionOrRecertificationIsNeeded"]),
            status: normalizedTasks?.TAX_REPORTING?.status,
            align: "center"
          }
        ),
        /* @__PURE__ */ jsx("div", { className: styles.summary, children: /* @__PURE__ */ jsxs(Card, { variant: "secondary", children: [
          /* @__PURE__ */ jsxs("div", { className: styles.summaryTaxStatusCardHeader, children: [
            /* @__PURE__ */ jsx(Typography, { el: "h3", variant: "title", children: taxReportingT(($) => $["taxStatus"]) }),
            /* @__PURE__ */ jsx(
              IconButton,
              {
                ariaLabel: "edit",
                icon: "edit",
                onClick: handleToggleFormVisible,
                variant: "tertiary"
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: styles.summaryTaxStatusCardBody, children: /* @__PURE__ */ jsx(
            StructuredList,
            {
              className: styles.summaryTaxStatusCardDescription,
              items: taxStatusSummary
            }
          ) })
        ] }) })
      ] }),
      handleCancelClick && /* @__PURE__ */ jsx(
        Button,
        {
          variant: "secondary",
          testId: "source-of-funds-getting-return-button",
          onClick: handleCancelClick,
          children: commonT(($) => $["backToTaskList"])
        }
      )
    ] })
  ] });
};
const taxReportingTypeValidations = {
  type: {
    modes: ["blur"],
    validate: (type) => !isEmpty$1(type),
    errorMessage: "chooseATaxStatusOptionToContinue"
  }
};
const logger = createLogger();
function TaxReportingDropin({ problems, handleHomeClick }) {
  const [loadingStatus, setLoadingStatus] = useState("success");
  const [formVisible, setFormVisible] = useState(false);
  useRef(null);
  const invalidateRootLegalEntity = useInvalidateRootLegalEntity();
  const { i18n } = useTranslation();
  const { t: taxReportingT } = useTranslation("taxReporting");
  addResourceBundles(i18n, [
    { ns: "taxReporting", importFn: (lang) => __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "./language/bg-BG.json": () => import("./bg-BG-DcxZ1tmt.js"), "./language/cs-CZ.json": () => import("./cs-CZ-D4Hg-t16.js"), "./language/da-DK.json": () => import("./da-DK-DCJhV2qS.js"), "./language/de-DE.json": () => import("./de-DE-DwOQKCuU.js"), "./language/el-GR.json": () => import("./el-GR-Hk4NbZSY.js"), "./language/en-US.json": () => import("./en-US-BQZhzROc.js"), "./language/es-ES.json": () => import("./es-ES-BOoPqnPI.js"), "./language/et-EE.json": () => import("./et-EE-Be__VK7Y.js"), "./language/fi-FI.json": () => import("./fi-FI-bZzNB1WB.js"), "./language/fr-FR.json": () => import("./fr-FR-cTKcuHqX.js"), "./language/hr-HR.json": () => import("./hr-HR-ComCqan_.js"), "./language/hu-HU.json": () => import("./hu-HU-DUGz5q5D.js"), "./language/it-IT.json": () => import("./it-IT-DERflsUd.js"), "./language/ja-JP.json": () => import("./ja-JP-BoxeBgOv.js"), "./language/lt-LT.json": () => import("./lt-LT-D5Rhxm1h.js"), "./language/lv-LV.json": () => import("./lv-LV-CG1zToz7.js"), "./language/nl-NL.json": () => import("./nl-NL-Cjlmc0Ii.js"), "./language/no-NO.json": () => import("./no-NO-CY_XHrYd.js"), "./language/pl-PL.json": () => import("./pl-PL-C_MvVzPy.js"), "./language/pt-BR.json": () => import("./pt-BR-CBAe0SnK.js"), "./language/pt-PT.json": () => import("./pt-PT-Dm5DRDrd.js"), "./language/ro-RO.json": () => import("./ro-RO-B5YT9vP-.js"), "./language/sk-SK.json": () => import("./sk-SK-S6iF1WDH.js"), "./language/sl-SI.json": () => import("./sl-SI-DqUEy_Cm.js"), "./language/sv-SE.json": () => import("./sv-SE-CRBRuE8Z.js") }), `./language/${lang}.json`, 3) }
  ]);
  const { data: taxRecommendationData, isLoading: isLoadingTaxRecommendationData } = useTaxClassification();
  const userEvents = useAnalyticsContext();
  const { data: legalEntityData, isLoading } = useLegalEntity(ROOT_LE);
  const { mutateAsync: updateLegalEntityMutation } = useUpdateLegalEntity();
  useEffect(() => {
    clearTaxClassificationErrorMessage();
  }, []);
  useEffect(() => {
    userEvents.addTaskEvent("Landed on page", {
      actionType: "start"
    });
  }, [userEvents]);
  const taxReportingClassification = useMemo(
    () => ({
      taxClassification: {
        type: legalEntityData?.organization?.taxReportingClassification?.type
      }
    }),
    [legalEntityData?.organization?.taxReportingClassification?.type]
  );
  const defaultData = useMemo(
    () => ({
      ...taxReportingClassification
    }),
    [taxReportingClassification]
  );
  const form = useMultiForm({
    requiredFields: taxReportingRequiredFields,
    rules: {
      taxClassification: taxReportingTypeValidations
    },
    defaultData
  });
  const { data = taxReportingClassification, setData, triggerValidation } = form;
  useEffect(() => {
    if (!data?.taxClassification?.type && taxReportingClassification?.taxClassification?.type) {
      setData("type", taxReportingClassification?.taxClassification?.type, "taxClassification");
      (async () => {
        await triggerValidation("taxClassification");
      })().catch(() => console.error("Error triggering validation"));
    }
  }, [
    data?.taxClassification?.type,
    taxReportingClassification?.taxClassification?.type,
    setData,
    triggerValidation
  ]);
  const forms = useMemo(() => {
    const requiredForms = getRequiredForms(
      taxReportingForms,
      taxReportingRequiredFields,
      void 0
    );
    const requiredFormsWithoutSummary = requiredForms.filter((form2) => form2.formId !== "summary");
    return addValidityToForms(requiredFormsWithoutSummary, form.isValid, problems);
  }, [form.isValid, problems]);
  const handleSubmit = useCallback(async () => {
    if (!legalEntityData) {
      return;
    }
    setLoadingStatus("loading");
    const taxReportingPayload = {
      businessType: taxRecommendationData?.businessType,
      financialInstitutionNumber: taxRecommendationData?.financialInstitutionNumber,
      mainSourceOfIncome: taxRecommendationData?.mainSourceOfIncome,
      type: data?.taxClassification?.type
    };
    const legalEntityPayload = {
      id: legalEntityData.id,
      ...legalEntityData?.organization && {
        organization: {
          ...legalEntityData.organization,
          taxReportingClassification: taxReportingPayload
        }
      }
    };
    try {
      await updateLegalEntityMutation(legalEntityPayload);
      await invalidateRootLegalEntity();
      userEvents.addTaskEvent("Success", {
        actionType: "submit",
        returnValue: data?.taxClassification?.type
      });
      handleHomeClick?.();
      setFormVisible(false);
      gotoFormByFormIndex(0);
      setTaxClassificationErrorMessage("");
      setLoadingStatus("success");
    } catch (e) {
      setTaxClassificationErrorMessage(
        e?.message || taxReportingT(($) => $["errorUpdatingTaxClassification"])
      );
      logger.log("Error updating source of funds", e);
      setLoadingStatus("success");
    }
  }, [data, taxRecommendationData, legalEntityData, updateLegalEntityMutation]);
  const handleToggleFormVisible = () => {
    setFormVisible(!formVisible);
  };
  const { handleNextClick, activeForm, gotoFormByFormIndex, steps } = useFormComposer(
    {
      problems,
      forms,
      onSubmit: handleSubmit
    }
  );
  return /* @__PURE__ */ jsx("div", { className: styles.taxReportingDropin, children: isLoading || isLoadingTaxRecommendationData ? /* @__PURE__ */ jsx(Loader, {}) : /* @__PURE__ */ jsxs(Fragment, { children: [
    !formVisible && /* @__PURE__ */ jsx(
      TaxReportingGettingStarted,
      {
        handleCancelClick: handleHomeClick,
        handleToggleFormVisible,
        taxReportingClassification,
        problems: legalEntityData?.problems
      }
    ),
    formVisible && /* @__PURE__ */ jsx(FormContextProvider, { form, children: /* @__PURE__ */ jsx(
      FormFlow,
      {
        forms,
        activeForm,
        gotoFormByFormIndex,
        handleBackClick: handleToggleFormVisible,
        handleCancelClick: handleHomeClick,
        handleNextClick,
        loadingStatus,
        currentStep: steps.current,
        totalSteps: steps.total,
        children: /* @__PURE__ */ jsx(
          TaxReporting,
          {
            taxReportingClassification: taxReportingClassification?.taxClassification,
            taxRecommendationData,
            activeForm,
            data
          }
        )
      }
    ) })
  ] }) });
}
export {
  TaxReportingDropin
};
