"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Button, Container } from "@/components/ui"; import { getStoredToken, loginWithRedirect } from "@/lib/auth"; import { identityApi } from "@/lib/identity"; import { isValidMobile, normalizeOtpCode, normalizePhone, persianToEnglish, } from "@/lib/phone"; export default function VerifyMobilePage() { const router = useRouter(); const [mobile, setMobile] = useState(""); const [code, setCode] = useState(""); const [countdown, setCountdown] = useState(0); const [step, setStep] = useState<"mobile" | "code">("mobile"); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const verifyingRef = useRef(false); useEffect(() => { if (!getStoredToken()) { void loginWithRedirect(); } }, []); useEffect(() => { if (countdown <= 0) return; const timer = setTimeout(() => setCountdown((c) => c - 1), 1000); return () => clearTimeout(timer); }, [countdown]); const handleRequestOtp = async () => { const token = getStoredToken(); if (!token) return; setError(""); const normalized = normalizePhone(mobile); if (!isValidMobile(normalized)) { setError("شماره موبایل صحیح نیست"); return; } setMobile(normalized); setLoading(true); try { const res = await identityApi.requestMobileVerify(normalized, token); setCountdown(res.expires_in); setStep("code"); } catch (e) { setError(e instanceof Error ? e.message : "ارسال کد ناموفق بود"); } finally { setLoading(false); } }; const handleVerify = useCallback(async () => { const token = getStoredToken(); if (!token || verifyingRef.current) return; const normalizedCode = normalizeOtpCode(code); if (normalizedCode.length !== 4) { setError("کد تأیید باید ۴ رقم باشد"); return; } verifyingRef.current = true; setLoading(true); let keepLoading = false; try { await identityApi.verifyMobile(mobile, normalizedCode, token); keepLoading = true; router.replace("/dashboard"); } catch (e) { setError(e instanceof Error ? e.message : "تأیید ناموفق بود"); } finally { if (!keepLoading) { setLoading(false); verifyingRef.current = false; } } }, [code, mobile, router]); return (

تأیید شماره موبایل

برای استفاده از سامانه یکپارچه، تأیید شماره موبایل الزامی است.

{error && (

{error}

)} {step === "mobile" ? (
setMobile(persianToEnglish(e.target.value))} className="w-full rounded-xl border border-gray-200 px-4 py-2.5" />
) : (
setCode(normalizeOtpCode(e.target.value))} className="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-center font-mono tracking-widest" />
)}
); }