function updateOtpMethodButtons($container, otpprocess) {
    const $buttons = $container.find('#hcotp_otp_method_buttons');
    const $emailBtn = $buttons.find('.email-button');
    const $smsBtn = $buttons.find('.sms-button');
    const $whatsappBtn = $buttons.find('.whatsapp-button');

    if (otpprocess === 'email') {
        $emailBtn.show();
        $smsBtn.hide();
        $whatsappBtn.hide();
        return;
    }

    if (otpprocess === 'sms') {
        $emailBtn.hide();
        $smsBtn.show();
        $whatsappBtn.show();
        return;
    }

    if (otpprocess === 'whatsapp') {
        $emailBtn.hide();
        $smsBtn.show();
        $whatsappBtn.show();
        return;
    }

    $emailBtn.show();
    $smsBtn.show();
    $whatsappBtn.show();
}

jQuery(document).ready(function ($) {
          
    $(document).on('click', '#msg91_send_otp', function () {

        let $button = $(this); 
        let $container = $button.closest('#hcotp-otp-form-wrap, .edit-account'); 
        const otpprocess = $container.find('#otpprocess').val();

        $button.prop('disabled', true).text('Sending...');

        // EMAIL RESEND
        if (otpprocess === 'email') {

            const email = $container.find('#hcotp_email, #account_email').val()?.trim();

            if (!email) {
                $container.find('#hcotp-otp-send-status')
                    .html('<span class="woocommerce-error">Invalid email.</span>');
                $button.prop('disabled', false);
                return;
            }

            $.post(hcotp_params.ajax_url, {
                action: 'hcotp_send_email_otp',
                email: email,
                security_nonce: hcotp_params.nonce
            }, function (res) {

                if (res.success) {
                    updateOtpMethodButtons($container, 'email');
                    startOTPTimer($container);
                } else {
                    $container.find('#hcotp-otp-send-status')
                        .html('<span class="woocommerce-error">' + res.data.message + '</span>');
                    $button.prop('disabled', false);
                }
            });

            return;
        }
    
        let mobile = $container.find('#msg91_mobile').val().trim();
        let countryCode = $container.find('#msg91_country_code').val();
        let msg = hcotp_params.sendotp_validation_msg || 'Please enter a valid mobile number (between 5 and 12 digits).';
    
        if (!mobile || mobile.length < 5 || mobile.length > 12) {
            $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + msg + '</span>');
            return;
        }
    
        let mobileWithCode = countryCode + mobile;

        $.post(hcotp_params.ajax_url, {
            action: 'hcotp_send_otp_ajax',
            mobile: mobileWithCode,
             otpprocess: 'sms',
             security_nonce: hcotp_params.nonce 
            
        }, function (res) {
            $container.find('.sms-button').prop('disabled', false).text('SMS');
            $container.find('.whatsapp-button').prop('disabled', false).text('Whatsapp');
            if (res) {
                if (res.success && res.success === true) {
                    $container.find('#otpprocess').val('sms');
                    buildOtpInputs(
                        $container,
                        hcotp_params.sms_otp_length || 4
                    );
                    $container.find('#send_otp_section').hide();
                    $container.find('#hcotp_otp_input_wrap').show();
                    updateOtpMethodButtons($container, 'sms');
                    startOTPTimer($container);
                } else {
                    $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + res.data.message + '</span>');
                    $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">' + res.data.message + '</span>');
                    $button.prop('disabled', false).text('Send OTP');
                }
            } else {
                 console.log('OTP');
                $container.find('#hcotp-otp-send-status').html('<span style="color:red;">Something went wrong. Try again.</span>');
                $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">Something went wrong. Try again.</span>');
                $button.prop('disabled', false).text('Send OTP');
            }
        });
    });

    $(document).on('click', '#msg91_send_otp_whatsapp', function () {
        let $button = $(this); 
        let $container = $button.closest('#hcotp-otp-form-wrap'); 
    
        let mobile = $container.find('#msg91_mobile').val().trim();
        let countryCode = $container.find('#msg91_country_code').val();
        let msg = hcotp_params.sendotp_validation_msg || 'Please enter a valid mobile number (between 5 and 12 digits).';
    
        if (!mobile || mobile.length < 5 || mobile.length > 12) {
            $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + msg + '</span>');
            return;
        }
    
        let mobileWithCode = countryCode + mobile;
    
        $button.prop('disabled', true).text('Sending...');

    
        $.post(hcotp_params.ajax_url, {
            action: 'hcotp_send_otp_ajax',
            mobile: mobileWithCode,
               otpprocess: 'whatsapp',
             security_nonce: hcotp_params.nonce 
            
        }, function (res) {
              $container.find('.sms-button').prop('disabled', false).text('SMS');
              $container.find('.whatsapp-button').prop('disabled', false).text('Whatsapp');
            if (res) {
                if (res.success && res.success === true) {
                    $container.find('#otpprocess').val('whatsapp');
                    buildOtpInputs(
                        $container,
                        hcotp_params.sms_otp_length || 4
                    );
                    $container.find('#send_otp_section').hide();
                    $container.find('#hcotp_otp_input_wrap').show();
                    updateOtpMethodButtons($container, 'whatsapp');
                    startOTPTimer($container); 
                } else {
                    $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + res.data.message + '</span>');
                    $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">' + res.data.message + '</span>');
                    $button.prop('disabled', false).text('Send OTP');
                    
                }
            } else {
                 console.log('OTP');
                $container.find('#hcotp-otp-send-status').html('<span style="color:red;">Something went wrong. Try again.</span>');
                $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">Something went wrong. Try again.</span>');
                $button.prop('disabled', false).text('Send OTP');
            }
        });
    });
    
    $(document).on('paste', '#hcotp_otp_input_fields .hcotp-otp-field', function (e) {
        e.preventDefault();

        const pasteData = (e.originalEvent.clipboardData || window.clipboardData)
            .getData('text')
            .replace(/\D/g, '');

        if (!pasteData) return;

        const $fields = $(this).closest('#hcotp_otp_input_fields').find('.hcotp-otp-field');
        const startIndex = $fields.index(this);

        pasteData.split('').forEach(function (digit, i) {
            const $field = $fields.eq(startIndex + i);
            if ($field.length) {
                $field.val(digit);
            }
        });

        const focusIndex = Math.min(startIndex + pasteData.length, $fields.length) - 1;
        $fields.eq(focusIndex).focus();
    });

    // TYPING SUPPORT
    $(document).on('input', '#hcotp_otp_input_fields .hcotp-otp-field', function () {
        const $this = $(this);
        $this.val($this.val().replace(/\D/g, ''));

        if ($this.val().length === 1) {
            $this.next('.hcotp-otp-field').focus();
        }
    });

    // BACKSPACE SUPPORT
    $(document).on('keydown', '#hcotp_otp_input_fields .hcotp-otp-field', function (e) {
        if (e.key === 'Backspace' && !$(this).val()) {
            $(this).prev('.hcotp-otp-field').focus();
        }
    });

    $(document).on('click', '#msg91_verify_otp', function () {
        let $button = $(this);
        let $container = $button.closest('#hcotp-otp-form-wrap');
        let mobile = $container.find('#msg91_mobile').val().trim();
        let countryCode = $container.find('#msg91_country_code').val();

        let mobileWithCode = countryCode + mobile;
        
        let otpLength = $container.find('.hcotp-otp-field').length;
    
        let otp = '';
        
        $container.find('.hcotp-otp-field').each(function () {
            otp += $(this).val().trim();
        });

        let msg = hcotp_params.verifyotp_validation_msg || 'Please enter the OTP.';
    
        if (otp.length !== otpLength) {
            $container.find('#hcotp-otp-verify-status').html('<span style="color:red;font-size: 14px;">' + msg + '</span>');
            return;
        }
         const otpButtons = $container.find('#hcotp_otp_method_buttons');

        
            
    
        $container.find('#hcotp-otp-verify-status').html('Verifying...');
        $button.prop('disabled', true).text('Verifying...');
        let otpprocess = $container.find('#otpprocess').val(); 
    
       const payload = {
            action: 'hcotp_verify_otp_ajax',
            otpprocess: otpprocess,
            otp: otp,
            security_nonce: hcotp_params.nonce
        };

        if (otpprocess === 'email') {
            payload.email = $container.find('#hcotp_email').val().trim();
        } else {
            payload.mobile = mobileWithCode;
        }

        $.post(hcotp_params.ajax_url, payload, function (res) {
              
            if (res && res.success) {
                $container.find('#hcotp-otp-verify-status').html('<span style="color:green;">OTP Verified!</span>');
                    // Hide the SMS & WhatsApp buttons
                otpButtons.hide();

                let redirectUrl = hcotp_params.redirect_page;
    
                if (redirectUrl) {
                  
                    setTimeout(() => {
                        window.location.href = redirectUrl;
                    }, 1500);
                } else {
                 
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                }
        
                $container.find('#msg91_verify_otp').hide();
                $container.find('#hcotp_resend_otp').hide();
                $container.find('#resend_timer_text').hide();
                $('#account-tab').removeClass('active show');
                if ($container.data('is-popup') == '1') {
                    setTimeout(function () {
                        window.location.href = '/';
                    }, 1000);
                }

            } else {
                
                $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">Invalid OTP.</span>');
                    // Hide the SMS & WhatsApp buttons
            otpButtons.show();
            }
    
            $button.prop('disabled', false).text('Verify OTP');
        }).fail(function () {
            $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">Server error. Try again.</span>');
            $button.prop('disabled', false).text('Verify OTP');
                otpButtons.show();
        });
    });

    $(document).on('click', '#hcotp_verify_email_otp', function () {

        let $button = $(this);

        // Scope only to account OTP wrapper
        let $container = $button.closest('#hcotp_otp_input_wrap');

        let otpLength = $container.find('.hcotp-otp-field').length;
        let otp = '';

        $container.find('.hcotp-otp-field').each(function () {
            otp += $(this).val().trim();
        });

        let msg = hcotp_params.verifyotp_validation_msg || 'Please enter the OTP.';

        if (otp.length !== otpLength) {
            $container.find('#hcotp-otp-verify-status')
                .html('<span style="color:red;font-size:14px;">' + msg + '</span>');
            return;
        }

        $container.find('#hcotp-otp-verify-status').html('Verifying...');
        $button.prop('disabled', true).text('Verifying...');
        const email = $('#account_email').val().trim();
        const payload = {
            action: 'hcotp_verify_otp_ajax',
            otpprocess: 'email',
            otp: otp,
            email: email, // account email field
            security_nonce: hcotp_params.nonce
        };

        $.post(hcotp_params.ajax_url, payload, function (res) {

            if (res && res.success) {

                $container.find('#hcotp-otp-verify-status')
                    .html('<span style="color:green;">Email verified successfully!</span>');

                // Hide OTP UI after success
                setTimeout(() => {
                    $container.slideUp();
                }, 800);

                // Reload account page to unlock features
                setTimeout(() => {
                    const url = new URL(window.location.href);
                    url.searchParams.delete('hcotp_email_required');
                    window.location.replace(url.toString());
                }, 1200);

            } else {

                $container.find('#hcotp-otp-verify-status')
                    .html('<span style="color:red;">Invalid OTP.</span>');
            }

            $button.prop('disabled', false).text('Verify OTP');

        }).fail(function () {

            $container.find('#hcotp-otp-verify-status')
                .html('<span style="color:red;">Server error. Try again.</span>');

            $button.prop('disabled', false).text('Verify OTP');
        });

    });
    
    $(document).on('click', '#hcotp_resend_otp', function () {
        let $button = $(this);
        let $container = $button.closest('#hcotp-otp-form-wrap');
        const otpprocess = $container.find('#otpprocess').val();
        $container.find('#hcotp-otp-verify-status').html('');

        if (otpprocess === 'email') {
            const email = $container.find('#hcotp_email, #account_email').val()?.trim();

            if (!email) {
                $container.find('#hcotp-otp-verify-status')
                    .html('<span style="color:red;">' + hcotp_params.enter_valid_email + '</span>');
                $button.prop('disabled', false).text('Resend OTP');
                return;
            }

            $button.prop('disabled', true).text('Sending...');

            $.post(hcotp_params.ajax_url, {
                action: 'hcotp_send_email_otp',
                email: email,
                security_nonce: hcotp_params.nonce
            }, function (res) {
                if (res && res.success) {
                    updateOtpMethodButtons($container, 'email');
                    startOTPTimer($container);
                } else {
                    $container.find('#hcotp-otp-verify-status')
                        .html('<span style="color:red;">' + res.data.message + '</span>');
                    $button.prop('disabled', false).text('Resend OTP');
                }
            }).fail(function () {
                $container.find('#hcotp-otp-verify-status')
                    .html('<span style="color:red;">' + hcotp_params.server_error_text + '</span>');
                $button.prop('disabled', false).text('Resend OTP');
            });

            return;
        }
    
        let mobile = $container.find('#msg91_mobile').val().trim();
        let countryCode = $container.find('#msg91_country_code').val();
    
        let msg = hcotp_params.sendotp_validation_msg || 'Please enter a valid mobile number (between 5 and 12 digits).';
        if (!mobile || mobile.length < 5 || mobile.length > 12) {
            $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + msg + '</span>');
            return;
        }
    
        let mobileWithCode = countryCode + mobile;
    
       
        $.post(hcotp_params.ajax_url, {
            action: 'hcotp_send_otp_ajax',
            mobile: mobileWithCode,
              security_nonce: hcotp_params.nonce 
        }, function (res) {
            
            if (res && res.success) {
                startOTPTimer($container);
            } else {
                $container.find('#hcotp-otp-send-status').html('<span style="color:red;">' + res.data.message + '</span>');
                $container.find('#hcotp-otp-verify-status').html('<span style="color:red;">' + res.data.message + '</span>');
                $button.prop('disabled', false).text('Resend OTP');
            }
        });
    });
    

    function startOTPTimer($container) {
        let timer = hcotp_params.resend_timer || 30;
        const resendBtn = $container.find('#hcotp_resend_otp');

        const otpButtons = $container.find('#hcotp_otp_method_buttons');

        // Hide the SMS & WhatsApp buttons
        otpButtons.hide();
            
        resendBtn.prop('disabled', true).text('Resend OTP (' + timer + 's)');
         $container.find('#hcotp-otp-verify-status').html('');
    
        const interval = setInterval(() => {
            timer--;
            resendBtn.text('Resend OTP (' + timer + 's)');
            if (timer <= 0) {
                clearInterval(interval);
                resendBtn.prop('disabled', false)
                    .html("Didn't receive an OTP?<strong> Resend OTP</strong>")
                     $container.find('#hcotp-otp-verify-status').html('');
                    
                     otpButtons.show();
                updateOtpMethodButtons($container, $container.find('#otpprocess').val());
            }
        }, 1000);
    }
    
});

