document.addEventListener("DOMContentLoaded", function() {



	const onboardingWrap = document.querySelector(".sensfrxOnboaredingwrap");

    // If element not found, stop execution

    if (!onboardingWrap) {

        return;

    }

	const step0 = document.getElementById("step-0");

	const step1 = document.getElementById("step-1");

	const step2 = document.getElementById("step-2");

	const step3 = document.getElementById("step-3");

	const step4 = document.getElementById("step-4");

	// Step 0 to Step 1

	const connectBtn = document.getElementById("sensfrxOnboardingConnect-btn");

	if (connectBtn) {

		connectBtn.addEventListener("click", function() {

			step0.style.display = "none";

			step1.style.display = "block";

		});

	}

	function setCookie(name, value, minutes) {

		let expires = "";

		if (minutes) {

			const date = new Date();

			date.setTime(date.getTime() + (minutes * 60 * 1000));

			expires = "; expires=" + date.toUTCString();

		}

		document.cookie = name + "=" + (value || "") + expires + "; path=/";

	}

	const emailInput = document.getElementById("sensfrx_email");

	emailInput.addEventListener('focus', function () {

		const errorMessage = document.getElementById("step-1-error");

		errorMessage.style.display = "none";

	});

	// Step 1 to Step 2

	const emailForm = document.getElementById("step-1-form");

	emailForm.addEventListener("submit", function(e) {

		e.preventDefault();

		const emailInput = document.getElementById("sensfrx_email");

		const email = emailInput.value;

		if (email) {

			setCookie('sensfrxVerifyEmail', email, 10); // Valid for 10 minutes

		}

		const button = emailForm.querySelector("button[type='submit']");

		const buttonText = button.querySelector(".button-text");

		const loader = button.querySelector(".loader");



		emailInput.disabled = true;

		button.disabled = true;

		button.style.filter = "blur(1px)";

		emailInput.style.opacity = "0.6";

		buttonText.textContent = "Sending OTP...";

		loader.style.display = "inline-block";



		const baseUrl = `${window.location.origin}${window.location.pathname.split('/wp-admin')[0]}`;

		const apiUrl = `${baseUrl}/wp-json/sensfrx-fraud-prevention-for-woocommerce/oauth/send-otp`;



		fetch(apiUrl, {

			method: 'POST',

			body: JSON.stringify({

				email: email

			}),

			headers: { 

				'Content-Type': 'application/json',

				'X-WP-Nonce': sensfrxData.nonce

			},

			credentials: 'same-origin'

		})

		.then(response => response.json())

		.then(data => {

			// console.log(data);

			if (data.status === "success") {

				var step = data.step_ahead;

				if (step == 2) {

					setTimeout(() => {

						button.disabled = false;

						button.style.filter = "none";

						buttonText.textContent = "Continue";

						loader.style.display = "none";

						emailInput.style.opacity = "1";

						emailInput.disabled = false;



						document.getElementById("display-email").textContent = email;

						step1.style.display = "none";

						step2.style.display = "block";

					}, 2000);

				} 

				if (step == 3) {

					step1.style.display = "none";

					step3.style.display = "block";

					setTimeout(() => {

						step3.style.display = "none";

						step4.style.display = "block";

						setTimeout(() => {

							location.reload();

						}, 3000);

					}, 3000);

				}

			} else {

				const errorMessage = document.getElementById("step-1-error");

				errorMessage.textContent = data.message;

				errorMessage.style.display = "block";

				button.disabled = false;

				button.style.filter = "none";

				buttonText.textContent = "Continue";

				loader.style.display = "none";

				emailInput.style.opacity = "1";

				emailInput.disabled = false;

			}

		})

		.catch(error => {

			console.error(data);

			const errorMessage = document.getElementById("step-1-error");

			errorMessage.textContent = "Unable to send verification email. Please check your email address or try again later.";

			errorMessage.style.display = "block";

			button.disabled = false;

			button.style.filter = "none";

			buttonText.textContent = "Continue";

			loader.style.display = "none";

			emailInput.style.opacity = "1";

			emailInput.disabled = false;

		});



		

	});

	// Step 2 to Step 3

	const otpForm = document.getElementById("step-2");

	const otpInputs = otpForm.querySelectorAll(".otp-input");

	const otpError = otpForm.querySelector(".error-message");

	const otpSuccess = otpForm.querySelector(".success-message");

	const verifyButton = otpForm.querySelector("button[type='submit']");



	otpForm.addEventListener("submit", function(e) {

		e.preventDefault();

		let code = "";

		function getCookie(name) {

			const value = `; ${document.cookie}`;

			const parts = value.split(`; ${name}=`);

			if (parts.length === 2) return parts.pop().split(';').shift();

		}

		const email = getCookie('sensfrxVerifyEmail');

		otpInputs.forEach(input => code += input.value.trim());





		if (code.length !== 6) {

			otpError.style.display = "flex";

			otpError.textContent = "Please enter a valid 6-digit OTP.";

			otpSuccess.style.display = "none";

			return;

		}



		if (!email) {

			otpError.style.display = "flex";

			otpError.textContent = "Email not found. Please start over.";

			otpSuccess.style.display = "none";

			return;

		}



		// Disable button during verification

		verifyButton.disabled = true;

		verifyButton.textContent = "Verifying...";



		const baseUrl = `${window.location.origin}${window.location.pathname.split('/wp-admin')[0]}`;

		const apiUrl = `${baseUrl}/wp-json/sensfrx-fraud-prevention-for-woocommerce/oauth/verify-otp`;





		fetch(apiUrl, {

			method: 'POST',

			body: JSON.stringify({

				otp: code,

				email: email

			}),

			headers: {

				'Content-Type': 'application/json',

				'X-WP-Nonce': sensfrxData.nonce

			},

			credentials: 'same-origin'

		})

		.then(response => {

			return response.json();

		})

		.then(data => {

			if (data.status === "success") {

				step2.style.display = "none";

				step3.style.display = "block";

				setTimeout(() => {

					step3.style.display = "none";

					step4.style.display = "block";

					setTimeout(() => {

						location.reload();

					}, 3000);

				}, 3000);

			} else {

				verifyButton.disabled = false;

				verifyButton.textContent = "Verify & Continue";

				otpError.style.display = "flex";

				otpError.textContent = data.message || "OTP verification failed. Please check the code.";

				otpSuccess.style.display = "none";

			}

		})

		.catch(error => {

			verifyButton.disabled = false;

			verifyButton.textContent = "Verify & Continue";

			otpError.style.display = "flex";

			otpError.textContent = "Unable to verify code. Please check the code or try resending it.";

			otpSuccess.style.display = "none";

		});



	});

	// Hide OTP error while typing

	otpInputs.forEach(input => {

		input.addEventListener("input", () => {

			otpError.style.display = "none";

		});

	});

	// Change email button

	const changeEmailBtn = document.querySelector(".change-email-btn");

	changeEmailBtn.addEventListener("click", function() {

		step2.style.display = "none";

		step1.style.display = "block";



		const emailInput = document.getElementById("sensfrx_email");

		const button = step1.querySelector("button[type='submit']");

		const buttonText = button.querySelector(".button-text");

		const loader = button.querySelector(".loader");



		emailInput.disabled = false;

		emailInput.style.opacity = "1";

		button.disabled = false;

		button.style.filter = "none";

		buttonText.textContent = "Continue";

		loader.style.display = "none";

	});

	// Resend code button

	const resendBtn = document.querySelector(".resend-btn");

	resendBtn.addEventListener("click", function() {

		function getCookie(name) {

			const value = `; ${document.cookie}`;

			const parts = value.split(`; ${name}=`);

			if (parts.length === 2) return parts.pop().split(';').shift();

		}

		const verifyEmail = getCookie('sensfrxVerifyEmail');





		if (!verifyEmail) {

			otpError.style.display = "flex";

			otpError.textContent = "Email not found. Please refresh and start over.";

			return;

		}



		// Disable button during resend

		resendBtn.disabled = true;

		resendBtn.textContent = "Sending...";



		const baseUrl = `${window.location.origin}${window.location.pathname.split('/wp-admin')[0]}`;

		const apiUrl = `${baseUrl}/wp-json/sensfrx-fraud-prevention-for-woocommerce/oauth/resend-otp`;





		fetch(apiUrl, {

			method: 'POST',

			body: JSON.stringify({

				email: verifyEmail

			}),

			headers: {

				'Content-Type': 'application/json',

				'X-WP-Nonce': sensfrxData.nonce

			},

			credentials: 'same-origin'

		})

		.then(response => {

			return response.json();

		})

		.then(data => {

			resendBtn.disabled = false;

			resendBtn.textContent = "Resend code";



			if (data.status === "success") {

				// Clear all OTP input boxes

				otpInputs.forEach(input => {

					input.value = "";

				});

				// Focus on first input after clearing

				if (otpInputs.length > 0) {

					otpInputs[0].focus();

				}

				otpError.style.display = "none";

				otpSuccess.style.display = "flex";

				otpSuccess.textContent = "New code sent to your email!";

				setTimeout(() => {

					otpSuccess.style.display = "none";

				}, 5000);

			} else {

				otpError.style.display = "flex";

				otpError.textContent = data.message || "Failed to resend code.";

				otpSuccess.style.display = "none";

			}

		})

		.catch(error => {

			resendBtn.disabled = false;

			resendBtn.textContent = "Resend code";

			otpError.style.display = "flex";

			otpError.textContent = "Unable to resend verification email. Please try again later.";

			otpSuccess.style.display = "none";

		});

	});

	// Helper function to check if all OTP inputs are filled and auto-submit

	function checkAndAutoSubmit() {

		let allFilled = true;

		otpInputs.forEach(input => {

			if (!input.value.trim()) {

				allFilled = false;

			}

		});

		

		if (allFilled && otpInputs.length === 6) {

			// All 6 boxes are filled, auto-submit the form

			setTimeout(() => {

				otpForm.dispatchEvent(new Event('submit'));

			}, 100); // Small delay to ensure all inputs are processed

		}

	}



	// input field auto next and paste handling

	document.querySelectorAll('.otp-input').forEach((input, index, inputs) => {

		// Auto-advance on input

		input.addEventListener('input', (e) => {

			// Only allow numeric input

			input.value = input.value.replace(/[^0-9]/g, '');

			

			if (input.value.length === 1 && index < inputs.length - 1) {

				inputs[index + 1].focus();

			}

			

			// Check if all inputs are filled and auto-submit

			checkAndAutoSubmit();

		});



		// Backspace navigation

		input.addEventListener('keydown', (e) => {

			if (e.key === 'Backspace' && input.value === '' && index > 0) {

				inputs[index - 1].focus();

			}

		});



		// Paste handling - distribute pasted code across inputs

		input.addEventListener('paste', (e) => {

			e.preventDefault();

			const pasteData = e.clipboardData.getData('text').trim();



			// Check if it's a 6-digit code

			if (/^\d{6}$/.test(pasteData)) {

				const digits = pasteData.split('');

				inputs.forEach((inp, idx) => {

					if (digits[idx]) {

						inp.value = digits[idx];

					}

				});

				// Focus on last input after paste

				inputs[inputs.length - 1].focus();

				// Check if all inputs are filled and auto-submit

				setTimeout(() => {

					checkAndAutoSubmit();

				}, 50);

			}

		});

	});

});