$(function() {
	$(".faq-accordion .faq-accordion-title").on("click", function() {
		if (!$(this).hasClass("active")) {
			$(this).addClass("active");
			$(this).next().show();
		} else {
			$(this).removeClass("active");
			$(this).next().hide();
		}

	})

	const phone = document.querySelector("#phone");
	const phone_2 = document.querySelector("#phone2");

	iti = window.intlTelInput(phone, {
		geoIpLookup: function(callback) {
			$.get("https://ipinfo.io", function() { }, "jsonp").always(function(resp) {
				var countryCode = resp && resp.country ? resp.country : "DE";
				country = countryCode;
				callback(countryCode);
			});
		},
		initialCountry: "auto",
		utilsScript: "./utils.js",
		separateDialCode: true,
	});

	iti_2 = window.intlTelInput(phone_2, {
		geoIpLookup: function(callback) {
			$.get("https://ipinfo.io", function() { }, "jsonp").always(function(resp) {
				var countryCode = resp && resp.country ? resp.country : "DE";
				callback(countryCode);
			});
		},
		initialCountry: "auto",
		utilsScript: "./utils.js",
		separateDialCode: true,
	});

	function validateForm(form, data, initType) {
		const errors = [];

		for (const input in data) {
			const value = data[input];

			if (input === "phone" && value) {
				const errorMap = [
					"Invalid number",
					"Invalid country code",
					"Too short number",
					"Too long number",
					"Invalid number",
				];

				if (value.trim()) {
					if (!initType.isValidNumber()) {
						const errorCode = initType.getValidationError();

						$(`.phone-validation`).html(errorMap[errorCode]);
						$(`.phone-validation`).show();
						errors.push(input);
					}
				}
			}
		}

		return errors;
	}

	$("input").on("input", function() {
		const inputName = $(this).attr("name");
		const phoneValidation = $(`.phone-validation`);

		if (inputName === "phone") {
			phoneValidation.removeClass("error");
			phoneValidation.html("");
		}
	});

	function submitForm(form, initType) {
		event.preventDefault();

		let formData = {
			uri_query: window.location.search.replace("?", ""),
		};
		const serializedData = form.serializeArray();

		serializedData.forEach(({ name, value }) => {
			if (name === "phone") {
				formData[name] = initType.getNumber();
			} else {
				formData[name] = value;
			}
		});

		const errors = validateForm(form, formData, initType);

		if (errors.length) return;

		const submitButton = $('button[type="submit"]');
		const loader = $(".loader-wrapper");

		$.ajax({
			type: "POST",
			url: "send.php",
			data: formData,
			dataType: "json",
			beforeSend: function() {
				submitButton.attr("disabled", "disabled");
				loader.addClass("open");
			},
			success: function(res) {

				const url = res?.data?.data?.loginURL;

				if (url) {
					const urlParams = new URLSearchParams(window.location.search);
					const pixelId = urlParams.get('pixel');

					if (pixelId) {
						$("head").append(`
							<img height="1" width="1" style="display:none"
							src="https://www.facebook.com/tr?id=${pixelId}&ev=Lead&noscript=1"
							/>
						`)
					}

					window.location.href = url;
				}


				submitButton.removeAttr("disabled");

			},
			error: function(error) {
				submitButton.removeAttr("disabled");
				loader.removeClass("open");
				alert("Something went wrong. Please try to change your email or phone number.");
				throw new Error("Something went wrong", { cause: error });
			},
		});
	}

	$("form#form, form#form2").on("submit", function(event) {
		const formLink = $(this);
		let type = iti;

		if (formLink.attr("id") === "form2") {
			type = iti_2
		}

		submitForm(formLink, type);
		event.stopImmediatePropagation();
	});
});