;
{
  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] = "e8df8fda-097d-4eeb-aede-c2ca3c37b312", e._sentryDebugIdIdentifier = "sentry-dbid-e8df8fda-097d-4eeb-aede-c2ca3c37b312");
  } catch (e) {
  }
}
;
import { i as isDateOlderThanAYear } from "./Address-DMDTO9vd.js";
import { aH as drop, b as useApiContext, k as httpGet, aa as useI18nContext, a3 as createLogger, i as isUndefinedOrNull, u as useTranslation } from "./StoreProvider-CqQrndhS.js";
import { jsx } from "preact/jsx-runtime";
import { useRef, useEffect, useCallback, useMemo, useState } from "preact/hooks";
import { useQuery } from "@tanstack/preact-query";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { I as InputText, a as InputBase } from "./InputText-DRSK56ma.js";
import { c as currencyByCountry } from "./types-BQgBwM6A.js";
const mapFinancialInformationToFinancialReport = ({
  currency,
  financialReportingDate,
  numberOfEmployees,
  balanceSheetTotal,
  netAssets,
  annualTurnover
}, dateOfIncorporation) => {
  if (dateOfIncorporation && !isDateOlderThanAYear(dateOfIncorporation)) {
    return {
      employeeCount: typeof numberOfEmployees === "number" ? numberOfEmployees.toFixed(0) : numberOfEmployees
    };
  }
  return {
    currencyOfFinancialData: currency,
    // TODO type this better
    dateOfFinancialData: financialReportingDate,
    employeeCount: typeof numberOfEmployees === "number" ? numberOfEmployees.toFixed(0) : numberOfEmployees,
    netAssets: netAssets?.toFixed(2) ?? void 0,
    balanceSheetTotal: balanceSheetTotal?.toFixed(2) ?? void 0,
    annualTurnover: annualTurnover?.toFixed(2) ?? void 0
  };
};
const mapFinancialReportsToFinancialInformation = (financialReports, withReportedValueOption = true) => {
  if (financialReports.length === 0) {
    throw new Error("No financial reports");
  }
  const mostRecentReport = financialReports.reduce((latest, curr) => {
    if (curr?.dateOfFinancialData && latest?.dateOfFinancialData && curr?.dateOfFinancialData > latest?.dateOfFinancialData) {
      return curr;
    }
    return latest;
  }, financialReports[0]);
  const financialInfo = {
    numberOfEmployees: mostRecentReport.employeeCount ? parseInt(mostRecentReport.employeeCount) : void 0,
    financialReportingDate: mostRecentReport.dateOfFinancialData,
    currency: mostRecentReport.currencyOfFinancialData
  };
  if (mostRecentReport.balanceSheetTotal !== void 0) {
    financialInfo.reportedValueOption = "balanceSheetTotal";
    financialInfo.balanceSheetTotal = parseFloat(mostRecentReport.balanceSheetTotal);
  }
  if (mostRecentReport.netAssets !== void 0) {
    financialInfo.reportedValueOption = "netAssets";
    financialInfo.netAssets = parseFloat(mostRecentReport.netAssets);
  }
  if (mostRecentReport.annualTurnover !== void 0) {
    financialInfo.reportedValueOption = "annualTurnover";
    financialInfo.annualTurnover = parseFloat(mostRecentReport.annualTurnover);
  }
  return withReportedValueOption ? financialInfo : drop("reportedValueOption").from(financialInfo);
};
const getLegalForms = async (countryCode, baseUrl) => {
  return httpGet({
    baseUrl,
    path: `datasets/legalForms/${countryCode}`
  });
};
const useLegalForms = (countryCode, options) => {
  const { baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["legalForms", countryCode],
    queryFn: () => getLegalForms(countryCode, baseUrl.value),
    ...options
  });
};
function LegalFormField({
  name = "legalForm",
  data,
  valid,
  errorMessage,
  label,
  readonly,
  handleChangeFor,
  countryCode
}) {
  const { i18n } = useI18nContext();
  const { data: legalFormsData } = useLegalForms(countryCode);
  const handleChangeForRef = useRef(handleChangeFor);
  useEffect(() => {
    handleChangeForRef.current = handleChangeFor;
  }, [handleChangeFor]);
  const handleChangeForLegalForm = useCallback(
    (e) => {
      const legalFormEvent = {
        target: {
          name: "legalForm",
          value: e.target.value
        }
      };
      handleChangeFor("legalForm")(legalFormEvent);
    },
    [handleChangeFor]
  );
  useEffect(() => {
    const selectedLabel = legalFormsData?.find(
      (legalForm) => legalForm.id === data.legalForm
    )?.name;
    const legalFormEvent = {
      target: {
        name: "legalFormLabel",
        value: selectedLabel
      }
    };
    handleChangeForRef.current("legalFormLabel")(legalFormEvent);
  }, [data.legalForm, legalFormsData]);
  return /* @__PURE__ */ jsx(
    Field,
    {
      name,
      label: label || i18n.get("businessStructure"),
      errorMessage,
      isValid: valid.legalForm,
      children: (childProps) => /* @__PURE__ */ jsx(
        Select,
        {
          ...childProps,
          name,
          placeholder: i18n.get("selectOne"),
          selected: data.legalForm,
          items: legalFormsData ?? [],
          readonly: readonly && !!data,
          onChange: handleChangeForLegalForm
        }
      )
    }
  );
}
const logger = createLogger();
const determineDecimalSeparator = (formatter) => formatter.formatToParts(0.1).find((part) => part.type === "decimal").value;
const determineCurrencySymbol = (formatter) => formatter.formatToParts(0).find((part) => part.type === "currency").value;
const getNumberFromFormattedCurrency = (formatted, decimalSeparator) => {
  const lastDecimalIndex = formatted.lastIndexOf(decimalSeparator);
  const normalized = Array.from(formatted).reduce((acc, curr, i) => {
    if (/[0-9]/.test(curr)) return acc + curr;
    if (i === lastDecimalIndex) return `${acc}.`;
    return acc;
  }, "");
  return parseFloat(normalized);
};
const InputCurrency = ({
  locale,
  currency,
  amount,
  onAmountChanged,
  ...baseProps
}) => {
  const formatter = useMemo(
    () => new Intl.NumberFormat(locale, { style: "currency", currency }),
    [locale, currency]
  );
  const decimalSeparator = useMemo(() => determineDecimalSeparator(formatter), [formatter]);
  const currencySymbol = useMemo(() => determineCurrencySymbol(formatter), [formatter]);
  const [text, setText] = useState("");
  const onInput = (e) => {
    setText(e.currentTarget.value);
  };
  const onBlur = (e) => {
    const rawValue = e.currentTarget.value;
    const value = getNumberFromFormattedCurrency(rawValue, decimalSeparator);
    if (Number.isNaN(value)) {
      logger.warn(`Unable to get number from formatted currency: "${rawValue}"`);
      setText(isUndefinedOrNull(amount) ? currencySymbol : formatter.format(amount));
      return;
    }
    onAmountChanged(value);
  };
  useEffect(() => {
    setText(isUndefinedOrNull(amount) ? currencySymbol : formatter.format(amount));
  }, [amount, currencySymbol, formatter]);
  return /* @__PURE__ */ jsx(InputText, { ...baseProps, value: text, onInput, onBlur });
};
function InputNumber(props) {
  return /* @__PURE__ */ jsx(InputBase, { ...props, type: "number" });
}
const CURRENCY_FIELD = ["currency"];
function Currency({
  data,
  valid,
  errors,
  labels,
  readonly,
  handleChangeFor,
  country
}) {
  const { t } = useTranslation("common");
  const currenciesForCurrCountry = currencyByCountry[country];
  const countryCurrenciesItems = currenciesForCurrCountry ? currenciesForCurrCountry.map((currency) => ({ id: currency, name: currency })) : [];
  return /* @__PURE__ */ jsx("div", { className: "adyen-kyc-field__currency", children: /* @__PURE__ */ jsx(
    Field,
    {
      name: "currency",
      label: labels.currency,
      errorMessage: errors.currency,
      isValid: valid.currency,
      dataTestId: "currency",
      children: (childProps) => /* @__PURE__ */ jsx(
        Select,
        {
          ...childProps,
          onChange: handleChangeFor("currency", "blur"),
          name: "currency",
          placeholder: t(($) => $["currencyPlaceholder"]),
          selected: data.currency,
          items: countryCurrenciesItems,
          readonly: readonly && !!data.currency
        }
      )
    }
  ) });
}
export {
  Currency as C,
  InputNumber as I,
  LegalFormField as L,
  mapFinancialInformationToFinancialReport as a,
  CURRENCY_FIELD as b,
  InputCurrency as c,
  mapFinancialReportsToFinancialInformation as m
};
