/**
 * Masteriyo two-factor authentication frontend JS.
 *
 * @since 2.7.0
 *
 * @param {object} $ jQuery object
 * @param {object} masteriyo_data Global data object
 */
(function ($, masteriyo_data) {
	'use strict';

	var masteriyoTwoFactorAuthentication = {
		/**
		 * Initializes the two-factor authentication functionalities.
		 *
		 * @since 2.7.0
		 */
		init: function () {
			this.setInitialCounterState();
			this.bindUIActions();
		},

		/**
		 * Sets the initial counter state and button state when the document is ready.
		 *
		 * @since 2.7.0
		 */
		setInitialCounterState: function () {
			const resendBtn = $('#masteriyo-resend-login-otp');
			const resendCounter = $('#masteriyo-resend-counter');

			let remainingTime = parseInt(
				$('input[name="resend_remaining_time"]').val(),
				10
			);

			if (remainingTime > 0) {
				resendBtn.prop('disabled', true);
				this.startCountdown(remainingTime, resendCounter, resendBtn);
			}
		},

		/**
		 * Starts a countdown based on the provided remaining time, updating both the counter and the button.
		 *
		 * @since 2.7.0
		 *
		 * @param {Number} remainingTime - The remaining time to count down from.
		 * @param {jQuery Object} counterElem - The jQuery object representing the counter element.
		 * @param {jQuery Object} buttonElem - The jQuery object representing the button to enable/disable.
		 */
		startCountdown: function (remainingTime, counterElem, buttonElem) {
			counterElem.text(
				counterElem.text().replace(/\(\d+\)/, `(${remainingTime})`)
			);

			if (remainingTime <= 0) {
				counterElem.hide();
			} else {
				counterElem.show();
			}

			const timerInterval = setInterval(() => {
				if (remainingTime <= 0) {
					clearInterval(timerInterval);
					buttonElem.prop('disabled', false);
					counterElem.text(counterElem.text().replace(/\(\d+\)/, '(0)'));

					counterElem.hide();
				} else {
					remainingTime--;

					counterElem.text(
						counterElem.text().replace(/\(\d+\)/, `(${remainingTime})`)
					);

					counterElem.show();
				}
			}, 1000);
		},

		/**
		 * Binds event handlers for OTP form submission and OTP resending.
		 *
		 * @since 2.7.0
		 */
		bindUIActions: function () {
			$('#masteriyo-login-otp-form').on('submit', this.handleOTPFormSubmit);
			$('#masteriyo-resend-login-otp').on('click', this.handleOTPResend);
		},

		/**
		 * Handles OTP form submission.
		 *
		 * @since 2.7.0
		 */
		handleOTPFormSubmit: function (e) {
			e.preventDefault();

			const formData = $(this).serializeArray();

			$.ajax({
				url: masteriyo_data.ajax_url,
				type: 'POST',
				data: formData,
				success: function (res) {
					if (res.success) {
						window.location.replace(res.data.redirect);
					} else {
						$('#masteriyo-login-otp-error-msg').show().html(res.data.message);
					}
				},
				error: function (error) {
					var message =
						xhr.responseJSON && xhr.responseJSON.message
							? xhr.responseJSON.message
							: error;

					$('#masteriyo-login-otp-error-msg').show().html(message);
				},
			});
		},

		/**
		 * Handles OTP resending.
		 *
		 * @since 2.7.0
		 */
		handleOTPResend: function (e) {
			e.preventDefault();

			$.ajax({
				url: masteriyo_data.ajax_url,
				type: 'POST',
				data: {
					action: 'masteriyo_two_factor_authentication_otp_login_resend',
					nonce: masteriyo_data.nonce,
					user_id: $('input[name="user_id"]').val(),
				},

				success: function (res) {
					if (res.success) {
						const btn = $('#masteriyo-resend-login-otp');
						const counterElem = $('#masteriyo-resend-counter');

						let currentText = btn.text();

						// Update just the integer part of the text
						const newText = currentText.replace(
							/\(\d+\)/,
							`(${res.data.resend_count})`
						);
						btn.text(newText);

						masteriyoTwoFactorAuthentication.startCountdown(
							res.data.resend_remaining_time,
							counterElem,
							btn
						);

						$('#masteriyo-login-otp-success-msg').show().html(res.data.message);
					} else {
						$('#masteriyo-login-otp-error-msg').show().html(res.data.message);
					}
				},
				error: function (error) {
					var message =
						xhr.responseJSON && xhr.responseJSON.message
							? xhr.responseJSON.message
							: error;

					$('#masteriyo-login-otp-error-msg').show().html(message);
				},
			});
		},
	};

	masteriyoTwoFactorAuthentication.init();
})(jQuery, window.MASTERIYO_TWO_FACTOR_AUTHENTICATION_DATA);