document.addEventListener('DOMContentLoaded', function () {
    const radios = document.querySelectorAll('input[name="msg91_login_form_type"]');
    const shortcodePreview = document.getElementById('msg91-shortcode-preview');

    radios.forEach(function (radio) {
        radio.addEventListener('change', function () {
            const shortcode = (this.value === 'screen') ? '[msg91_otp_form]' : '[msg91_otp_popup_form]';
            shortcodePreview.textContent = shortcode;
        });
    });
});

document.addEventListener('DOMContentLoaded', function () {
    const countryCodeSelect = document.getElementById('msg91_country_code');

    if (countryCodeSelect) {
        countryCodeSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const dialCode = selectedOption.value;
            const flag = selectedOption.getAttribute('data-flag');
            const flagContainer = document.getElementById('country-flag');

            if (flagContainer) {
                flagContainer.innerHTML = flag + ' ' + dialCode;
            }

            this.style.display = 'none';
        });
    }
});

document.addEventListener("DOMContentLoaded", function () {
    const popupModal = document.getElementById("hcotp-otp-popup-modal");

    document.addEventListener("click", function (e) {
        const trigger = e.target.closest('.otp-popup-trigger');
        if (trigger) {
            e.preventDefault();
            if (popupModal) {
                popupModal.style.display = "block";
            }
        }
    });

    window.openMsg91OtpPopup = function () {
        if (popupModal) {
            popupModal.style.display = "block";
        }
    };
});

