All files / src/components/auth PhoneOtpForm.tsx

96.75% Statements 179/185
92.7% Branches 89/96
96.29% Functions 26/27
97.22% Lines 175/180

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445                    1x 1x 1x     412x 412x 412x 412x 412x 412x 412x 412x   412x 412x   412x 95x 95x 42x   95x 420x 420x 7x 7x   7x 7x   413x         412x 49x 49x       412x 61x 61x 46x 46x 46x             412x 61x 61x 53x         412x 131x     412x 57x 57x 2x 2x   55x 55x 55x 1x 1x           54x     412x 57x 57x   54x 54x 54x 54x 54x     54x 49x 49x 2x 2x 2x         52x 5x 5x 1x 1x 1x       51x         49x 2x 2x 2x     47x 47x   47x 45x       2x 2x   54x       412x   16x 16x 16x 16x 16x 16x   16x           12x 3x 3x 3x       9x 2x 2x           9x   4x 4x     4x   16x           412x     97x 97x 97x 97x 97x   97x 82x       97x 14x 14x 14x             412x   3x 2x   1x 1x 1x 1x                 412x   5x 5x 5x   4x 4x 18x   4x 4x     4x 5x     5x 2x           412x 2x 2x 2x 2x 2x   2x 2x     412x 6x 6x 6x 6x 6x 6x 6x   6x       4x 2x 2x 2x     2x 2x 2x         2x 2x   6x       412x         412x 181x                                                       1086x       2172x           97x 3x                                                         231x                                 2x                                         56x 56x     1x 1x                                            
import { useState, useRef, useCallback, useEffect } from "react";
import { parsePhoneNumber, isValidPhoneNumber } from "libphonenumber-js";
import { authClient } from "../../lib/auth-client";
import { authApi } from "../../lib/api";
 
interface PhoneOtpFormProps {
	onSuccess: () => void;
	mode?: "sign-in" | "sign-up";
}
 
const RESEND_COUNTDOWN_SECONDS = 60;
const OTP_LENGTH = 6;
const COUNTDOWN_STORAGE_KEY = "otp_countdown_end";
 
