;
{
  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] = "2856a03a-295c-4168-b162-a60a1033e5bf", e._sentryDebugIdIdentifier = "sentry-dbid-2856a03a-295c-4168-b162-a60a1033e5bf");
  } catch (e) {
  }
}
;
import { useQuery, useMutation } from "@tanstack/preact-query";
import { b as useApiContext, k as httpGet, ai as isEmpty, u as useTranslation, v as useExperimentsContext, t as IconButton, $ as httpPost } from "./StoreProvider-CqQrndhS.js";
import { jsx, jsxs, Fragment } from "preact/jsx-runtime";
import { useRef, useMemo, useState, useEffect } from "preact/hooks";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { L as List } from "./List-BAzyC6sw.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { signal } from "@preact/signals";
const fetchIndustryCodes = async (legalEntityId, baseUrl, businessLineTypes2, locale) => {
  const results = await Promise.all(
    businessLineTypes2.map((businessLineType) => {
      return httpGet({
        baseUrl,
        path: `legalEntities/${legalEntityId}/businessLines/${businessLineType}/industryCodes?locale=${locale}`
      });
    })
  );
  const deduped = [];
  for (const result of results) {
    for (const industryCodeDTO of result) {
      const found = deduped.find((item) => item.code === industryCodeDTO.code);
      if (!found) {
        deduped.push(industryCodeDTO);
      }
    }
  }
  return deduped;
};
const useIndustryCodes = (businessLineTypes2, locale, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["industryCodes", businessLineTypes2.join(","), locale],
    queryFn: () => fetchIndustryCodes(rootLegalEntityId.value, baseUrl.value, businessLineTypes2, locale),
    ...options
  });
};
const industryCodeFieldValidation = () => ({
  industryCodes: {
    modes: ["blur"],
    validate: (industryCode) => !isEmpty(industryCode),
    errorMessage: "fieldIsRequired"
  }
});
const industryCodeFieldMetadata = {
  label: "industry",
  validators: [
    industryCodeFieldValidation().industryCodes
  ]
};
const selectedBusinessLine = signal(void 0);
const shouldSignNewPci = signal(false);
const industryCodesContent = "adyen-kyc-industry-codes-content";
const industryCodesSelection = "adyen-kyc-industry-codes-selection";
const styles$1 = {
  industryCodesContent,
  industryCodesSelection
};
const mapSelectedCodes = (selectedCodes) => {
  return selectedCodes && selectedCodes.length > 0 ? selectedCodes.map((i) => {
    return {
      value: i,
      touched: !!i.id
    };
  }) : [{ value: { id: "", name: "" }, touched: false }];
};
function IndustryCodeField({
  data,
  valid,
  errors,
  labels,
  readonly,
  handleChangeFor,
  guidanceText,
  setErrors,
  // need to manually set errors due to nested select components
  setValid,
  // need to manually set validation due to nested select components
  businessLineTypes: businessLineTypes2,
  single = false,
  industryCodes,
  existingBusinessLines
}) {
  const { t } = useTranslation("ui");
  const industryCodesRef = useRef(null);
  const { isExperimentEnabled } = useExperimentsContext();
  const singleIndustryCode = single || !!selectedBusinessLine.value || // when editing a business line, only single dropdown should render
  isExperimentEnabled("EnableLimitToSingleBusinessLine");
  const allIndustryCodeSelectItems = useMemo(
    () => industryCodes?.map((entry) => ({
      id: entry.code,
      name: `${entry.code} - ${entry.description}`
    })) ?? [],
    [industryCodes]
  );
  const selectableIndustryCodes = useMemo(() => {
    if (!businessLineTypes2.includes("acquiring")) return allIndustryCodeSelectItems;
    const selectedIds = data.industryCodes?.map((c) => c.id);
    const existingIds = (existingBusinessLines ?? []).map((b) => b.industryCode);
    return allIndustryCodeSelectItems.filter((item) => {
      const isDuplicate = selectedIds?.includes(item.id) || existingIds?.includes(item.id);
      return !isDuplicate;
    });
  }, [allIndustryCodeSelectItems, businessLineTypes2, data.industryCodes, existingBusinessLines]);
  const selectedCodes = data.industryCodes;
  const [items, setItems] = useState(mapSelectedCodes(selectedCodes));
  useEffect(() => {
    setItems(mapSelectedCodes(selectedCodes));
  }, [selectedCodes]);
  const updateIndustryCodes = (value) => {
    handleChangeFor("industryCodes")(value);
  };
  const addIndustryCodeField = (e) => {
    if (items[items.length - 1].value.id === "") {
      handleIndustryCodeFocusOut(e, items.length - 1);
      return;
    }
    const newItems = [...items, { value: { id: "", name: "" }, touched: false }];
    setItems(newItems);
    updateIndustryCodes(newItems.map((item) => item.value));
  };
  const removeField = (indexToRemove) => {
    const newItems = items.filter((_, index) => index !== indexToRemove);
    setItems(newItems);
    updateIndustryCodes(newItems.map((item) => item.value));
  };
  const handleSelectIndustryCode = (indexToUpdate, selectedItem) => {
    setItems((prevItems) => {
      const newItems = [...prevItems];
      newItems[indexToUpdate] = {
        value: {
          id: selectedItem.id,
          name: selectedItem.name
        },
        touched: true
      };
      updateIndustryCodes(
        newItems.map((item) => {
          return {
            id: item.value.id,
            name: item.value.name
          };
        })
      );
      return newItems;
    });
  };
  const handleIndustryCodeFocusOut = (e, index) => {
    if (industryCodesRef.current && !industryCodesRef.current.contains(e.relatedTarget)) {
      setItems((prevItems) => {
        if (prevItems[index].value.id || prevItems[index].touched) {
          return prevItems;
        }
        const newItems = [...prevItems];
        newItems[index] = { ...newItems[index], touched: true };
        const isGroupInvalid = newItems.some((item) => item.value.id === "");
        if (isGroupInvalid) {
          setErrors?.(
            "industryCodes",
            {
              isValid: false,
              errorMessage: "fieldIsRequired",
              hasError: true
            },
            "industryCodesForm"
          );
          setValid?.("industryCodes", false, "industryCodesForm");
        } else {
          setErrors?.("industryCodes", null, "industryCodesForm");
          setValid?.("industryCodes", true, "industryCodesForm");
        }
        return newItems;
      });
    }
  };
  return /* @__PURE__ */ jsx(
    Field,
    {
      name: "industryCodes",
      label: labels?.industryCodes || t(($) => $["industry"]),
      errorMessage: errors.industryCodes,
      isValid: valid.industryCodes,
      formatGuidance: guidanceText.industryCodes,
      showErrorIcon: false,
      children: (childProps) => /* @__PURE__ */ jsx(Wrapper, { single: singleIndustryCode, children: /* @__PURE__ */ jsx(
        "div",
        {
          className: styles$1.industryCodesContent,
          ref: industryCodesRef,
          "data-testid": "industryCode",
          children: items.map((code, index) => {
            const isInvalid = code.touched && code.value.id === "";
            return /* @__PURE__ */ jsxs("div", { className: styles$1.industryCodesSelection, children: [
              /* @__PURE__ */ jsx(
                Select,
                {
                  ...childProps,
                  id: `industryCodeSelection-${index}`,
                  name: `industryCodeSelection-${index}`,
                  selected: code.value,
                  placeholder: t(($) => $["industryCode__placeholder"]),
                  items: allIndustryCodeSelectItems,
                  excludedValues: allIndustryCodeSelectItems.filter(
                    (i) => !selectableIndustryCodes.includes(i)
                  ),
                  readonly: !!data.industryCodes && readonly || !!industryCodes && selectableIndustryCodes.length === 0,
                  onSelect: (selectedItem) => handleSelectIndustryCode(index, selectedItem),
                  isInvalid,
                  onBlur: (e) => handleIndustryCodeFocusOut(e, index)
                }
              ),
              !singleIndustryCode && /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    ariaLabel: t(($) => $["removeIndustryCode"]),
                    variant: "tertiary",
                    icon: "minusCircleFilled",
                    circle: true,
                    onClick: () => removeField(index),
                    disabled: items.length === 1 || readonly
                  }
                ),
                /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    ariaLabel: t(($) => $["addIndustryCode"]),
                    variant: "tertiary",
                    icon: "plusCircleFilled",
                    circle: true,
                    onClick: addIndustryCodeField,
                    disabled: readonly || code.value.id === "" || code.value.id !== "" && index !== items.length - 1 || selectableIndustryCodes.length === 0
                  }
                )
              ] })
            ] }, code.value.id);
          })
        }
      ) })
    }
  );
}
function Wrapper({ single, children }) {
  return single ? children : /* @__PURE__ */ jsx(List, { dividers: false, variant: "grouped-primary", children });
}
const salesChannelsWithWebData = ["eCommerce", "ecomMoto"];
const SALES_CHANNELS_FIELD = ["salesChannels"];
const WEB_DATA_FIELD = ["webAddress", "webExempt"];
const INDUSTRY_CODE_FIELD = ["industryCodes"];
const SCTA_FIELD = ["sctaUrl", "sctaExempt"];
const businessLinesConfigurations = {
  industryCodes: { rule: "REQUIRED" },
  salesChannels: { rule: "REQUIRED" },
  webAddress: { rule: "webAddressRequired" },
  webExempt: { rule: "OPTIONAL" },
  sctaUrl: { rule: "sctaUrlRequired" },
  sctaExempt: { rule: "OPTIONAL" }
};
const businessLinesForms = {
  industryCodesForm: {
    formId: "industryCodesForm",
    formName: "industryCodesForm",
    fields: INDUSTRY_CODE_FIELD
  },
  salesChannelsForm: {
    formId: "salesChannelsForm",
    formName: "paymentProcessing",
    fields: [...SALES_CHANNELS_FIELD, ...WEB_DATA_FIELD]
  },
  sctaForm: {
    formId: "sctaForm",
    formName: "japaneseCommercialDisclosure",
    fields: SCTA_FIELD
  }
};
const businessLineTypes = ["acquiring"];
const divider = "adyen-kyc-divider";
const styles = {
  divider
};
const Divider = () => /* @__PURE__ */ jsx("hr", { className: styles.divider });
const createBusinessLine = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/businessLines`
    },
    data
  );
};
const useCreateBusinessLine = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useMutation({
    mutationFn: (data) => createBusinessLine(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const updateBusinessLine = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/businessLines/${data.id}`
    },
    data
  );
};
const useUpdateBusinessLine = (options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useMutation({
    mutationFn: (data) => updateBusinessLine(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
export {
  Divider as D,
  INDUSTRY_CODE_FIELD as I,
  SALES_CHANNELS_FIELD as S,
  WEB_DATA_FIELD as W,
  IndustryCodeField as a,
  useCreateBusinessLine as b,
  useUpdateBusinessLine as c,
  businessLineTypes as d,
  shouldSignNewPci as e,
  SCTA_FIELD as f,
  selectedBusinessLine as g,
  businessLinesConfigurations as h,
  industryCodeFieldMetadata as i,
  businessLinesForms as j,
  salesChannelsWithWebData as s,
  useIndustryCodes as u
};