jQuery(document).ready(function($) {
	$('#hcotp-settings-wrap .nav-tab-wrapper a.nav-tab').on('click', function(e){
				e.preventDefault();
				var tab_id = $(this).data('tab');
				$('#hcotp-settings-wrap .nav-tab-wrapper a.nav-tab').removeClass('nav-tab-active');
                $('#hcotp-settings-wrap .hcotp-tab-content').removeClass('active-tab').hide();
				
                $(this).addClass('nav-tab-active');
				$('#' + tab_id).addClass('active-tab').show();

				$('#hcotp_msg91_active_tab_input').val(tab_id);
	});
});

jQuery(document).ready(function($) {
    const $checkbox = $('#hcotp_whatsapp_auth_checkbox');
    const $inputsDiv = $('#hcotp_whatsapp_auth_inputs');

    $checkbox.on('change', function() {
        $inputsDiv.toggle(this.checked);
    });
});

function buildOtpInputs($container, length) {
    const $wrap = $container.find('#hcotp_otp_input_fields');
    $wrap.empty();

    for (let i = 0; i < length; i++) {
        $wrap.append(
            '<input type="text" maxlength="1" class="hcotp-otp-field" inputmode="numeric" />'
        );
    }
}

jQuery(document).on('change', 'input[name="hcotp_login_type"]', function () {
	const type = jQuery(this).val();
    const $container = jQuery('#hcotp-otp-form-wrap');

    // Reset to "send OTP" step when switching login type.
    $container.find('#hcotp_otp_input_wrap').hide();
    $container.find('#send_otp_section').show();
    $container.find('#hcotp-otp-send-status, #hcotp-otp-verify-status').html('');
    $container.find('#otpprocess').val('');
    $container.find('#msg91_send_otp').prop('disabled', false).text('Send OTP');
    $container.find('#hcotp_send_email_otp').prop('disabled', false).text('Send Email OTP');

	if (type === 'email') {
        jQuery('.hcotp-mobile-login').hide();
		jQuery('.hcotp-email-login').show();
        jQuery('#hcotp_send_email_otp').text('Send Email OTP');
        jQuery('#hcotp_otp_method_buttons .sms-button, #hcotp_otp_method_buttons .whatsapp-button').hide();
        jQuery('#hcotp_otp_method_buttons .email-button').show();
		buildOtpInputs(
			$container,
			hcotp_params.email_otp_length || 6
		);
	} else {
        jQuery('.hcotp-email-login').hide();
		jQuery('.hcotp-mobile-login').show();
        jQuery('#hcotp_otp_method_buttons .email-button').hide();
        jQuery('#hcotp_otp_method_buttons .sms-button, #hcotp_otp_method_buttons .whatsapp-button').show();
		buildOtpInputs(
			$container,
			hcotp_params.sms_otp_length || 4
		);
	}
});

