;
{
  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] = "01016d98-eb05-4443-bacb-61d53b091fd1", e._sentryDebugIdIdentifier = "sentry-dbid-01016d98-eb05-4443-bacb-61d53b091fd1");
  } catch (e) {
  }
}
;
import "@tanstack/preact-query";
import { $ as httpPost, ad as httpDelete, k as httpGet, a3 as createLogger, b9 as StateContext, u as useTranslation, p as useAnalyticsContext, r as Icon, z as Typography, L as Loader, t as IconButton } from "./StoreProvider-CqQrndhS.js";
import { g as getLocalizedIdDocumentTypeOptions } from "./utils-DIFjlEiz.js";
import { jsx, jsxs } from "preact/jsx-runtime";
import cx from "classnames";
import { useEffect } from "preact/hooks";
const createDocument = async (context, document, ownerId) => {
  const { baseUrl, rootLegalEntityId } = context;
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${rootLegalEntityId}/documents/${ownerId}`
    },
    document
  );
};
const deleteDocument$1 = async (context, documentId) => {
  const { baseUrl, rootLegalEntityId } = context;
  return httpDelete({
    baseUrl,
    path: `legalEntities/${rootLegalEntityId}/documents/${documentId}/`
  });
};
const getDocument$1 = async (context, documentId) => {
  const { baseUrl, rootLegalEntityId } = context;
  return httpGet({
    baseUrl,
    path: `legalEntities/${rootLegalEntityId}/documents/${documentId}`
  });
};
const updateDocument = async (context, document, documentId, ownerId) => {
  const { baseUrl, rootLegalEntityId } = context;
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${rootLegalEntityId}/documents/${documentId}/${ownerId}`
    },
    document
  );
};
const isExistingFile = (file) => "existing" in file && file.existing;
const isNewlyUploadedFile = (file) => !isExistingFile(file);
const logger = createLogger();
const documentStore = {};
const idDocumentTypeOptions = getLocalizedIdDocumentTypeOptions();
const idTypes = idDocumentTypeOptions.map((types) => types.id);
let getDocumentService;
let updateDocumentService;
let createDocumentService;
let deleteDocumentService;
const documentApiUtils = (context) => {
  if (!getDocumentService || !updateDocumentService || !createDocumentService || !deleteDocumentService) {
    getDocumentService = (documentId) => getDocument$1(context, documentId);
    updateDocumentService = (document, documentId, ownerId) => updateDocument(context, document, documentId, ownerId);
    createDocumentService = (document, ownerId) => createDocument(context, document, ownerId);
    if (deleteDocument$1) {
      deleteDocumentService = (documentId) => deleteDocument$1(context, documentId);
    }
  }
  return {
    fetchDocuments,
    fetchDocument,
    uploadDocuments,
    deleteDocument
  };
};
const fetchDocuments = async (documentDetails, entityId) => {
  if (documentDetails.length === 0) return [];
  const documentPromises = [];
  documentDetails.forEach((documentDetail) => {
    documentPromises.push(fetchDocument(documentDetail));
  });
  const entityDocuments = await Promise.all(documentPromises);
  documentStore[entityId] = [];
  entityDocuments.forEach((document) => {
    const id = document.owner?.id;
    if (id) {
      documentStore[id].push(document);
    } else {
      logger.error("Document has no `owner.id`", document);
    }
  });
  return documentStore[entityId];
};
const fetchDocument = async (documentDetail) => {
  const document = await getDocumentService(documentDetail.id);
  return {
    ...document,
    modificationDate: documentDetail.modificationDate
  };
};
const deleteDocument = async (documentId) => deleteDocumentService(documentId);
const uploadDocuments = async (documents, entityId) => {
  const uploadPromises = [];
  const existingProofOfOwnershipAttachments = [];
  documents.forEach((document) => {
    const existingDocument = getDocument(entityId, document.type);
    if (document.type === "proofOfOwnership" && document.attachments) {
      const existingAttachments = document.attachments.filter((att) => !att.content);
      const newAttachments = document.attachments.filter((att) => att.content);
      document.attachments = newAttachments;
      existingProofOfOwnershipAttachments.push(...existingAttachments);
    }
    if (hasDocumentChanged(document, entityId) || document.type === "proofOfOwnership" && document.attachments?.length) {
      if (existingDocument && document.type !== "proofOfOwnership") {
        uploadPromises.push(updateDocumentService(document, existingDocument.id, entityId));
      } else {
        uploadPromises.push(createDocumentService(document, entityId));
      }
    }
  });
  const uploadedDocuments = await Promise.all(uploadPromises);
  if (existingProofOfOwnershipAttachments.length > 0) {
    const proofOfOwnershipDoc = uploadedDocuments.find((doc) => doc.type === "proofOfOwnership");
    if (proofOfOwnershipDoc) {
      proofOfOwnershipDoc.attachments = [
        ...existingProofOfOwnershipAttachments,
        ...proofOfOwnershipDoc.attachments ?? []
      ];
    }
  }
  const uploadedProofOfOwnershipDocuments = uploadedDocuments.filter(
    (doc) => doc.type === "proofOfOwnership"
  );
  if (uploadedProofOfOwnershipDocuments.length > 0) {
    documentStore[entityId] = documentStore[entityId].filter(
      (doc) => doc.type !== "proofOfOwnership"
    );
    const proofOfOwnershipWithModificationDate = uploadedProofOfOwnershipDocuments.map(
      (doc) => ({
        ...doc,
        modificationDate: (/* @__PURE__ */ new Date()).toISOString()
      })
    );
    documentStore[entityId].push(...proofOfOwnershipWithModificationDate);
  }
  updateEntityDocuments(uploadedDocuments, entityId);
  return documentStore[entityId];
};
const updateEntityDocuments = (uploadedDocuments, entityId) => {
  if (!documentStore[entityId]) documentStore[entityId] = [];
  uploadedDocuments.map(
    (doc) => ({
      ...doc,
      modificationDate: (/* @__PURE__ */ new Date()).toISOString()
    })
  ).forEach((uploadedDocument) => {
    const existingDocumentIndex = documentStore[entityId].findIndex(
      (document) => document.id === uploadedDocument.id
    );
    if (existingDocumentIndex > -1) {
      documentStore[entityId][existingDocumentIndex] = uploadedDocument;
    } else {
      documentStore[entityId].push(uploadedDocument);
    }
  });
};
const getDocument = (entityId, documentType) => {
  if (!entityId) {
    return;
  }
  return documentStore[entityId]?.find((document) => document.type === documentType);
};
const getDocuments = (entityId, documentType) => {
  if (!entityId) {
    return [];
  }
  return documentStore[entityId]?.filter(
    (document) => document.type === documentType
  ) ?? [];
};
const getIdDocument = (entityId) => documentStore[entityId]?.find((document) => idTypes.includes(document.type));
const createDocumentRequest = async ({
  entityId,
  entityType,
  documentType,
  page1,
  page2,
  description,
  existingDocument
}) => {
  const pagesToUpload = [page1, page2].filter(
    (page) => page !== void 0 && isNewlyUploadedFile(page)
  );
  const [page1ToUpload, page2ToUpload] = pagesToUpload;
  const [encodedPage1, encodedPage2] = await Promise.all(pagesToUpload.map(fileToBase64));
  if (!encodedPage1) {
    if (existingDocument && existingDocument.description !== description) {
      return {
        owner: {
          id: entityId,
          type: entityType
        },
        type: documentType,
        description: description || `Document type: ${documentType}`
      };
    }
    return;
  }
  return {
    owner: {
      id: entityId,
      type: entityType
    },
    type: documentType,
    description: description || `Document type: ${documentType}`,
    attachments: page1ToUpload && page2ToUpload && encodedPage1 && encodedPage2 ? [
      createAttachment(encodedPage1, page1ToUpload.name, "front"),
      createAttachment(encodedPage2, page2ToUpload.name, "back")
    ] : [createAttachment(encodedPage1, page1ToUpload.name)]
  };
};
const createAttachment = (content, pageName, pageType) => ({
  content,
  pageName,
  ...pageType && { pageType }
});
const hasDocumentChanged = (newDocument, entityId) => {
  const existingDocument = getDocument(entityId, newDocument.type);
  if (existingDocument) {
    return existingDocument.attachments.some(
      (attachment, index) => attachment.content !== newDocument?.attachments?.[index]?.content
    ) || existingDocument.description !== newDocument?.description;
  }
  return true;
};
const fileToBase64 = (file) => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    const base64String = reader.result.toString().split(";base64,")[1];
    resolve(base64String);
  };
  reader.onerror = (error) => reject(error);
});
const getFileExtention = (fileName) => fileName.split(".").pop();
const mergeAttachments = (existing, incoming) => {
  if (!existing?.length) return incoming;
  if (!incoming?.length) return existing;
  const incomingFileTypes = incoming.map((attachment) => attachment.pageType);
  const filteredExisting = existing.filter(
    (attachment) => !incomingFileTypes.includes(attachment.pageType)
  );
  return [...filteredExisting, ...incoming];
};
const mergeProofOfOwnershipAttachments = (existing, incoming) => {
  if (!existing?.length) return incoming;
  if (!incoming?.length) return existing;
  const incomingFileNames = incoming.map((attachment) => attachment.pageName);
  const filteredExisting = existing.filter(
    (attachment) => !incomingFileNames.includes(attachment.pageName)
  );
  const result = [...incoming, ...filteredExisting].slice(0, 2);
  return result;
};
function StateContextSetter({ stateRef }) {
  if (stateRef.current.setState) {
    return null;
  }
  return /* @__PURE__ */ jsx(StateContext.Consumer, { children: (stateContextValue) => {
    const { dispatch, setActiveForms } = stateContextValue;
    stateRef.current.setState = dispatch;
    stateRef.current.setActiveForms = setActiveForms;
    return null;
  } });
}
function bytesToSize(bytes) {
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  if (bytes === 0) return "n/a";
  const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)).toString());
  if (i === 0) return `${bytes} ${sizes[i]}`;
  return `${(bytes / 1024 ** i).toFixed()} ${sizes[i]}`;
}
function DropzoneFile(props) {
  const { file, errorMessage, onDelete, loading } = props;
  const { t } = useTranslation("common");
  const userEvents = useAnalyticsContext();
  let documentIcon;
  const formatSize = (bytes) => {
    const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    if (!bytes || bytes === 0) return "n/a";
    const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)).toString());
    if (i === 0) return `${bytes} ${sizes[i]}`;
    return `${(bytes / 1024 ** i).toFixed(1)} ${sizes[i]}`;
  };
  switch (file.type?.split("/")[0]) {
    case "image":
      documentIcon = "image";
      break;
    default:
      documentIcon = "document";
  }
  useEffect(() => {
    if (!errorMessage) return;
    userEvents.addFieldEvent("Encountered error", {
      actionType: "change",
      field: "dropzone file",
      returnType: "validation",
      returnValue: errorMessage
    });
  }, [errorMessage, userEvents]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cx("adyen-kyc-dropzone-file", { "adyen-kyc-dropzone-file--error": errorMessage }),
      children: [
        /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-dropzone-file__details", children: [
          /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-dropzone-file__labels", children: [
            errorMessage ? /* @__PURE__ */ jsx(
              Icon,
              {
                testId: "document-invalid",
                name: "warning",
                className: "adyen-kyc-dropzone-file__icon"
              }
            ) : /* @__PURE__ */ jsx(
              Icon,
              {
                testId: "document-valid",
                name: documentIcon,
                className: "adyen-kyc-dropzone-file__icon"
              }
            ),
            /* @__PURE__ */ jsx(Typography, { variant: "body-stronger", className: "adyen-kyc-dropzone-file__name", children: file.name }),
            /* @__PURE__ */ jsx(Typography, { className: "adyen-kyc-dropzone-file__size", children: isNewlyUploadedFile(file) && formatSize(file.size) })
          ] }),
          errorMessage && /* @__PURE__ */ jsx("div", { className: "adyen-kyc-dropzone-file__error", children: t(($) => $[errorMessage]) })
        ] }),
        loading ? /* @__PURE__ */ jsx("div", { className: "adyen-kyc-dropzone-file__loading", children: /* @__PURE__ */ jsx(Loader, { size: "medium" }) }) : errorMessage ? /* @__PURE__ */ jsx(
          IconButton,
          {
            ariaLabel: t(($) => $["close"]),
            icon: "cross",
            variant: "tertiary",
            onClick: onDelete
          }
        ) : /* @__PURE__ */ jsx(
          IconButton,
          {
            ariaLabel: t(($) => $["deleteDocument"]),
            icon: "bin",
            variant: "tertiary",
            onClick: onDelete
          }
        )
      ]
    }
  );
}
const hasDuplicates = (arr) => arr.some((item, currIndex) => arr.indexOf(item) !== currIndex);
const defaultFileValidationOptions = {
  allowedFileTypes: ["JPG", "JPEG", "PNG", "PDF"],
  maxNumberOfFiles: 1,
  maxSize: 4194304,
  // 4MB by default
  isOptional: false
};
const filterOnlyNewlyUploadedFiles = (files) => files.filter(isNewlyUploadedFile);
const fileValidationRules = ({
  allowedFileTypes,
  maxNumberOfFiles,
  maxSize,
  isOptional
}) => [
  {
    validate: (files) => {
      if (isOptional && (!files || files.length === 0)) return true;
      return Boolean(files && files.length > 0);
    },
    errorMessage: "fieldIsRequired",
    modes: ["blur", "input"]
  },
  {
    validate: (files) => {
      if (!files) return true;
      return files.length <= maxNumberOfFiles;
    },
    errorMessage: "tooManyFiles",
    modes: ["blur", "input"]
  },
  {
    validate: (files) => {
      if (!files) return true;
      return !hasDuplicates(files.map((file) => file.name));
    },
    errorMessage: "duplicatedFiles",
    modes: ["blur", "input"]
  },
  {
    validate: (files) => {
      if (!files) return true;
      return filterOnlyNewlyUploadedFiles(files).every(
        (file) => allowedFileTypes.some(
          (filetype) => file.name.toLowerCase().endsWith(filetype.toLowerCase())
        )
      );
    },
    errorMessage: "unsupportedFiletype",
    modes: ["blur", "input"]
  },
  {
    validate: (files) => {
      if (!files) return true;
      return filterOnlyNewlyUploadedFiles(files).every((file) => !file.size || file.size < maxSize);
    },
    errorMessage: "maximumFileSizeExceeded",
    modes: ["blur", "input"]
  }
];
export {
  DropzoneFile as D,
  StateContextSetter as S,
  getDocument as a,
  getFileExtention as b,
  createDocumentRequest as c,
  documentApiUtils as d,
  bytesToSize as e,
  defaultFileValidationOptions as f,
  getIdDocument as g,
  fileValidationRules as h,
  fileToBase64 as i,
  getDocuments as j,
  mergeProofOfOwnershipAttachments as k,
  mergeAttachments as m
};
