Untitled

 avatar
unknown
plain_text
2 months ago
65 kB
5
Indexable
/* eslint-disable no-unused-expressions */
/* eslint-disable react/jsx-indent */
/* eslint no-use-before-define: ["error", { "functions": false , variables:false}] */
/* eslint-disable jsx-a11y/label-has-associated-control */
import React, { useState, useCallback, useEffect, useRef } from 'react';
import loadable from '@loadable/component';
import Cookies from 'universal-cookie';
import './SignUpModal.scss';
import Lottie from 'react-lottie';
import { nbGaEvent, adobeMediaOptimiser } from '../../../utils/Common/eventUtils.js';
import NbTelInput from '../form-elements/NbTelInput/NbTelInput.jsx';
import NbInput from '../form-elements/NbInput/NbInput.jsx';
// import { initializeClarity } from '../../../utils/Common/commonUtilityCall';
import { SIGNUP_MODAL_DATA, SIGNUP_MODAL_CONSTANT, handleRedirectionFromParent } from './constants';
import Icons from '../../Icons/Icons';
import NbSwitch from '../form-elements/NbSwitch/NbSwitch.jsx';
import { validateEmail, readCookie, validateName, getFormattedPropertyType } from '../../../utils/Common/Common';
import {
	sendNewOtpFlowGAEventForScreenView,
	sendNewOtpFlowGAEventForCloseButton,
	sendNewOtpFlowGAEventForContinueButton,
} from './utils.js';
import NbLoader from '../NbLoader/NbLoader.jsx';
import AlertBox from '../AlertMsgBox/AlertMsgBox.jsx';
import NbRadio from '../form-elements/NbRadio/NbRadio.jsx';
import NbOTP from '../form-elements/NbOtp/NbOtp.jsx';
import NbModal from '../NbModal/NbModal';
import nbCache from '../../../utils/Common/nbCache';
import lock from '../../../images/Signup/lockLottie.json';
import facebookEvent from '../../../utils/Common/fbEvents';
import nbSwagger from '../../../utils/Common/nbSwagger.js';
import EmailInputWithSuggestion from '../form-elements/EmailInputWithSuggestion/EmailInputWithSuggestion.jsx';
import InvalidDomainPopup from '../form-elements/InvalidDomainPopup/InvalidDomainPopup.jsx';
import { cookieHandler } from '../../../utils/Common/commonUtilityCall.js';
const staticBaseURL = `${baseURL || '/nb-new/public'}/Signup`;
const mobileSignUp = `${staticBaseURL}/mobileSignUp.svg`;
const Visibility = `${baseURL || '/nb-new/public'}/MaterialIcons/Visibility.png`;
const VisibilityOff = `${baseURL || '/nb-new/public'}/MaterialIcons/VisibilityOff.png`;

const NbButton = loadable(() =>
	import(/* webpackChunkName: "NbButton", webpackMode: "lazy" */ '../NbButton/NbButton.jsx')
);

const MODAL_HASH = 'signup-login';

const DEFAULT_WHATSAPP_OPT_IN = true;


const withCustomIcon = (text) => {
	const textWithoutIcon = text.split(/{icon:[a-zA-Z0-9-:]*}/gi);
	const icons = text.match(/{icon:[a-zA-Z0-9-:]*}/gi);
	const jsx = [];
	const iconsJSX = [];
	if (icons === null) return text;
	icons.forEach((icon) => {
		const iconConfig = icon.match(/{icon:(.*)}/)[1];
		const iconData = iconConfig.split(':');
		iconsJSX.push(<Icons noMargin key={`${iconData[0]}`} type={iconData[0]} color={iconData[1] || '#000'} />);
	});
	textWithoutIcon.forEach((subText, index) => {
		jsx.push(subText);
		if (iconsJSX[index]) jsx.push(iconsJSX[index]);
	});
	return jsx;
};