jQuery(document).on('click', '#hcotp_send_email_otp', function () {
    
	const $button = jQuery(this);
	const $container = $button.closest('#hcotp-otp-form-wrap, .edit-account');
    $button.prop('disabled', true).text('Sending...');
	const $emailInput = $container.find('#hcotp_email, #account_email');
    const email = $emailInput.val() ? $emailInput.val().trim() : '';

    if($container.hasClass('edit-account')) {
        $container.find('#hcotp_otp_input_wrap').slideUp();
    }
    if (!email) {
		$container.find('#hcotp-otp-send-status')
			.html('<span style="color:red;">' + hcotp_params.enter_valid_email + '</span>');
		$button.prop('disabled', false).text('Send Email OTP');
		return;
	}

    // Email format validation
    if (email.indexOf('@example.com') > -1) {
        $container.find('#hcotp-otp-send-status')
            .html('<span style="color:red;">' + hcotp_params.use_valid_email + '</span>');
        $button.prop('disabled', false).text('Send Email OTP');
        return;
    }
    const emailRegex = new RegExp(/^[a-zA-Z0-9]([a-zA-Z0-9-_.]{1,})?@[a-zA-Z0-9]([a-zA-Z0-9-]{1,})?\.[a-zA-Z]{2,}$/);
    if (!emailRegex.test(email)) {
        $container.find('#hcotp-otp-send-status')
            .html('<span style="color:red;">' + hcotp_params.invalid_email_format + '</span>');
        $button.prop('disabled', false).text('Send Email OTP');
		return;
	}

	jQuery.post(hcotp_params.ajax_url, {
		action: 'hcotp_send_email_otp',
		email: email,
		security_nonce: hcotp_params.nonce
	}, function (res) {
		if (res.success) {
			$container.find('#otpprocess').val('email');
            buildOtpInputs(
                $container,
                hcotp_params.email_otp_length || 6
            );
            $container.find('#send_otp_section').slideUp();
			$container.find('#hcotp_otp_input_wrap').slideDown();
            updateOtpMethodButtons($container, 'email');
			$button.prop('disabled', false).text('Send Email OTP');
		} else {
			$container.find('#hcotp-otp-send-status')
				.html('<span style="color:red;">' + res.data.message + '</span>');
			$button.prop('disabled', false).text('Send Email OTP');
		}
	}).fail(function () {
		$container.find('#hcotp-otp-send-status')
			.html('<span style="color:red;">' + hcotp_params.server_error_text + '</span>');
		$button.prop('disabled', false).text('Send Email OTP');
	});
});

jQuery(document).ready(function () {
	if (hcotp_params.email_otp_enabled && hcotp_params.user_requires_email) {
        console.log(hcotp_params);
		jQuery('.hcotp-mobile-login').hide();
		jQuery('.hcotp-login-method').hide();
		jQuery('.hcotp-email-login').show();

		// jQuery('#hcotp-otp-send-status').html(
		// 	'<span style="color:#d63638;">Please add and verify your email to continue.</span>'
		// );
	}
});