export function PhoneOtpForm({ onSuccess, mode = "sign-in" }: PhoneOtpFormProps) {
	const [step, setStep] = useState<"phone" | "otp">("phone");
	const [fullName, setFullName] = useState("");
	const [phoneNumber, setPhoneNumber] = useState("");
	const [countryCode] = useState("+91");
	const [otp, setOtp] = useState<string[]>(() => Array(OTP_LENGTH).fill(""));
	const [isLoading, setIsLoading] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [resendCountdown, setResendCountdown] = useState(0);
 
	const otpInputRefs = useRef<(HTMLInputElement | null)[]>([]);
	const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
 
	const startCountdownTimer = useCallback((seconds: number) => {
		setResendCountdown(seconds);
		if (countdownRef.current) {
			clearInterval(countdownRef.current);
		}
		countdownRef.current = setInterval(() => {
			setResendCountdown((prev) => {
				if (prev <= 1) {
					Eif (countdownRef.current) {
						clearInterval(countdownRef.current);
					}
					sessionStorage.removeItem(COUNTDOWN_STORAGE_KEY);
					return 0;
				}
				return prev - 1;
			});
		}, 1000);
	}, []);
 
	const startResendCountdown = useCallback((seconds: number = RESEND_COUNTDOWN_SECONDS) => {
		sessionStorage.setItem(COUNTDOWN_STORAGE_KEY, String(Date.now() + seconds * 1000));
		startCountdownTimer(seconds);
	}, [startCountdownTimer]);
 
	// On mount, restore any active countdown from sessionStorage
	useEffect(() => {
		const endTime = sessionStorage.getItem(COUNTDOWN_STORAGE_KEY);
		if (endTime) {
			const remaining = Math.ceil((parseInt(endTime, 10) - Date.now()) / 1000);
			if (remaining > 0) {
				startCountdownTimer(remaining);
			} else E{
				sessionStorage.removeItem(COUNTDOWN_STORAGE_KEY);
			}
		}
	}, [startCountdownTimer]);
 
	useEffect(() => {
		return () => {
			if (countdownRef.current) {
				clearInterval(countdownRef.current);
			}
		};
	}, []);
 
	const getFullPhoneNumber = useCallback(() => {
		return `${countryCode}${phoneNumber}`;
	}, [countryCode, phoneNumber]);
 
	const validatePhone = useCallback(() => {
		const trimmed = phoneNumber.trim();
		if (!trimmed) {
			setError("Please enter your phone number");
			return false;
		}
		const full = getFullPhoneNumber();
		try {
			if (!isValidPhoneNumber(full)) {
				setError("Please enter a valid phone number");
				return false;
			}
		} catch {
			setError("Please enter a valid phone number");
			return false;
		}
		return true;
	}, [phoneNumber, getFullPhoneNumber]);
 
	const handleSendOtp = useCallback(async () => {
		setError(null);
		if (!validatePhone()) return;
 
		setIsLoading(true);
		try {
			const fullPhone = getFullPhoneNumber();
			const parsed = parsePhoneNumber(fullPhone);
			const e164 = parsed.format("E.164");
 
			// For sign-in: check if phone is registered before sending OTP
			if (mode === "sign-in") {
				const { exists } = await authApi.checkPhone(e164);
				if (!exists) {
					setError("No account found with this phone number. Please sign up first.");
					setIsLoading(false);
					return;
				}
			}
 
			// For sign-up: check if phone is already registered before sending OTP
			if (mode === "sign-up") {
				const { exists } = await authApi.checkPhone(e164);
				if (exists) {
					setError("This phone number is already registered. Please sign in instead.");
					setIsLoading(false);
					return;
				}
			}
 
			const sendResult = await authClient.phoneNumber.sendOtp({
				phoneNumber: e164,
			});
 
			// Check for error response from better-auth
			if (sendResult?.error) {
				setError(sendResult.error.message || "Failed to send OTP. Please try again.");
				setIsLoading(false);
				return;
			}
 
			setStep("otp");
			startResendCountdown();
			// Focus first OTP box after transition
			setTimeout(() => {
				otpInputRefs.current[0]?.focus();
			}, 50);
		} catch (err: unknown) {
			const message =
				err instanceof Error ? err.message : "Failed to send OTP. Please try again.";
			setError(message);
		} finally {
			setIsLoading(false);
		}
	}, [validatePhone, getFullPhoneNumber, startResendCountdown, mode]);
 
	const handleVerifyOtp = useCallback(
		async (otpValue: string) => {
			setError(null);
			setIsLoading(true);
			try {
				const fullPhone = getFullPhoneNumber();
				const parsed = parsePhoneNumber(fullPhone);
				const e164 = parsed.format("E.164");
 
				const result = await authClient.phoneNumber.verify({
					phoneNumber: e164,
					code: otpValue,
				});
 
				// better-auth client returns { data, error } — check for error
				if (result?.error) {
					setError(result.error.message || "Invalid OTP. Please try again.");
					setIsLoading(false);
					return;
				}
 
				// If signing up with a name, update the user profile
				if (mode === "sign-up" && fullName.trim()) {
					try {
						await authApi.updateProfile({ name: fullName.trim() });
					} catch {
						// Non-fatal — name can be updated later
					}
				}
 
				onSuccess();
			} catch (err: unknown) {
				const rawMsg = err instanceof Error ? err.message : "Invalid OTP. Please try again.";
				const message = rawMsg.toLowerCase().includes("unique") || rawMsg.toLowerCase().includes("already")
					? "This phone number is already registered. Please sign in instead."
					: rawMsg;
				setError(message);
			} finally {
				setIsLoading(false);
			}
		},
		[getFullPhoneNumber, onSuccess, mode, fullName],
	);
 
	const handleOtpChange = useCallback(
		(index: number, value: string) => {
			// Only allow single digit
			const digit = value.replace(/\D/g, "").slice(-1);
			const newOtp = [...otp];
			newOtp[index] = digit;
			setOtp(newOtp);
			setError(null);
 
			if (digit && index < OTP_LENGTH - 1) {
				otpInputRefs.current[index + 1]?.focus();
			}
 
			// Auto-submit when last digit is filled
			if (digit && index === OTP_LENGTH - 1) {
				const filledOtp = newOtp.join("");
				Eif (filledOtp.length === OTP_LENGTH) {
					handleVerifyOtp(filledOtp);
				}
			}
		},
		[otp, handleVerifyOtp],
	);
 
	const handleOtpKeyDown = useCallback(
		(index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
			if (e.key === "Backspace") {
				if (otp[index]) {
					// Clear current box
					const newOtp = [...otp];
					newOtp[index] = "";
					setOtp(newOtp);
				I} else if (index > 0) {
					// Move to previous box
					otpInputRefs.current[index - 1]?.focus();
				}
			}
		},
		[otp],
	);
 
	const handleOtpPaste = useCallback(
		(e: React.ClipboardEvent<HTMLInputElement>) => {
			e.preventDefault();
			const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, OTP_LENGTH);
			if (!pasted) return;
 
			const newOtp = Array(OTP_LENGTH).fill("");
			for (let i = 0; i < pasted.length; i++) {
				newOtp[i] = pasted[i];
			}
			setOtp(newOtp);
			setError(null);
 
			// Focus the next empty box or the last filled box
			const nextEmpty = pasted.length < OTP_LENGTH ? pasted.length : OTP_LENGTH - 1;
			otpInputRefs.current[nextEmpty]?.focus();
 
			// Auto-submit if all 6 digits pasted
			if (pasted.length === OTP_LENGTH) {
				handleVerifyOtp(pasted);
			}
		},
		[handleVerifyOtp],
	);
 
	const handleChangePhone = useCallback(() => {
		setStep("phone");
		setOtp(Array(OTP_LENGTH).fill(""));
		setError(null);
		Eif (countdownRef.current) {
			clearInterval(countdownRef.current);
		}
		setResendCountdown(0);
		sessionStorage.removeItem(COUNTDOWN_STORAGE_KEY);
	}, []);
 
	const handleResend = useCallback(async () => {
		Iif (resendCountdown > 0) return;
		setError(null);
		setIsLoading(true);
		try {
			const fullPhone = getFullPhoneNumber();
			const parsed = parsePhoneNumber(fullPhone);
			const e164 = parsed.format("E.164");
 
			const resendResult = await authClient.phoneNumber.sendOtp({
				phoneNumber: e164,
			});
 
			if (resendResult?.error) {
				setError(resendResult.error.message || "Failed to resend OTP. Please try again.");
				setIsLoading(false);
				return;
			}
 
			setOtp(Array(OTP_LENGTH).fill(""));
			startResendCountdown();
			setTimeout(() => {
				otpInputRefs.current[0]?.focus();
			}, 50);
		} catch (err: unknown) {
			const message =
				err instanceof Error ? err.message : "Failed to resend OTP. Please try again.";
			setError(message);
		} finally {
			setIsLoading(false);
		}
	}, [resendCountdown, getFullPhoneNumber, startResendCountdown]);
 
	const formattedPhone = phoneNumber
		? `${countryCode} ${phoneNumber}`
		: "";
 
 
	if (step === "otp") {
		return (
			<div className="space-y-4">
				<div>
					<p className="text-sm text-muted-foreground">
						Enter the 6-digit code sent to your WhatsApp{" "}
						<span className="font-medium text-foreground">{formattedPhone}</span>
					</p>
					<button
						type="button"
						onClick={handleChangePhone}
						className="text-xs text-primary underline mt-1 hover:no-underline"
					>
						Change phone number
					</button>
				</div>
 
				{error && (
					<p role="alert" className="text-sm text-destructive">
						{error}
					</p>
				)}
 
				<div>
					<label htmlFor="otp-0" className="block text-sm font-medium text-foreground mb-2">
						Verification code
					</label>
					<fieldset className="flex gap-2 border-0 p-0 m-0" aria-label="OTP input">
						{otp.map((digit, index) => (
							<input
								// biome-ignore lint/suspicious/noArrayIndexKey: OTP boxes are positional
								key={index}
								ref={(el) => {
									otpInputRefs.current[index] = el;
								}}
								type="text"
								inputMode="numeric"
								maxLength={1}
								value={digit}
								onChange={(e) => handleOtpChange(index, e.target.value)}
								onKeyDown={(e) => handleOtpKeyDown(index, e)}
								onPaste={handleOtpPaste}
								id={`otp-${index}`}
								aria-label={`OTP digit ${index + 1}`}
								className="w-10 h-12 text-center text-lg font-medium border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50"
								disabled={isLoading}
							/>
						))}
					</fieldset>
				</div>
 
				<div className="text-xs text-muted-foreground">
					{resendCountdown > 0 ? (
						<span>Resend WhatsApp OTP in {resendCountdown}s</span>
					) : (
						<button
							type="button"
							onClick={handleResend}
							disabled={isLoading}
							className="text-primary underline hover:no-underline disabled:opacity-50"
						>
							Resend WhatsApp OTP
						</button>
					)}
				</div>
			</div>
		);
	}
 
	return (
		<div className="space-y-4">
			{error && (
				<p role="alert" className="text-sm text-destructive">
					{error}
				</p>
			)}
 
			{mode === "sign-up" && (
				<div>
					<label htmlFor="phone-full-name" className="block text-sm font-medium text-foreground mb-1">
						Full Name
					</label>
					<input
						id="phone-full-name"
						type="text"
						value={fullName}
						onChange={(e) => setFullName(e.target.value)}
						placeholder="Your full name"
						disabled={isLoading}
						className="w-full h-10 px-3 border border-input rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50"
					/>
				</div>
			)}
 
			<div>
				<label htmlFor="phone-number" className="block text-sm font-medium text-foreground mb-1">
					Phone number
				</label>
				<div className="flex gap-2">
					<div className="flex items-center px-3 border border-input rounded-md bg-muted text-foreground text-sm h-10 min-w-[72px]">
						<span>🇮🇳 {countryCode}</span>
					</div>
					<input
						id="phone-number"
						type="tel"
						value={phoneNumber}
						onChange={(e) => {
							setPhoneNumber(e.target.value.replace(/\D/g, ""));
							setError(null);
						}}
						onKeyDown={(e) => {
							Eif (e.key === "Enter") {
								handleSendOtp();
							}
						}}
						placeholder="98765 43210"
						disabled={isLoading}
						className="flex-1 h-10 px-3 border border-input rounded-md bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50"
						aria-label="Phone number"
					/>
				</div>
			</div>
 
			<button
				type="button"
				onClick={handleSendOtp}
				disabled={isLoading}
				className="w-full h-10 px-4 bg-primary text-primary-foreground text-sm font-medium rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
			>
				{isLoading ? "Sending..." : "Send WhatsApp OTP"}
			</button>
		</div>
	);
}