function getLang(lan) {
	const lans = {
	  zh: {
	    "银行卡号": "银行卡号",
	    "有效期": "有效期",
	    "安全码": "安全码",
	    "确认": "确认",
	  },
	  en: {
	    "银行卡号": "Card number",
	    "有效期": "Expiry",
	    "安全码": "CVC",
	    "确认": "Confirm",
	  },
	  es: {
	    "银行卡号": "Número de tarjeta",
	    "有效期": "validez",
	    "安全码": "El Código de Seguridad",
	    "确认": "Confirmar",
	  }
	};
	
	if (!lan) return lans.en;
	return lans[lan]
}

let paramsOfAirwallex = {};

(function () {
	let elementId = document.getElementById('element');
  let lan = 'en';
	
	function initAirwallex() {
		try {
		  Airwallex.init({
		    env: "prod",
		    origin: window.location.origin,
		    locale: lan
		  });
		  const cardNumber = Airwallex.createElement("cardNumber");
		  const expiry = Airwallex.createElement("expiry");
		  const cvc = Airwallex.createElement("cvc");
		  cardNumber.mount("cardNumber");
		  expiry.mount("expiry");
		  cvc.mount("cvc");
			sendMessage({ status: 'loading', res: { state: false } })
		} catch (error) {
		  console.error("------ int Airwallex There was an error -------", error);
		}
	}
	
	function initElement() {
		const findItem = getLang(lan);
		console.log('---- findItem -----', JSON.stringify(findItem))
		let childHtml = `<div class="field-container">
		    <div>${findItem['银行卡号']}</div>
		    <div id="cardNumber"></div>
		    <p id="cardNumber-error" style="color: red;"></p>
		  </div>
		  <div class="field-container">
		    <div>${findItem['有效期']}</div>
		    <div id="expiry"></div>
		    <p id="expiry-error" style="color: red;"></p>
		  </div>
		  <div class="field-container">
		    <div>${findItem['安全码']}</div>
		    <div id="cvc"></div>
		    <p id="cvc-error" style="color: red;"></p>
		  </div>
		  <div id="submit" class="submit">${findItem['确认']}</div>`
		  elementId.innerHTML = childHtml;
			
			handleEventBind();
	}
	
  window.addEventListener('appMessage', function (e) {
    console.log("------ appMessage ------", JSON.stringify(e.detail));
    const { type, lan: lang, ...payData } = e.detail;
		paramsOfAirwallex = payData;
		lan = lang;
		
		// sendMessage({ status: 'loading', res: { state: true } })
		initElement();
		let timer = setTimeout(() => {
			initAirwallex();
			clearTimeout(timer);
			timer = null;
		}, 100)
  });
})()


function sendMessage(data = {}) {
	location.href = `callback?str=${escape(JSON.stringify(data))}`
}


function handleEventBind() {
	document.getElementById("submit").addEventListener("click", () => {
		sendMessage({ status: 'loading', res: { state: true } })
		
	  Airwallex.confirmPaymentIntent({
	    element: Airwallex.getElement("cardNumber"),
	    id: paramsOfAirwallex.intent_id,
	    client_secret: paramsOfAirwallex.client_secret
	  })
		.then((response) => {
			sendMessage({ status: 'success', res: response })
	  })
		.catch((response) => {
			sendMessage({ status: 'error', res: response })
	    console.log("---------- submit There was an error ----------", JSON.stringify(response));
	  })
		.finally(() => {
			sendMessage({ status: 'loading', res: { state: false } })
		});
	});
	
	const elementsReady = {
	  cardNumber: false,
	  expiry: false,
	  cvc: false
	};
	const cardNumberElement = document.getElementById("cardNumber");
	const expiryElement = document.getElementById("expiry");
	const cvcElement = document.getElementById("cvc");
	const domElementArray = [cardNumberElement, expiryElement, cvcElement];
	
	domElementArray.forEach((element) => {
	  element.addEventListener("onReady", (event) => {
	    const { type } = event.detail;
	    if (elementsReady.hasOwnProperty(type)) {
	      elementsReady[type] = true;
	    }
	
	    if (!Object.values(elementsReady).includes(false)) {
	      document.getElementById("element").style.display = "block";
	    }
	  });
	});
	
	const elementsCompleted = {
	  cardNumber: false,
	  expiry: false,
	  cvc: false
	};
	
	domElementArray.forEach((element) => {
	  element.addEventListener("onChange", (event) => {
	    const { type, complete } = event.detail;
	    if (elementsCompleted.hasOwnProperty(type)) {
	      elementsCompleted[type] = complete;
	    }
	    const allElementsCompleted = !Object.values(
	      elementsCompleted
	    ).includes(false);
	    document.getElementById("submit").disabled = !allElementsCompleted;
	  });
	});
	
	domElementArray.forEach((element) => {
	  element.addEventListener("onFocus", (event) => {
	    const { type } = event.detail;
	    const element = document.getElementById(type + "-error");
	    if (element) {
	      element.innerHTML = "";
	    }
	  });
	});
	domElementArray.forEach((element) => {
	  element.addEventListener("onBlur", (event) => {
	    const { error, type } = event.detail;
	    const element = document.getElementById(type + "-error");
	    if (element && error) {
	      element.innerHTML = error.message || JSON.stringify(error);
	    }
	  });
	});
	
	/* domElementArray.forEach((element) => {
	  element.addEventListener("onBlur", (event) => {
	    console.error("There was an error", event.detail.error);
	  });
	}); */
}


