import { LayoutUnit } from "../../../../layout/LayoutUnit.mjs";
import { PaymentTenderTypeEnum } from "../../../../enums/paymentTenderTypeEnum.mjs";
import { CircularProgress as CircularProgress$1 } from "../../../../UI/loading/CircularProgress.mjs";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Box, InputLabel, Typography, useTheme } from "@material-ui/core";
import { useTranslation } from "react-i18next";
//#region src/utilities/form/paymentForm/vendorsForms/FiservForm.tsx
const defaultCssStyles = (theme) => {
	return `
input, button, select {
  font-family: 'Segoe UI', Roboto, Noto, 'Helvetica Neue', Helvetica, Ubuntu, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  font-size: 14px;
  line-height: 1.1876em;
  height: 16.6146px;
  border: 1px solid ${theme.palette.grey[400]};
  border-radius: 2px;
  color: currentColor;
  width: 80%;
  height: 1.1876em;
  margin: 8px 0px 0px 0px;
  display: block;
  padding: 6px 0px 6px 5px;
  min-width: 0;
  background: none;
  box-sizing: content-box;
  animation-name: mui-auto-fill-cancel;
  letter-spacing: inherit;
  animation-duration: 10ms;
}
input:focus, button:focus, select:focus {
  outline: none;
  border-color: ${theme.palette.primary.main};
  box-shadow: 0px 0px 3px ${theme.palette.primary.main};
}
#ccexpirymonth, #ccexpiryyear {
  display: inline-block;
  vertical-align: middle;
}
#ccexpirymonth, #ccexpiryyear {
  width: 30%;
}
br {
  display: none;
}
button {
  background-color: ${theme.palette.primary.main};
  color: ${theme.palette.background.paper};
  text-transform: uppercase;
}
label {
  display: block;
  font-family: "Segoe UI", Roboto, Noto, "Helvetica Neue", Helvetica, Ubuntu, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !important;
  font-size: 14px;
  color: ${theme.palette.text.secondary};
  margin-top: 10px;
}
.error {
  color: ${theme.palette.error.main};
  border-color: ${theme.palette.error.main};
}
::placeholder {
  color: ${theme.palette.grey[500]};
}`.trim();
};
const DEFAULT_CREDIT_CARD_PLACEHOLDERS = "`placeholder=Enter Card Details&placeholdercvv=123&placeholdermonth=MM&placeholderyear=YYYY`;";
const DEFAULT_CREDIT_CARD_FEATURES = `&useexpiry=true&usecvv=true&invalidcreditcardevent=true&formatinput=true&unique=true&enhancedresponse=true&cardnumbernumericonly=true`;
const DEFAULT_ECHECK_PLACEHOLDERS = `placeholder=Routing Number / Account Number`;
const DEFAULT_ECHECK_FEATURES = `&fullmobilekeyboard=true`;
/**
* `FiservForm` Component
*
* This component is responsible for rendering an iframe for payment processing tailored for the Fiserv payment gateway. It manages the dynamic creation of the iframe URL based on the provided attributes and configures the iframe behavior accordingly.
*
* @param {Object} {
*   paymentMethod = PaymentTenderTypeEnum.CreditCard,
*   baseUrl = "https://fts-uat.cardconnect.com/itoke/ajax-tokenizer.html",
*   customCss = defaultCssStyles,
*   attributes = null
* } The properties passed to the component.
* @param {PaymentTenderTypeEnum} [paymentMethod=PaymentTenderTypeEnum.CreditCard] The payment method type, affecting the endpoint.
* @param {Object} [onStatusChange=null] Callback function to handle the status change event.
* @param {string} [baseUrl="https://fts-uat.cardconnect.com/itoke/ajax-tokenizer.html"] The base URL for the Fiserv payment gateway iframe.
* @param {string} [customCss=defaultCssStyles] Custom CSS to apply within the iframe.
* @param {Object} [attributes=null] Additional payment attributes to append as query parameters.
* @param {string} [attributes.placeholder] Placeholder text for the card fields.
* @param {string} [attributes.placeholdercvv] Placeholder text for the CVV field.
* @param {string} [attributes.placeholdermonth] Placeholder for the expiration month field.
* @param {string} [attributes.placeholderyear] Placeholder for the expiration year field.
* @param {boolean} [attributes.useexpiry=true] Flag to enable the use of the expiration date.
* @param {boolean} [attributes.usecvv=true] Flag to enable the use of the CVV code.
* @param {boolean} [attributes.invalidcreditcardevent=true] Event triggered on invalid card input.
* @param {boolean} [attributes.formatinput=true] Formats the card input fields.
* @param {boolean} [attributes.unique=true] Ensures unique card number inputs.
* @param {boolean} [attributes.enhancedresponse=true] Provides enhanced responses.
* @param {boolean} [attributes.cardnumbernumericonly=true] Allows only numeric input for the card number.
* @param {boolean} [attributes.fullmobilekeyboard=false] Enables full mobile keyboard access.
*
* @return {React.Component} The `FiservForm` component that handles the rendering of the payment iframe and processes payment data or errors.
*/
const FiservForm = ({ paymentMethod = PaymentTenderTypeEnum.CreditCard, onStatusChange = (paymentFormResult) => {}, baseUrl = "https://fts-uat.cardconnect.com/itoke/ajax-tokenizer.html", customCss = "", attributes = null, paymentData = null }) => {
	const [loading, setLoading] = useState(true);
	const [token, setToken] = useState("");
	const [error, setError] = useState(null);
	const { t } = useTranslation();
	const defaultCss = defaultCssStyles(useTheme());
	/**
	* handleFiservResponse
	*
	* @param {*} response
	*/
	const handleFiservResponse = useCallback((response) => {
		let isError;
		if (paymentMethod === PaymentTenderTypeEnum.CreditCard) isError = response?.errorCode !== "0" || response?.errorMessage || !response?.token;
		else if (paymentMethod === PaymentTenderTypeEnum.ECheck) isError = !response?.message;
		onStatusChange({
			isValid: !isError,
			payload: response,
			message: response?.message,
			errorCode: response?.errorCode,
			errorMessage: response?.errorMessage
		});
	}, [onStatusChange, paymentMethod]);
	const handleLoad = () => {
		setLoading(false);
	};
	const handleError = () => {
		setLoading(false);
	};
	useEffect(() => {
		const handleMessage = (event) => {
			try {
				const data = JSON.parse(event.data);
				setToken(data.message);
				handleFiservResponse(data);
			} catch (error_0) {
				console.error("Error parsing the event data", error_0);
			}
		};
		window.addEventListener("message", handleMessage, false);
		return () => {
			window.removeEventListener("message", handleMessage, false);
		};
	}, [paymentMethod]);
	/**
	* iFrameURL
	*
	* @return {*}
	*/
	const iFrameURL = useMemo(() => {
		let url = "";
		try {
			const encodedCss = encodeURIComponent(customCss || defaultCss);
			switch (paymentMethod) {
				case PaymentTenderTypeEnum.CreditCard:
					const creditCardCssStyles = `css=${encodedCss}`;
					const queryParams = attributes ? Object.entries(attributes)?.map(([key_0, value_0]) => `${key_0.toLowerCase()}=${value_0?.toString()}`).join("&") : "";
					url = attributes ? `${queryParams}&${creditCardCssStyles}` : `${DEFAULT_CREDIT_CARD_PLACEHOLDERS}&${creditCardCssStyles}${DEFAULT_CREDIT_CARD_FEATURES}`;
					break;
				case PaymentTenderTypeEnum.ECheck:
					const eCheckCssStyles = `css=${encodedCss}`;
					const queryParamsECheck = attributes ? Object.entries(attributes)?.map(([key, value]) => `${key.toLowerCase()}=${value?.toString()}`).join("&") : "";
					url = attributes ? `${queryParamsECheck}&${eCheckCssStyles}` : `${DEFAULT_ECHECK_PLACEHOLDERS}&${eCheckCssStyles}${DEFAULT_ECHECK_FEATURES}`;
					break;
				default: url = "";
			}
		} catch (error_1) {
			setError(error_1?.message);
		}
		return `
        ${url}
        `.trim();
	}, [paymentMethod]);
	return /* @__PURE__ */ React.createElement("div", null, error ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Typography, {
		variant: "subtitle1",
		color: "error"
	}, t("There was an error rendering the hosted payment form. Please check your settings and try again"), ":"), /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "xxs" }), /* @__PURE__ */ React.createElement(Typography, {
		variant: "body1",
		color: "error"
	}, t("Error"), ":", error)) : /* @__PURE__ */ React.createElement("form", {
		name: "tokenform",
		id: "tokenform"
	}, paymentMethod === PaymentTenderTypeEnum.ECheck && /* @__PURE__ */ React.createElement(InputLabel, { style: {
		fontSize: 15,
		marginLeft: 10
	} }, t("eCheck Information")), loading && /* @__PURE__ */ React.createElement(Box, { sx: {
		position: "fixed",
		top: 0,
		left: 0,
		width: "100%",
		height: "100%",
		backgroundColor: "rgba(255, 255, 255, 0.8)",
		zIndex: 9999,
		display: "flex",
		alignItems: "center",
		justifyContent: "center"
	} }, /* @__PURE__ */ React.createElement(CircularProgress$1, {
		size: "3rem",
		color: "primary"
	})), /* @__PURE__ */ React.createElement("iframe", {
		id: "tokenframe",
		name: "tokenframe",
		src: `${baseUrl}?${iFrameURL}`,
		scrolling: "yes",
		width: "100%",
		height: "220",
		frameBorder: "0",
		onLoad: handleLoad,
		onError: handleError,
		style: { display: loading ? "none" : "block" }
	})));
};
//#endregion
export { FiservForm };

//# sourceMappingURL=FiservForm.mjs.map