// FORM INITIAL STATE
const FORM_INIT_STATE = {
	dialCode: { value: '91' },
	phoneNumber: { value: '' },
	iso2: { value: 'in' },
	whatsAppOptIn: { value: true },
	whatsAppOptInSource: { value: undefined },
	name: { value: '' },
	email: { value: '' },
	loginMethod: { value: 'otp' },
	password: { value: '' },
	otp: { value: '' },
};
const lockLottie = {
	loop: true,
	autoplay: true,
	animationData: lock,
};
const SignUpModal = ({
	show,
	sendVerificationOtpRequest,
	newAccountData,
	newAccountDataError,
	backdrop = true,
	closeSignUpModal,
	createNewAccountRequest,
	removeUsersinupState,
	onHide,
	emailLogin,
	type = 'default',
	checkIfPhoneExistsRequest,
	newUser,
	oldUser,
	onSuccess,
	verifyNewOtpRequest,
	sendOTPToEmail,
	verifyOtpRequest,
	verifyPasswordRequest,
	otpVerification,
	passwordVerification,
	userInfo,
	preSelectedPhone,
	preSelectedNameAndEmail,
	emailOtpVerification,
	updateSecondaryNumberRequest,
	createNewOtpAccountRequest,
	resetSignupData,
	// userPhoneData = {
	// 	newPhone: '+919038294623',
	// 	existingPhone: '+919116176100',
	// 	existingEmail: '[email protected]',
	// },
	userPhoneData,
	removeSignUpViaEmailState,
	existingWhatsAppStatus = false,
	cookies,
	history,
	location,
	newAccountCreationData,
	newOtpVerifyFlow,
	verifyNewOtpInitalRequest,
	updateNewNumberOtpFlow,
	newMobileUpdateSucess,
	newMobileUpdateError,
	customExtraInfo,
}) => {
	const [isActiveNewFlow, setIsActiveNewFlow] = useState(false);
	const [formData, setFormData] = useState(FORM_INIT_STATE);
	const verifyOtpFired = useRef(false);
	const [showWhatsApp, setWhatsAppShowFlag] = useState(false);
	const [activeStep, setStep] = useState(1);
	const [phoneNumberChangeFlag, setPhoneNumberChangeFlag] = useState(false);
	const [showLoader, setLoaderState] = useState(false);
	const [formErrorMsg, setFromErrorMsg] = useState('');
	const [otpInfoMsg, setOTPInfoMsg] = useState('');
	const [updatePhoneScreen, setUpdatePhoneScreen] = useState(false);
	const [passwordVisibility, setPasswordVisibility] = useState(null);
	const [isOTPEmailLabelStatus, setOTPEmailLabelStatus] = useState(false);
	const [isAutoReadOtpDetected, setAutoReadOtpDetected] = useState(false);
	const [idAutoReadSubmitApiCalled, setAutoReadSubmitApiCalled] = useState(false);
	const [isOtpMandateFlowEnabled, setOtpMandateFlowEnabled] = useState(false);
	const [maxIndLength, setMaxIndLength] = useState(18);
	const [isContinueClicked, setIsContinueClicked] = useState(false);
	const [showEmailErrorPopup, setShowEmailErrorPopup] = useState(false);
	const [emailErrorMessage, setEmailErrorMessage] = useState('');
	const [correctedEmail, setCorrectedEmail] = useState('');
	const [emailDomainDecisionDone, setEmailDomainDecisionDone] = useState(false);
	const isDeferredFlowRef = useRef(false);

	useEffect(() => {
		try {
			const deferredExp = localStorage.getItem('deferred_login_exp');
			isDeferredFlowRef.current = !!deferredExp && JSON.parse(deferredExp) === true;
		} catch {
			isDeferredFlowRef.current = false;
		}
	}, []);
	const emailRef = useRef();


	

	let pageSpecificData = SIGNUP_MODAL_DATA[type];
	if (oldUser && type === 'default') {
		pageSpecificData = SIGNUP_MODAL_DATA.signin;
	}

	const serviceType = typeof localStorage !== 'undefined' && localStorage.getItem('service');

	const removeCookies = (cookies = ['gacontact', 'gapyp']) => {
		if (typeof window === 'undefined') return;

		cookies.forEach((cookie) => {
			try {
				cookieHandler.remove(cookie, { path: '/' });
			} catch (e) {
				// fail silently
			}
		});
	};

	// handle modal close
	const closeModal = useCallback(() => {
		!isActiveNewFlow && nbGaEvent('user_signup', 'back_loginScreen', { service: serviceType, ...customExtraInfo });
		if (!isActiveNewFlow && pageSpecificData.gaEventCategory) {
			nbGaEvent(pageSpecificData.gaEventCategory, 'Back-LoginScreen');
		}
		if (onHide) onHide();
		removeCookies(['gacontact', 'gapyp']);
		// action to close the signup/login modal
		removeEventListeneres();
		removeUsersinupState();
		verifyNewOtpInitalRequest();
		setPhoneNumberChangeFlag(false);
		setStep(1);
		setLoaderState(false);
		setWhatsAppShowFlag(false);
		setFormData(FORM_INIT_STATE);
		setOTPInfoMsg('');
		resetSignupData();
		closeSignUpModal();
		try {
			if (typeof document === 'object') {
				document.body.style.overflow = '';
				if (handleRedirectionFromParent.includes(type)) return;
				history.replace(`${location.pathname}${location.search || ''}`);
			}
		} catch (e) {
			// no doc
		}
	}, [onHide]);

	useEffect(() => {
		if (oldUser || newUser || newOtpVerifyFlow) {
			setLoaderState(false);
			if (newUser && newOtpVerifyFlow) setStep(2);
		}
		if (newOtpVerifyFlow) verifyOtpFired.current = false;
	}, [oldUser, newUser, newOtpVerifyFlow]);

	const handleHashChange = useCallback(() => {
		try {
			if (typeof window === 'object') {
				if (window.location.hash !== `#${MODAL_HASH}`) {
					closeModal();
				}
			}
		} catch (e) {
			// hash change err
		}
	}, [onHide]);

	const handleKeyDown = useCallback(
		(event) => {
			if (event.keyCode === 27) {
				// ESCAPE
				closeModal();
			}
		},
		[onHide]
	);

	const handleClick = useCallback(
		(event) => {
			if (event.target && event.target.className === 'login-signup__backdrop' && type !== 'ListPageSignIn') {
				closeModal();
			}
		},
		[onHide]
	);

	const removeEventListeneres = () => {
		document.body.classList.remove('overflow-hidden');
		window.removeEventListener('hashchange', handleHashChange);
		document.removeEventListener('keydown', handleKeyDown);
		document.removeEventListener('click', handleClick);
	};

	const focusInput = useCallback((key) => {
		try {
			// auto focus error input
			const element = document.getElementById(`login-signup-form__${key}-input`);
			if (element) element.focus();
		} catch (e) {
			//
		}
	}, []);

	// handle form Update state and error
	const updateFormData = useCallback((key, value, isErrorOrCb = false, errorMsg = '', cb) => {
		setFormData((currentData) => {
			let isValueArray = false;
			const updateData = { ...currentData };
			let isError = false;
			if (typeof isErrorOrCb === 'function') cb = isErrorOrCb;
			else isError = isErrorOrCb;

			if (Array.isArray(key)) isValueArray = true;

			if (Array.isArray(key)) {
				if (isValueArray && key.length === value.length) {
					key.forEach((formKey, index) => {
						updateData[formKey] = {
							value: value[index],
							isError: isError && isError[index] ? isError[index] : false,
							errorMsg: isError && isError[index] && errorMsg && errorMsg[index] ? errorMsg[index] : '',
						};
						if (updateData[formKey].isError) {
							focusInput(key);
						}
					});
				} else {
					key.forEach((formKey, index) => {
						updateData[formKey] = {
							value,
							isError: isError && isError[index] ? isError[index] : isError,
							errorMsg: isError && isError[index] && errorMsg && errorMsg[index] ? errorMsg[index] : errorMsg,
						};
						if (updateData[formKey].isError) {
							focusInput(key);
						}
					});
				}
			} else {
				updateData[key] = {
					value,
					isError,
					errorMsg,
				};
				if (isError) {
					focusInput(key);
				}
			}

			if (cb && typeof cb === 'function') cb();

			return updateData;
		});
	}, []);

	// PERFORM VALIDATION AND API CALLS

	const validation = useCallback(
		(noErrorNotification, isNRIUser = false) => {
			let valid = true;
			const phoneNumber = formData.phoneNumber.value;
			const dialCode = formData.dialCode.value;
			const {
				password: { value: password },
				otp: { value: otp },
				loginMethod: { value: loginMethod },
				whatsAppOptIn: { value: whatsAppOptIn },
				whatsAppOptInSource: { value: whatsAppOptInSource },
				email: { value: email },
				name: { value: name },
				iso2: { value: iso2 },
			} = formData;
			if (activeStep === 1) {
				const phoneLength = phoneNumber.trim().length;
				if (
					phoneLength < 4 ||
					(dialCode === '91' && phoneLength < 10) ||
					(dialCode === '971' && phoneLength < 8) ||
					(dialCode === '1' && phoneLength < 10) ||
					(dialCode === '65' && phoneLength < 8) ||
					(dialCode === '44' && phoneLength < 9)
				) {
					valid = false;
					if (!noErrorNotification) {
						updateFormData('phoneNumber', phoneNumber, true, SIGNUP_MODAL_CONSTANT.PHONE_INVALID_ERROR);
					}
				} else if (isActiveNewFlow && !isNRIUser && !newOtpVerifyFlow) {
					adobeMediaOptimiser.logEvent(`ev_Newphone-${readCookie('nbpt')}`);
					// if (pageSpecificData.isOTPVerify) {
					setStep(3);
					// send otp
					sendOTP();
				} else if (isNRIUser && !isContinueClicked && ['44', '1', '971', '65'].includes(dialCode)) {
					if (isNRIUser) {
						setOtpMandateFlowEnabled(false);
					}
					nbGaEvent('user_signup', 'login_initiated', { service: serviceType, ...customExtraInfo });
					checkIfPhoneExistsRequest(dialCode, phoneNumber, pageSpecificData.flow || '');
					setIsContinueClicked(false);
				} else if (isNRIUser && isContinueClicked) {
					if (isNRIUser) {
						setOtpMandateFlowEnabled(false);
					}
					nbGaEvent('user_signup', 'login_initiated', { service: serviceType, ...customExtraInfo });
					checkIfPhoneExistsRequest(dialCode, phoneNumber, pageSpecificData.flow || '');
					setIsContinueClicked(false);
				}
			} else if (activeStep === 2) {
				// signup
				// validation email & name
				const nameError = validateName(name.trim());
				if (nameError && nameError.length > 0) {
					valid = false;
					if (!noErrorNotification) {
						updateFormData('name', name, true, nameError);
					}
				}

				if (validateEmail(email) === false) {
					valid = false;
					if (!noErrorNotification) {
						updateFormData('email', email, true, SIGNUP_MODAL_CONSTANT.EMAIL_INVALID_ERROR);
					}
				}
				const result = emailRef?.current?.validateEmail();

				if (!result?.valid && result?.domainError && !emailDomainDecisionDone) {
					setCorrectedEmail(result?.correctedEmail);
					setEmailErrorMessage(result?.message);
					setShowEmailErrorPopup(true);
					setStep(6);
					return;
				}

				if (valid) {
					setLoaderState(true);
					if (newOtpVerifyFlow) {
						createNewOtpAccountRequest({
							name,
							phoneNumber,
							email,
							dialCode,
							flow: pageSpecificData.flow,
							whatsAppOptIn,
							whatsAppOptInSource,
							isOtpMandateFlowEnabled,
							iso2,
						});
					} else {
						createNewAccountRequest({
							name,
							phoneNumber,
							email,
							dialCode,
							flow: pageSpecificData.flow,
							whatsAppOptIn,
							whatsAppOptInSource,
							isOtpMandateFlowEnabled,
						});
					}

					if (isOtpMandateFlowEnabled) {
						nbGaEvent('signup_otp_mandate', `detail_submit`, {
							eventDetailsInfo: JSON.stringify({
								name,
								phoneNumber,
								email,
								dialCode,
								flow: pageSpecificData.flow,
							}),
						});
					}
				}
			} else if (activeStep === 3) {
				if (loginMethod === 'password' && password.trim().length < 4) {
					valid = false;
					updateFormData('password', password, true, SIGNUP_MODAL_CONSTANT.PASSWORD_INVALID_ERROR);
					setAutoReadOtpDetected(false);
				} else if (loginMethod === 'otp' && otp.trim().length < 4) {
					valid = false;
					updateFormData('otp', otp, true, SIGNUP_MODAL_CONSTANT.OTP_INVALID_ERROR);
					setAutoReadOtpDetected(false);
				} else if (loginMethod === 'otp') {
					setLoaderState(true);
					if (isActiveNewFlow && formData.dialCode.value === '91' && !verifyOtpFired.current) {
						verifyNewOtpInitalRequest();
						verifyOtpFired.current = true;
						verifyNewOtpRequest({
							phoneNumber,
							otp,
							dialCode,
							whatsAppOptIn,
							whatsAppOptInSource,
							isLoggedIn: userInfo?.isLoggedIn,
							isPhoneUpdateOtp: pageSpecificData?.isOTPVerify || false,
							iso2,
							newFlow: isActiveNewFlow,
						});
					} else if (!verifyOtpFired.current) {
						verifyOtpRequest({
							phoneNumber,
							otp,
							dialCode,
							whatsAppOptIn,
							whatsAppOptInSource,
							isLoggedIn: userInfo?.isLoggedIn,
							isPhoneUpdateOtp: pageSpecificData?.isOTPVerify || false,
						});
					}

					if (isOtpMandateFlowEnabled && newAccountData) {
						nbGaEvent('signup_otp_mandate', `otp_submit`);
					}
					if (pageSpecificData?.otpGAMandate) {
						nbGaEvent(pageSpecificData.gaEventCategory, `otp_submit`);
						nbGaEvent('signup_otp_mandate', `otp_submit`);
					}
				} else {
					setLoaderState(true);
					verifyPasswordRequest({ phoneNumber, password, dialCode, whatsAppOptIn, whatsAppOptInSource });
				}
			} else if (activeStep === 4) {
				// login via otp
				if (otp.trim().length < 4) {
					valid = false;
					updateFormData('otp', otp, true, SIGNUP_MODAL_CONSTANT.OTP_INVALID_ERROR);
					setAutoReadOtpDetected(false);
				} else {
					setLoaderState(true);
					verifyOtpRequest({ email, otp, isLoggedIn: userInfo?.isLoggedIn, newFlow: isActiveNewFlow, iso2 });
					if (isOtpMandateFlowEnabled && newAccountData) {
						nbGaEvent('signup_otp_mandate', `otp_submit`);
					}
				}
			}
			setFromErrorMsg('');
			return valid;
		},
		[formData, activeStep, isContinueClicked, setIsContinueClicked, verifyOtpFired.current]
	);

	function debounce_leading(func, timeout = 300) {
		let timer;
		return (...args) => {
			if (!timer) {
				func.apply(this, args);
			}
			clearTimeout(timer);
			timer = setTimeout(() => {
				timer = undefined;
			}, timeout);
		};
	}

	const debounceSignUpClick = debounce_leading(() => validation(false, formData?.dialCode?.value !== '91'), 2000);

	// HANDLE SUBMIT OF FORM
	const handleFormSubmit = useCallback(
		(event) => {
			event.preventDefault();
			// using debouce for check api
			debounceSignUpClick();
		},

		[formData, activeStep]
	);


	const setSentryUserContext = async (userId) => {
		try {
			const Sentry = await import('@sentry/browser');
			Sentry.setUser({
				id: userId,
			});
		} catch (error) {
			console.error('Error setting Sentry user context:', error);
		}
	};

	/* Method to Register the ADOBE EVENT on Completion on Login/SignUp  */

	useEffect(() => {
		if (isActiveNewFlow && activeStep === 2 && newAccountData)
			nbGaEvent('user_name_email', 'detail_success', {
				phoneNumber: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				name: formData?.name?.value,
				newUser,
				...customExtraInfo,
			});
	}, [isActiveNewFlow, activeStep, newAccountData]);

	// Complete Login/Signup Action
	const onCompletion = useCallback(
		(userData) => {
			if (typeof onSuccess === 'function') onSuccess(userData);
			try {
				setSentryUserContext(userData.id);
				nbCache.set('ustats', { id: userData.id, em: userData.email, ph: userData.phone });
			} catch (error) {
				// console.log(error)
			}
			removeCookies(['gacontact', 'gapyp']);
			closeSignUpModal();
			removeEventListeneres();
			if (cookieHandler.get('showMsgNotification') === undefined) {
				cookieHandler.set('showMsgNotification', true);
			}
		},
		[onSuccess]
	);

	const checkListOptimize = useCallback((checkList) => {
		if (typeof window === 'object' && window.innerWidth < 768) {
			return checkList.slice(0, 2);
		}
		return checkList;
	}, []);
	// send otp
	const autoReadSMS = (cb) => {
		// used AbortController with setTimeout so that WebOTP API (Autoread sms) will get disabled after 1min
		const signal = new AbortController();
		setTimeout(() => {
			signal.abort();
		}, 1 * 60 * 1000);
		async function main() {
			if ('OTPCredential' in window) {
				try {
					if (navigator.credentials) {
						try {
							await navigator.credentials
								.get({ abort: signal, otp: { transport: ['sms'] } })
								.then((content) => {
									if (content && content.code) {
										cb(content.code);
									}
								})
								.catch((e) => console.log(e));
						} catch (e) {
							return;
						}
					}
				} catch (err) {
					console.log(err);
				}
			}
		}
		main();
	};

	useEffect(() => {
		if (isAutoReadOtpDetected && !idAutoReadSubmitApiCalled) {
			validation(false, formData?.dialCode?.value !== '91');
			setAutoReadSubmitApiCalled(true);
		}
	}, [isAutoReadOtpDetected]);

	const sendOTP = useCallback(() => {
		const {
			phoneNumber: { value: phoneNumber },
			dialCode: { value: dialCode },
			iso2: { value: iso2 },
		} = formData;
		sendVerificationOtpRequest(
			phoneNumber,
			dialCode,
			pageSpecificData.isOTPVerify || false,
			isOtpMandateFlowEnabled,
			iso2,
			isActiveNewFlow && formData.dialCode.value?.includes('91')
		);
		setOTPInfoMsg('OTP sent successfully!');
		setTimeout(() => {
			setOTPInfoMsg('');
		}, 4000);
		try {
			let isMobile = cookies && cookies?.isMobile === 'true';
			if (typeof window !== 'undefined') {
				isMobile = window?.innerWidth < 1026;
			}
			if (isMobile) {
				autoReadSMS((data) => {
					if (data) {
						updateFormData('otp', data);
						setAutoReadSubmitApiCalled(false);
						setAutoReadOtpDetected(true);
						nbGaEvent('mobilesignup', 'auto_read_otp_success');
					}
				});
			}
		} catch (error) {
			console.log(error);
		}
	}, [formData]);
	const setScroll = useCallback((y) => {
		try {
			if (typeof window === 'object' && typeof document === 'object' && window.innerWidth < 768) {
				document.getElementById('login-signup-modal').scrollTo(0, y);
			}
		} catch (e) {
			// err while scorll
		}
	}, []);

	/* Method to Continue with the existing Phone */
	const continueWithExistingPhone = () => {
		if (isActiveNewFlow && formData.dialCode.value === '91') {
			isActiveNewFlow &&
				nbGaEvent('email_verified', 'continue_old', {
					phoneNumber: formData?.phoneNumber?.value,
					email: formData?.email?.value,
					name: formData?.name?.value,
					newUser,
					...customExtraInfo,
				});
			setStep(1);
			resetSignupData();
			return setFormData(FORM_INIT_STATE);
		}
		nbGaEvent(pageSpecificData.gaEventCategory, `UseOldPhone-${pageSpecificData.flow}`);
		updateSecondaryNumberRequest({
			newPhone: userPhoneData.newPhone,
		});
		return onCompletion();
	};

	/* Method to update the phone */
	const updatePhone = () => {
		verifyOtpRequest({
			phoneNumber: userPhoneData.newPhone,
			otp: formData?.otp?.value,
			flow: 'number_change',
			isPhoneUpdateOtp: true,
		});
	};

	/* Method trigged when user clicks on changePhone */
	const onChangePhone = () => {
		// eslint-disable-next-line no-unused-expressions
		!isActiveNewFlow && nbGaEvent(pageSpecificData.gaEventCategory, `SignIn_Initiated-back-${pageSpecificData.flow}`);
		if (isActiveNewFlow) {
			if (activeStep === 2)
				nbGaEvent('user_name_email', 'detail_change_phone', {
					phoneNumber: formData?.phoneNumber?.value,
					name: formData?.name?.value,
					email: formData?.email?.value,
					newUser,
					...customExtraInfo,
				});
			else if (activeStep === 4)
				nbGaEvent('user_otp_email', 'otp2_change_phone', {
					phoneNumber: formData?.phoneNumber?.value,
					name: formData?.name?.value,
					email: formData?.email?.value,
					newUser,
					...customExtraInfo,
				});
			else {
				nbGaEvent('user_otp_number', 'otp1_change_phone', {
					phoneNumber: formData?.phoneNumber?.value,
					newUser,
					...customExtraInfo,
				});
				if (isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'otp1_change_phone_defer');
			}
		}
	};

	/* Method to Send Update Phone OTP */
	const sendUpdatePhoneOtp = () => {
		sendVerificationOtpRequest(userPhoneData.newPhone, null, true);
	};

	/* Method to Go to the update phone screen */
	const goToUpdatedPhoneScreen = () => {
		if (isActiveNewFlow && formData.dialCode.value === '91') {
			nbGaEvent('email_verified', 'migrate_new', {
				phoneNumber: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				name: formData?.name?.value,
				newUser,
				...customExtraInfo,
			});
			setLoaderState(true);
			return updateNewNumberOtpFlow({
				phone: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				countryCode: formData?.iso2?.value,
				otp: formData?.otp?.value,
				name: formData?.name?.value,
				newUser,
			});
		}
		if (updatePhoneScreen === false) {
			updateFormData(['otp'], ['']);
			sendUpdatePhoneOtp();
			nbGaEvent(pageSpecificData.gaEventCategory, `UseNewPhone-${pageSpecificData.flow}`);
			return setUpdatePhoneScreen(!updatePhoneScreen);
		}
		return null;
	};

	// Method to show success and failure for new mobile update api

	useEffect(() => {
		if (isActiveNewFlow) {
			setLoaderState(false);
			if (newMobileUpdateSucess) {
				nbGaEvent('email_verified', 'migrate_new_sucess', {
					phoneNumber: formData?.phoneNumber?.value,
					email: formData?.email?.value,
					name: formData?.name?.value,
					newUser,
					...customExtraInfo,
				});
				setTimeout(() => {
					onCompletion(userInfo);
				}, 2000);
			}
		} else if (newMobileUpdateError) {
			setFromErrorMsg('New Mobile Updation Failed');
		}
	}, [newMobileUpdateSucess, newMobileUpdateError]);

	// Method to Toggle Password Visibility
	const togglePasswordVisibility = () => {
		nbGaEvent(pageSpecificData.gaEventCategory, `ShowPassword_SignIn-${pageSpecificData.flow}`);
		setPasswordVisibility(!passwordVisibility);
	};

	const maskEmail = (email, maskCharacter = 'x') => {
		const breakingPoint = email.indexOf('@');
		const userName = email.substr(0, breakingPoint);
		const domain = email.substr(breakingPoint);
		const validUpto = Math.ceil(userName.length * 0.4);
		const maskingCharacterLength = userName.length - validUpto;
		return `${userName.substr(0, validUpto)}${maskCharacter.repeat(maskingCharacterLength)}${domain}`;
	};

	const maskPhone = (phone, maskCharacter = 'x') => {
		phone = phone.toString();
		if (phone.length === 13 && phone.startsWith('+91')) {
			phone = phone.replace('+91', '');
		} else if (phone.length === 12 && phone.startsWith('91')) {
			phone = phone.replace('91', '');
		}
		const firstPart = phone.substr(0, 2);
		const lastPart = phone.substr(phone.length - 3, phone.length);
		let middlePart = '';
		for (let index = 2; index < phone.length - 3; index++) {
			middlePart += maskCharacter;
		}
		return firstPart + middlePart + lastPart;
	};

	// did mount
	useEffect(() => {
		try {
			if (show) {
				setOTPEmailLabelStatus(false);
				// logging adobeevent
				/* Timeout added before this AMO event to make sure its not nullyfying any previous event which is just fired preponed to this */
				setTimeout(() => {
					adobeMediaOptimiser.logEvent(`ev_Userdetailpopup-${readCookie('nbpt')}`);
				}, 500);
				document.body.classList.add('overflow-hidden');
				if (handleRedirectionFromParent.includes(type))
					history.replace(`${window.location.pathname}${window.location.search || ''}#${MODAL_HASH}`);
				else history.replace(`${location.pathname}${location.search || ''}#${MODAL_HASH}`);
				// window.location.hash = MODAL_HASH;
				window.addEventListener('hashchange', handleHashChange);
				document.addEventListener('keydown', handleKeyDown);
				document.addEventListener('click', handleClick);
				if (preSelectedPhone && preSelectedPhone.dialCode) {
					if (pageSpecificData?.otpGAMandate) {
						nbGaEvent(pageSpecificData.gaEventCategory, `otp_popup_view`);
						nbGaEvent('signup_otp_mandate', `otp_popup_view`);
					}
					setTimeout(() => {
						window.triggerAlert(
							pageSpecificData?.errorMessageOTP ||
							'An account already exists with the give credentials. Please login to continue',
							'error'
						);
						updateFormData(
							['phoneNumber', 'dialCode', 'iso2'],
							[preSelectedPhone.phone, preSelectedPhone.dialCode.dialCode, preSelectedPhone.dialCode.iso2]
						);
					}, 100);
				}
				if (preSelectedNameAndEmail) {
					setTimeout(() => {
						updateFormData(['name', 'email'], [preSelectedNameAndEmail.name, preSelectedNameAndEmail.email]);
					}, 100);
				}
			}
		} catch (e) {
			// no doc
		}
	}, [show]);

	// Handling GA event in case of otp failure and already email exist.

	// eslint-disable-next-line consistent-return
	useEffect(() => {
		if (!isActiveNewFlow) return null;
		if (activeStep === 2 && formData?.email?.isError && formData?.email?.errorMsg !== 'Please enter valid email') {
			nbGaEvent('user_name_email', 'detail_exist', {
				phoneNumber: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				name: formData?.name?.value,
				newUser,
				...customExtraInfo,
			});
		}
		if (activeStep === 2 && formData?.email?.isError && formData?.email?.errorMsg === 'Please enter valid email') {
			nbGaEvent('user_name_email', 'detail_fail', {
				phoneNumber: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				name: formData?.name?.value,
				newUser,
				...customExtraInfo,
			});
		}
		if (activeStep === 4 && formData?.otp?.isError)
			nbGaEvent('user_otp_email', 'otp2_fail', {
				phoneNumber: formData?.phoneNumber?.value,
				email: formData?.email?.value,
				name: formData?.name?.value,
				newUser,
				...customExtraInfo,
			});
		if (activeStep === 3 && formData?.otp?.isError)
			nbGaEvent('user_otp_number', 'otp1_fail', {
				phoneNumber: formData?.phoneNumber?.value,
				newUser,
				...customExtraInfo,
			});
	}, [formData?.otp?.isError, formData?.email?.isError]);

	// handle new User or Old User decision
	useEffect(() => {
		if (newOtpVerifyFlow && (newUser || oldUser) && activeStep === 3)
			nbGaEvent('user_otp_number', 'otp1_pass', {
				phoneNumber: formData?.phoneNumber?.value,
				newUser,
				...customExtraInfo,
			});
		if (emailLogin && show) {
			// otp already sent
			setStep(4);
			setScroll(125);
		}
		if (show && activeStep === 1) {
			if (!phoneNumberChangeFlag) {
				const isChecked = existingWhatsAppStatus || DEFAULT_WHATSAPP_OPT_IN;
				updateFormData(['whatsAppOptIn', 'whatsAppOptInSource'], [isChecked, isChecked ? 'loginSignup' : undefined]);
			}
			if (newUser) {
				nbGaEvent(pageSpecificData.gaEventCategory, `newPhone-${pageSpecificData.flow}`);
			

				setStep(2);
				setPhoneNumberChangeFlag(false);
				setScroll(125);
				// eslint-disable-next-line no-unused-expressions
				!isActiveNewFlow
					? nbGaEvent('user_signup', 'newPhone_signup', { service: serviceType, ...customExtraInfo })
					: nbGaEvent('user_signup', 'newPhone_signup', { service: serviceType, ...customExtraInfo });
				try {
					document.getElementById('login-signup-form__name-input').focus();
				} catch (e) {
					// err
				}
			} else if (oldUser) {
				nbGaEvent(pageSpecificData.gaEventCategory, `SignIn_Initiated-${pageSpecificData.flow}`);
				nbGaEvent('user_signup', 'login_initiated', { service: serviceType, ...customExtraInfo });
				if (isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'number_screen_view_old_defer');
				setStep(3);
				// send otp
				sendOTP();
				setScroll(125);
			} else {
				setScroll(0);
			}
		}
	}, [newUser, oldUser, emailLogin, newOtpVerifyFlow]);

	// detect phone number change
	useEffect(() => {
		// phoneNumberChangeFlag check from this validation call is changed
		if (show) {
			validation(true, formData?.dialCode?.value !== '91');
		}
	}, [formData.phoneNumber, isContinueClicked]);

	/* Method to Submit the Singup/Login Success ADOBE EVENTS */

	// detect signup completed
	useEffect(() => {
		if (newAccountData === null) return;
		setLoaderState(false);
		if (
			(userInfo && userInfo.isLoggedIn && newAccountData) ||
			(isActiveNewFlow && newAccountData && formData.dialCode.value === '91')
		) {
			try {
				nbCache.set('urlObj', { urlSet: true });
			} catch (error) {
				// console.log(error);
			}

			nbGaEvent('NewUser', `${pageSpecificData.flow}`);
			nbGaEvent('NewUser', 'signup_success', {
				service: serviceType,
				userId: userInfo?.id,
				property_city: cookieHandler.get('nbcr') || null,
				property_type:
					(cookieHandler.get('nbpt')?.toLowerCase() &&
						getFormattedPropertyType(cookieHandler.get('nbpt')?.toLowerCase())) ||
					customExtraInfo?.property_type?.toLowerCase() ||
					null,
				property_Price: customExtraInfo?.property_Price,
			});
			if (pageSpecificData.flow !== 'pyp') onCompletion(userInfo);
			try {
				facebookEvent.triggerCapiEvent(
					`UserRegistration${cookieHandler.get('nbpt')?.toLowerCase()
						? `_${getFormattedPropertyType(cookieHandler.get('nbpt')?.toLowerCase())}`
						: ''
					}`,
					userInfo
				);
				facebookEvent.triggerCapiEvent(
					`signup_${cookieHandler.get('nbpt')?.toLowerCase()
						? `_${getFormattedPropertyType(cookieHandler.get('nbpt')?.toLowerCase())}`
						: ''
					}`,
					userInfo
				);
			} catch (error) {
				console.log(error);
			}
		} else if (newAccountData && isOtpMandateFlowEnabled) {
			setStep(3);
			sendOTP();
			setLoaderState(false);
			nbSwagger.goalDone('otp_mandate_experiment', 'showOtp');
			nbGaEvent('signup_otp_mandate', `otp_popup_view`, { userId: newAccountCreationData?.id });
			nbGaEvent('NewUser', `${pageSpecificData.flow}`);
			nbGaEvent('NewUser', 'signup_success', {
				service: serviceType,
				userId: newAccountCreationData?.id,
				property_city: cookieHandler.get('nbcr') || null,
				property_type:
					(cookieHandler.get('nbpt')?.toLowerCase() &&
						getFormattedPropertyType(cookieHandler.get('nbpt')?.toLowerCase())) ||
					customExtraInfo?.property_type?.toLowerCase() ||
					null,
				property_Price: customExtraInfo?.property_Price,
			});
		}
		if (newAccountDataError) {
			// only email error handled
			if (newAccountDataError.match('Email') !== null) {
				nbGaEvent(pageSpecificData.gaEventCategory, `email_phone_mismatch-${pageSpecificData.flow}`);
				updateFormData('email', formData.email.value, true, 'alreadyExist');
			} else {
				setFromErrorMsg(SIGNUP_MODAL_CONSTANT.DEFAULT_ALERT_MSG);
			}
			try {
				const phoneNumber = formData.phoneNumber.value;
				const dialCode = formData.dialCode.value;
				const {
					email: { value: email },
					name: { value: name },
				} = formData;
				nbGaEvent('signup_otp_mandate', `detail_submit_failed`, {
					eventDetailsInfo: JSON.stringify({
						name,
						phoneNumber,
						email,
						dialCode,
					}),
				});
				nbGaEvent(pageSpecificData.gaEventCategory, `detail_submit_failed`, {
					eventDetailsInfo: JSON.stringify({
						name,
						phoneNumber,
						email,
						dialCode,
					}),
				});
			} catch (error) {
				console.log(error);
			}
		}
	}, [newAccountData, newAccountDataError]);

	// Change the value of Email- OTP popup
	useEffect(() => {
		// eslint-disable-next-line no-unused-expressions
		isActiveNewFlow && sendNewOtpFlowGAEventForScreenView(activeStep, formData, newUser, customExtraInfo);
		if (activeStep === 3 && formData?.dialCode?.value !== '91') setOTPEmailLabelStatus(true);
		if (activeStep === 3 && isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'otp1_screen_view_defer');
	}, [activeStep]);

	// close the Email- OTP popup
	const handleOTPEmailPopupClose = () => {
		setOTPEmailLabelStatus(false);
	};

	async function checkForOtpMendateFlow() {
		setOtpMandateFlowEnabled(true);
	}

	const setNewOtpFlow = async () => {
		try {
			setIsActiveNewFlow(true);
			sendNewOtpFlowGAEventForScreenView(activeStep, formData, newUser, customExtraInfo);
				if (isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'number_screen_view_new_defer');
		} catch (e) {
			console.error(e);
		}
	};

	useEffect(() => {
		setNewOtpFlow();
		if (typeof window !== 'undefined') {
			// initializeClarity(userInfo?.id, 'SignLoginPageFlow');
			checkForOtpMendateFlow();
		}
	}, []);

	useEffect(() => {
		if (newAccountCreationData && newAccountCreationData?.id) {
			nbCache.set('ustats', { id: newAccountCreationData?.id });
		}
	}, [newAccountCreationData]);

	// detect login completed
	useEffect(() => {
		if (userInfo && userInfo.isLoggedIn && (otpVerification || passwordVerification)) {
			nbGaEvent(
				pageSpecificData.gaEventCategory,
				`${passwordVerification ? 'SignIn_success-password' : 'SignIn_success-otp'}-${pageSpecificData.flow}`
			);
			if (isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'otp1_pass_defer');
			setLoaderState(false);
			onCompletion(userInfo);
			// if (!adobeSignupEventCalled) {
			// 	setAdobeSignupEventCalled(true);
			// }
			if (isOtpMandateFlowEnabled && newAccountData && !passwordVerification) {
				nbSwagger.goalDone('otp_mandate_experiment', 'otpVerified');
				nbGaEvent('signup_otp_mandate', `otp_success`);
			}
			if (pageSpecificData?.otpGAMandate) {
				nbGaEvent(pageSpecificData.gaEventCategory, `otp_success`);
				nbGaEvent('signup_otp_mandate', `otp_success`);
			}
			nbGaEvent('user_signup', `login_success_${otpVerification ? 'otp' : 'password'}`, {
				service: serviceType,
				...customExtraInfo,
			});
			nbGaEvent('user_signin', 'login_success', { service: serviceType, userId: userInfo?.id, ...customExtraInfo });
		} else if (otpVerification === false) {
			setLoaderState(false);
			verifyOtpFired.current = false;
			nbGaEvent('user_signup', 'login_failed_otp', { service: serviceType, ...customExtraInfo });
			nbGaEvent(pageSpecificData.gaEventCategory, `SignIn_failed-otp-${pageSpecificData.flow}`);
			if (isOtpMandateFlowEnabled && newAccountData) {
				nbGaEvent('signup_otp_mandate', `otp_fail`);
			}
			if (pageSpecificData?.otpGAMandate) {
				nbGaEvent(pageSpecificData.gaEventCategory, `otp_fail`);
				nbGaEvent('signup_otp_mandate', `otp_fail`);
			}
			if (isDeferredFlowRef.current) nbGaEvent('user_otp_number', 'otp1_fail_defer');
			if (emailLogin && formData.otp.value === '') return;
			updateFormData('otp', '', true, SIGNUP_MODAL_CONSTANT.OTP_INVALID_ERROR);
		} else if (passwordVerification === false) {
			setLoaderState(false);
			nbGaEvent('user_signup', 'login_failed_password', { service: serviceType, ...customExtraInfo });
			nbGaEvent(pageSpecificData.gaEventCategory, `SignIn_failed-password-${pageSpecificData.flow}`);
			updateFormData('password', '', true, SIGNUP_MODAL_CONSTANT.PASSWORD_INVALID_ERROR);
		} else if (emailOtpVerification === true) {
			isActiveNewFlow &&
				nbGaEvent('user_otp_email', 'otp2_success', {
					phoneNumber: formData?.phoneNumber?.value,
					name: formData?.name?.value,
					email: formData?.email?.value,
					...customExtraInfo,
				});
			setLoaderState(false);
			setStep(5);
		}
	}, [userInfo?.isLoggedIn, otpVerification, passwordVerification, emailOtpVerification, verifyOtpFired.current]);
	if (!show) return null;
	let forceOverFlow = false;
	if (typeof window === 'object' && window.innerHeight < 450) {
		forceOverFlow = true;
	}
	let isMobile = cookies && cookies?.isMobile === 'true';
	if (typeof window !== 'undefined') {
		isMobile = window?.innerWidth < 1026;
	}

	return (
		<div
			className={`login-signup ${activeStep > 1 || forceOverFlow ? 'overflow' : ''}`}
			id='login-signup-modal'
			style={
				type === 'MapPropertyDetailMob' || type === 'filterApplyMob'
					? {
						height: activeStep === 1 ? '54vh' : '58vh',
						bottom: '0px',
						borderRadius: '28px 28px 0px 0px',
						zIndex: '30',
					}
					: { top: '0px' }
			}
		>
			{backdrop && (
				<div
					className='login-signup__backdrop'
					onClick={() => {
						isActiveNewFlow &&
							activeStep === 1 &&
							nbGaEvent('user_otp_number', 'number_screen_view_close', { newUser, ...customExtraInfo });
						isActiveNewFlow &&
							activeStep === 2 &&
							nbGaEvent('user_otp_number', 'email_screen_detail_close', { newUser, ...customExtraInfo });
						isActiveNewFlow &&
							activeStep === 3 &&
							nbGaEvent('user_otp_number', 'number_otp_screen_close', { newUser, ...customExtraInfo });
						if (isDeferredFlowRef.current) {
							if (activeStep === 1) nbGaEvent('user_otp_number', 'number_screen_view_close_defer');
							if (activeStep === 3) {
								nbGaEvent('user_otp_number', 'number_otp_screen_close_defer');
								nbGaEvent('user_otp_number', 'otp1_cross_defer');
							}
						}
					}}
				/>
			)}
			{showLoader && <NbLoader />}
			{formErrorMsg && <AlertBox msg={formErrorMsg} />}
			<div
				className={`login-signup__modal step${activeStep}`}
				style={
					type === 'MapPropertyDetailMob' || type === 'filterApplyMob'
						? { height: activeStep === 1 ? '54vh' : '58vh', minHeight: '58vh' }
						: {}
				}
			>
				<div className='login-signup__modal-dialog'>
					{type !== 'ListPageSignIn' &&
						type !== 'MapPropertyDetailMob' &&
						type !== 'filterApplyMob' &&
						type !== 'shortlistMapMob' ? (
						// eslint-disable-next-line no-unused-expressions
						<div
							className='login-signup__modal-close-icon'
							onClick={() => {
								closeModal();
								isActiveNewFlow && sendNewOtpFlowGAEventForCloseButton(activeStep, formData, newUser);
								isActiveNewFlow &&
									activeStep === 1 &&
									nbGaEvent('user_otp_number', 'number_screen_view_close', { newUser, ...customExtraInfo });
								isActiveNewFlow &&
									activeStep === 2 &&
									nbGaEvent('user_otp_number', 'email_screen_detail_close', { newUser, ...customExtraInfo });
								isActiveNewFlow &&
									activeStep === 3 &&
									nbGaEvent('user_otp_number', 'number_otp_screen_close', { newUser, ...customExtraInfo });
								if (isDeferredFlowRef.current) {
									if (activeStep === 1) nbGaEvent('user_otp_number', 'number_screen_view_close_defer');
									if (activeStep === 3) {
										nbGaEvent('user_otp_number', 'number_otp_screen_close_defer');
										nbGaEvent('user_otp_number', 'otp1_cross_defer');
									}
								}
							}}
						>
							<Icons type='close' />
						</div>
					) : type === 'MapPropertyDetailMob' || type === 'filterApplyMob' ? (
						<div
							className='rounded-10 w-5p h-0.6p absolute top-0.6p'
							onClick={closeModal}
							style={{ right: '43vw', backgroundColor: '#E0E0E0' }}
						></div>
					) : null}
					<div className='login-signup__modal-content'>
						<div
							className='login-signup__modal-content-left'
							style={
								(type === 'MapPropertyDetailMob' || type === 'filterApplyMob') && activeStep > 1
									? { display: 'none' }
									: {}
							}
						>
							<div
								className={`login-signup__modal-content-left-img ${type}`}
								style={
									type === 'MapPropertyDetailMob' || type === 'filterApplyMob'
										? { height: '100px', width: '100px' }
										: {}
								}
							>
								<img
									src={pageSpecificData?.image}
									alt='signup'
									style={
										type === 'MapPropertyDetailMob' || type === 'filterApplyMob'
											? { height: '100px', width: '100px' }
											: {}
									}
								/>
							</div>
							<div className='login-signup__modal-content-left-content'>
								<div
									className='left-content-heading heading-5 font-semi-bold'
									style={type === 'MapPropertyDetailMob' || type === 'filterApplyMob' ? { marginBottom: '0px' } : {}}
								>
									{!isDeferredFlowRef?.current ? pageSpecificData?.title : 'Login/Sign up to post your property'}
								</div>
								{pageSpecificData.subTitle &&
									type !== 'filterApply' &&
									type !== 'MapPropertyDetail' &&
									type !== 'shortlistMap' &&
									type !== 'premiumFiltersMap' &&
									type !== 'polygonClick' && (
										<div
											className='sub-title'
											style={
												type === 'MapPropertyDetailMob' || type === 'filterApplyMob'
													? {
														display: 'inline',
														fontSize: '26px',
														fontWeight: 'bold',
														fontFamily: 'roboto',
														color: '#454F63',
														position: 'relative',
													}
													: {}
											}
										>
											{ pageSpecificData.subTitle }
											{(type === 'MapPropertyDetailMob' || type === 'filterApplyMob') && (
												<div
													style={{ height: '32px', width: '32px', position: 'absolute', right: '-30px', top: '0px' }}
												>
													<Lottie options={lockLottie} height={32} width={32} />
												</div>
											)}
										</div>
									)}

								{pageSpecificData.checklist && pageSpecificData.checklist.length > 0 && (
									<ul className='checklist' style={isDeferredFlowRef?.current  ? {paddingBottom : '12px'} : {}}>

										{checkListOptimize(pageSpecificData.checklist).map((checkListData) => (
											<li title={checkListData} key={checkListData}>
												{checkListData}   
											</li>
										))}
									</ul>
								)}
							</div>
						</div>
						<div
							className='login-signup__modal-content-right'
							style={type === 'MapPropertyDetailMob' || type === 'filterApplyMob' ? { minHeight: '54vh' } : {}}
						>
							{activeStep === 1
								? (type === 'MapPropertyDetail' ||
									type === 'filterApply' ||
									type === 'shortlistMap' ||
									type === 'premiumFiltersMap' ||
									type === 'polygonClick') && (
									<div className='flex flex-col items-center mb-3p'>
										<div style={{ height: '124px', width: '140px' }}>
											<img alt='' src={mobileSignUp} style={{ height: '122px', width: '140px' }}></img>
										</div>
										<div
											style={{
												display: 'inline',
												fontSize: '26px',
												fontWeight: 'bold',
												fontFamily: 'roboto',
												color: '#454F63',
												position: 'relative',
											}}
										>
											{pageSpecificData.subTitle}
											<div style={{ height: '32px', width: '32px', position: 'absolute', left: '-34px', top: '3px' }}>
												<Lottie options={lockLottie} height={32} width={32} />
											</div>
										</div>
									</div>
								)
								: null}
							<form
								noValidate
								action='#'
								id='login-signup-form'
								className='login-signup__modal-form'
								onSubmit={handleFormSubmit}
							>
								<div className='login-signup-form__top-label heading-5 font-semi-bold'>
									{SIGNUP_MODAL_CONSTANT[`STEP${activeStep}_TOP_LABEL`]}
								</div>
								{/* STEP1 PHONE NUMBER/WHATSAPP COMMON */}
								<div className={`login-signup-form-group ${activeStep === 5 ? 'hidden' : ''}`}>
									{/* PHONE NUMBER */}
									<div className='login-signup-form__phone-number'>
										{activeStep === 1 ? (
											<NbTelInput
												onSelectFlag={(event, { dialCode, iso2 }) => {
													updateFormData(['dialCode', 'iso2'], [dialCode, iso2]);
												}}
												value={formData.phoneNumber.value}
												onPhoneNumberChange={(status, val, length) => {
													if (val === formData.phoneNumber.value) return;
													if (length > 0 && maxIndLength === 18 && formData.dialCode.value === '91') {
														setMaxIndLength(10);
													} else if (length === 0 && maxIndLength === 10 && formData.dialCode.value === '91') {
														setMaxIndLength(18);
													}
													updateFormData(['phoneNumber', 'name', 'email', 'whatsAppOptIn'], [val, '', '', true], () => {
														setWhatsAppShowFlag(true);
													});
												}}
												id={'signUp-phoneNumber'}
												inputClassName={`login-signup-form__phone-number-input ${showWhatsApp ? 'whatsAppOpen' : ''} ${formData.phoneNumber.isError ? 'error' : ''
													}`}
												defaultCountry={formData.iso2.value || 'in'}
												maxLength={formData.dialCode.value === '91' ? maxIndLength : 15}
												autoFocus
											/>
										) : (
											<div
												className={`login-signup-form__phone-number-read-only ${showWhatsApp ? 'whatsAppOpen' : ''}`}
											>
												<div className='login-signup-form__phone-number-read-only-text'>{`+${formData.dialCode.value} ${formData.phoneNumber.value}`}</div>
												<div
													className='login-signup-form__phone-number-read-only-action'
													onClick={() => {
														setPhoneNumberChangeFlag(true);
														removeUsersinupState();
														setStep(1);
														onChangePhone();
														setOTPEmailLabelStatus(false);
														try {
															if (
																typeof window === 'object' &&
																typeof document === 'object' &&
																window.innerWidth < 768
															) {
																document.getElementById('login-signup-modal').scrollTo(0, 0);
															}
														} catch (e) {
															// reset scroll error
														}
													}}
												>
													{'Change Phone'}
												</div>
											</div>
										)}
									</div>

									{/* WhatsAPP */}
									{pageSpecificData.watsappOptInText && (
										<div className={`login-signup-form__whatsApp-notification ${showWhatsApp ? 'whatsAppOpen' : ''}`}>
											<div className='login-signup-form__whatsApp-notification-label flex'>
												{withCustomIcon(pageSpecificData.watsappOptInText)}
											</div>
											<div className='login-signup-form__whatsApp-notification-input'>
												<NbSwitch
													onChange={(event) => {
														const isChecked = event.target.checked;
														updateFormData(
															['whatsAppOptIn', 'whatsAppOptInSource'],
															[isChecked, isChecked ? 'loginSignup' : undefined]
														);
													}}
													isChecked={formData.whatsAppOptIn.value}
													onClick={
														!formData.whatsAppOptIn.value &&
														nbGaEvent(
															pageSpecificData.gaEventCategory,
															`WhatsAppOptOut_SignIn-${pageSpecificData.flow}`
														)
													}
													size='xs'
												/>
											</div>
										</div>
									)}
									<div
										className={`text-error-color login-signup-form__phone-number-error ${showWhatsApp ? 'whatsAppOpen' : ''
											}`}
									>
										{formData.phoneNumber.isError && formData.phoneNumber.errorMsg}
									</div>
								</div>

								{/* STEP2 SIGNUP */}
								<div className={`login-signup-form-group step2 overflow-visible ${activeStep === 2 ? 'show' : ''} `}>
									{/* NAME INPUT */}
									<div className='login-signup-form__name'>
										<NbInput
											onChange={({ target: { value: val } }) => {
												updateFormData('name', val);
											}}
											placeholder='Name'
											type='text'
											autoFocus
											autoCompleteType='name'
											value={formData.name.value}
											id='login-signup-form__name-input'
											errorMsg={formData.name.errorMsg}
											hasError={formData.name.isError}
										/>
									</div>

									{/* Email INPUT */}
									<div className='login-signup-form__email'>
										<EmailInputWithSuggestion
											ref={emailRef}
											value={formData?.email?.value}
											formError={formData?.email?.errorMsg}
											onChange={(val) => updateFormData('email', val)}
											onValidSubmit={() => {
												isActiveNewFlow && sendNewOtpFlowGAEventForContinueButton(activeStep, formData, newUser);
											}}
										/>

										{formData?.email?.errorMsg === 'alreadyExist' && (
											<div className='email-exist-error-message'>
												{'Email already in use '}
												<span className='font-semi-bold'>{formData.email.value}</span>
												{'. Please '}
												{
													<span
														className='email-otp-trigger'
														onClick={() => {
															isActiveNewFlow &&
																nbGaEvent('user_name_email', 'detail_exist_email_click', {
																	phoneNumber: formData?.phoneNumber?.value,
																	name: formData?.name?.value,
																	email: formData?.email?.value,
																	...customExtraInfo,
																});
															sendOTPToEmail(formData.email.value);
															updateFormData('otp', '');
															// console.log(error);
															setAutoReadOtpDetected(false);
														}}
													>
														{'Login with email OTP'}
													</span>
												}
												{' to continue.'}
											</div>
										)}
									</div>
								</div>
								{showEmailErrorPopup && (
									<div
										className={`${isMobile
											? 'w-full h-full bg-[#00000099] flex items-end justify-center z-10 backdrop-blur-[7.8px] fixed top-0 left-0'
											: 'login-signup-form-group step6 '
											} ${activeStep === 6 ? 'show' : 'hidden'}`}
									>
										<InvalidDomainPopup
											className={isMobile ? 'w-[350px] h-[333px]' : ''}
											isMobile={isMobile}
											value={formData?.email?.value}
											setShowEmailErrorPopup={setShowEmailErrorPopup}
											emailErrorMessage={emailErrorMessage}
											setEmailDomainDecisionDone={setEmailDomainDecisionDone}
											correctedEmail={correctedEmail}
											onChange={(updatedEmail) => {
												updateFormData('email', updatedEmail);
												setStep(2);
											}}
											onContinue={() => {
												setShowEmailErrorPopup(false);
												setStep(2);
											}}
										/>
									</div>
								)}

								{/* STEP3 LOGIN */}
								<div
									className={`login-signup-form-group step3 ${activeStep === 3 ? 'show' : ''} ${showWhatsApp ? '' : 'whatsAppNotOpen'
										}`}
								>
									{!isMobile && isOTPEmailLabelStatus && (
										<div className='otp-email-toast-message-block'>
											<div className='otp-email-toast-label'>The OTP has been sent to your Registered Email Id</div>
										</div>
									)}
									{/* Radio Box */}
									{(!isOtpMandateFlowEnabled || !newAccountData) &&
										!pageSpecificData?.isOTPVerify &&
										(!isActiveNewFlow || formData.dialCode.value !== '91') ? (
										<NbRadio
											validationState={null}
											name='loginType'
											onChange={(event) => {
												updateFormData('loginMethod', event.target.value);
												nbGaEvent('user_signup', 'toggle_otp_login', { service: serviceType, ...customExtraInfo });
											}}
											onClick={() => {
												nbGaEvent(pageSpecificData.gaEventCategory, `ToggleOTP_SignIn-${pageSpecificData.flow}`);
											}}
											text='Generate OTP'
											id='login-signup-form-login-radio-otp'
											inline
											value='otp'
											checked={formData.loginMethod.value === 'otp'}
										/>
									) : null}
									{(!isOtpMandateFlowEnabled || !newAccountData) &&
										!pageSpecificData?.isOTPVerify &&
										(!isActiveNewFlow || formData.dialCode.value !== '91') ? (
										<NbRadio
											validationState={null}
											name='loginType'
											onChange={(event) => {
												updateFormData('loginMethod', event.target.value);
												nbGaEvent('user_signup', 'toggle_password_login', { service: serviceType, ...customExtraInfo });
											}}
											onClick={() => {
												nbGaEvent(pageSpecificData.gaEventCategory, `TogglePassword_SignIn-${pageSpecificData.flow}`);
											}}
											text="I've Password"
											id='login-signup-form-login-radio-password'
											checked={formData.loginMethod.value === 'password'}
											inline
											value='password'
										/>
									) : null}
									{activeStep === 3 && (
										<div className='login-signup-form-authentication-input'>
											{formData.loginMethod.value === 'otp' ? (
												// OTP
												<>
													<NbOTP
														size={
															pageSpecificData?.isOTPVerify || (isActiveNewFlow && formData.dialCode.value === '91')
																? 6
																: 4
														}
														onChange={(val) => {
															updateFormData(['password', 'otp'], ['', val]);
															setAutoReadOtpDetected(false);
														}}
														autoFocus
														hasError={formData.otp.isError}
														errorMsg={formData.otp.errorMsg}
														value={formData.otp.value}
														otpResend
														otpResendClick={(event) => {
															event.preventDefault();
															!isActiveNewFlow &&
																nbGaEvent('user_signup', 'resend_otp_login', {
																	service: serviceType,
																	...customExtraInfo,
																});
															!isActiveNewFlow &&
																nbGaEvent(
																	pageSpecificData.gaEventCategory,
																	`ResendOTP_SignIn--${pageSpecificData.flow}`
																);
															!isActiveNewFlow &&
																nbGaEvent(
																	pageSpecificData.gaEventCategory,
																	`ToggleOTP_SignIn-${pageSpecificData.flow}`
																);
															isActiveNewFlow &&
																activeStep === 3 &&
																nbGaEvent('user_otp_number', 'otp1_resend', {
																	phoneNumber: formData?.phoneNumber?.value,
																	...customExtraInfo,
																});
															if (isDeferredFlowRef.current && activeStep === 3) nbGaEvent('user_otp_number', 'otp1_resend_defer');
															sendOTP();
															isActiveNewFlow &&
																activeStep === 4 &&
																nbGaEvent('user_otp_email', 'otp2_resend', {
																	phoneNumber: formData?.phoneNumber?.value,
																	email: formData?.email?.value,
																	name: formData?.name?.value,
																	...customExtraInfo,
																});
														}}
														type={isAutoReadOtpDetected && formData?.otp?.value?.length > 3 ? 'normal' : 'otp'}
														inputWidth={'80%'}
														otpResendTimeout={30}
													/>
												</>
											) : (
												<>
													<NbInput
														onChange={({ target: { value: val } }) => {
															updateFormData(['password', 'otp'], [val, '']);
														}}
														placeholder='Enter Password'
														type={passwordVisibility ? 'text' : 'password'}
														autoFocus
														value={formData.password.value}
														id='login-signup-form__password-input'
														errorMsg={formData.password.errorMsg}
														hasError={formData.password.isError}
														rightIcon={
															passwordVisibility ? (
																<span onClick={togglePasswordVisibility}>
																	<img src={Visibility} alt='' className='cursor-pointer custom-material-icon' />
																</span>
															) : (
																<span onClick={togglePasswordVisibility}>
																	<img src={VisibilityOff} alt='' className='cursor-pointer custom-material-icon' />
																</span>
															)
														}
													/>
												</>
											)}
											{isMobile && (
												<NbModal
													mobileFullScreen={false}
													backDropClose={false}
													showState={isOTPEmailLabelStatus}
													containerClass='email-otp-popup-message'
													size='sm'
												>
													<div className='otp-email-popup-block'>
														<div className='otp-email-label'>The OTP has been sent to your Registered Email Id</div>
														<div className='confirm-label' onClick={handleOTPEmailPopupClose}>
															OK
														</div>
													</div>
												</NbModal>
											)}
										</div>
									)}
								</div>

								{/* STEP4 LOGIN VIA EMAIL OTP */}
								<div
									className={`login-signup-form-group step4 ${activeStep === 4 ? 'show' : ''} ${showWhatsApp ? '' : 'whatsAppNotOpen'
										}`}
								>
									<div className='login-signup-form__email-read-only'>
										<div className='login-signup-form__email-read-only-text'>{`${maskEmail(
											formData.email.value
										)}`}</div>
										<div
											className='login-signup-form__email-read-only-action'
											onClick={() => {
												isActiveNewFlow &&
													nbGaEvent('user_otp_email', 'otp2_change_email', {
														phoneNumber: formData?.phoneNumber?.value,
														name: formData?.name?.value,
														email: formData?.email?.value,
														...customExtraInfo,
													});
												setStep(2);
												// eslint-disable-next-line no-unused-expressions
												removeSignUpViaEmailState();
											}}
										>
											{'Change Email'}
										</div>
									</div>
									<div className='email-otp-input'>
										{activeStep === 4 && (
											<NbOTP
												size={4}
												label={`Enter the OTP send to <span className='font-semi-bold'>${maskEmail(
													formData.email.value
												)}</span>`}
												onChange={(val) => {
													updateFormData(['password', 'otp'], ['', val]);
												}}
												value={formData.otp.value}
												autoFocus
												hasError={formData.otp.isError}
												errorMsg={formData.otp.errorMsg}
												infoMsg={otpInfoMsg}
												otpResend
												otpResendClick={(event) => {
													event.preventDefault();
													sendOTPToEmail(formData.email.value);
												}}
												inputWidth={'80%'}
												otpResendTimeout={60}
											/>
										)}
									</div>
								</div>
								<div
									className={`login-signup-form-group step5 ${activeStep === 5 ? 'show' : 'hidden'} ${showWhatsApp ? '' : 'whatsAppNotOpen'
										}`}
								>
									<div className='heading-5 font-semi-bold'>Phone Verification</div>
									{userPhoneData && updatePhoneScreen === false && (
										<div>
											<div className='phone-verification-content'>
												Your account <span className='font-semi-bold'>{userPhoneData.existingEmail}</span> is linked
												with the number{' '}
												<span className='font-semi-bold'>
													{userPhoneData.existingPhone && maskPhone(userPhoneData.existingPhone)}
												</span>
												.
											</div>
											<NbButton
												id='signUpUpdateNumber'
												type='button'
												btnStyle='primary'
												block
												onClick={goToUpdatedPhoneScreen}
											>
												Update my number to{' '}
												{((!isActiveNewFlow || formData.dialCode.value !== '91') && userPhoneData?.newPhone) ||
													formData?.phoneNumber?.value}
											</NbButton>
											<div className='text-center or-devider'>
												<span>OR</span>
											</div>
											<NbButton
												id='signUpContNumber'
												type='button'
												btnStyle='info'
												block
												onClick={continueWithExistingPhone}
											>
												Continue using {userPhoneData.existingPhone && maskPhone(userPhoneData.existingPhone)}
											</NbButton>
										</div>
									)}
									{userPhoneData && updatePhoneScreen && (
										<div>
											<div className='phone-verification-content'>
												Please enter the OTP sent to <span className='font-semi-bold'>{userPhoneData.newPhone}</span> to
												verify the phone number update.
											</div>
											<NbOTP
												size={6}
												label={`Enter the OTP send to <span className='font-semi-bold'>${userPhoneData.newPhone}</span>`}
												value={formData.otp.value}
												onChange={(val) => updateFormData(['otp'], [val])}
												autoFocus
												hasError={formData.otp.isError}
												errorMsg={formData.otp.errorMsg}
												infoMsg={otpInfoMsg}
												otpResend
												otpResendClick={(event) => {
													event.preventDefault();
													sendUpdatePhoneOtp();
												}}
												inputWidth={'80%'}
												otpResendTimeout={60}
											/>
											<div className='update-phone-cta-container'>
												<NbButton
													id='signupUpdateAndLogin'
													type='button'
													btnStyle='primary'
													block
													onClick={updatePhone}
												>
													Update and Login
												</NbButton>
												<div className='text-center'>
													Don&apos;t want to update the number?{' '}
													<span className='update-phone-go-back' onClick={goToUpdatedPhoneScreen}>
														Go Back
													</span>
												</div>
											</div>
										</div>
									)}
								</div>

								<div
									className={`login-signup-form-submit-button step${activeStep} ${showWhatsApp ? 'whatsAppOpen' : ''} ${activeStep === 5 ? 'hidden' : ''
										} ${activeStep === 6 ? 'hidden' : ''}`}
								>
									<NbButton
										id='signUpSubmit'
										type='submit'
										className='z-0'
										btnStyle='primary'
										onClick={() => {
											setIsContinueClicked(true);
											isActiveNewFlow && sendNewOtpFlowGAEventForContinueButton(activeStep, formData, newUser);
											if (isDeferredFlowRef.current) {
												if (activeStep === 1 && formData.phoneNumber.value)
													nbGaEvent('user_otp_number', 'phone_field_filled_defer');
												if (activeStep === 2) {
													if (formData.name.value) nbGaEvent('user_otp_number', 'name_field_filled_defer');
													if (formData.email.value) nbGaEvent('user_otp_number', 'email_field_filled_defer');
												}
												if (activeStep === 3)
													nbGaEvent('user_otp_number', 'otp1_continue_defer');
											}
										}}
									>
										{pageSpecificData.STEP1_SUBMIT_BUTTON_TEXT}
									</NbButton>
								</div>
							</form>
							<div className='login-signup-modal-footer'>
								{'By continuing, you agree to our '}
								<span
									onClick={() => {
										window.open('/terms-and-condition');
									}}
									className='cursor-pointer'
								>
									{'Terms & Conditions'}
								</span>
								{(activeStep === 3 ||
									type === 'MapPropertyDetail' ||
									type === 'premiumFiltersMap' ||
									type === 'filterApply' ||
									type === 'MapPropertyDetailMob' ||
									type === 'filterApplyMob' ||
									type === 'shortlistMap' ||
									type === 'shortlistMapMob' ||
									type === 'polygonClick') && (
										<div>
											For any issue/query please email
											<>{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}</>
											<label className='ml-0.3p mail-label-block'>[email protected]</label>
										</div>
									)}
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
};

export default SignUpModal;
Editor is loading...
Leave a Comment