"use client"; import { useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Icon, Avatar } from "./icons"; import { StepBack, FlashNote, Badge, OtpBoxes, ResendLink, RememberDevice, SocialButtons, startSocial, PasswordStrength, LegalModal, } from "./bits"; import { countryCodes, relationshipOptions, addressCountries, TERMS, PRIVACY, passwordStrength, type AddrCountry, } from "./data"; const STEPS = ["Account", "Property", "Verify", "Address"]; const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; export function RegisterFlow() { const router = useRouter(); const [step, setStep] = useState(0); // shared form state const [sso, setSso] = useState<{ provider: string; email: string } | null>(null); const [email, setEmail] = useState(""); const [first, setFirst] = useState(""); const [last, setLast] = useState(""); const [cc, setCc] = useState("+1"); const [phone, setPhone] = useState(""); const [pw, setPw] = useState(""); const [relationship, setRelationship] = useState("Homeowner"); const [alloeNo, setAlloeNo] = useState(""); const [alloeFirst, setAlloeFirst] = useState(""); const [alloeLast, setAlloeLast] = useState(""); const [termsOk, setTermsOk] = useState(false); const [privacyOk, setPrivacyOk] = useState(false); // step 1 const [allotment, setAllotment] = useState(""); const [plotVerified, setPlotVerified] = useState(false); // step 2 const [emailVerified, setEmailVerified] = useState(false); const [phoneVerified, setPhoneVerified] = useState(false); const isSelf = relationship === "Homeowner"; const country = countryCodes.find((c) => c.code === cc)!; const phoneOk = phone.replace(/\D/g, "").length === country.digits; const pwOk = sso ? true : passwordStrength(pw).score >= 3; const alloeIdOk = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/.test(alloeNo); const step0Valid = first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk && termsOk && privacyOk && (isSelf || (alloeIdOk && alloeFirst.trim() && alloeLast.trim())); const step1Valid = /^LUP-\d{6}$/.test(allotment) || plotVerified; const step2Valid = emailVerified && phoneVerified; function finish() { const profile = { name: `${first} ${last}`.trim(), initials: `${first[0] ?? ""}${last[0] ?? ""}`.toUpperCase(), email: sso?.email || email, isAllottee: isSelf, allotteeNames: isSelf ? null : `${alloeFirst} ${alloeLast}`.trim(), }; try { localStorage.setItem("lup_profile", JSON.stringify(profile)); } catch { /* ignore */ } router.push("/dashboard"); } return (
{step === 0 && ( setStep(1)} toLogin={() => router.push("/portal/login")} /> )} {step === 1 && ( setStep(0)} onContinue={() => setStep(2)} /> )} {step === 2 && ( setStep(1)} onContinue={() => setStep(3)} /> )} {step === 3 && ( setStep(2)} onFinish={finish} /> )}
); } /* ====================== STEP 0 — ACCOUNT ====================== */ function StepAccount(p: { sso: { provider: string; email: string } | null; setSso: (v: { provider: string; email: string } | null) => void; email: string; setEmail: (v: string) => void; first: string; setFirst: (v: string) => void; last: string; setLast: (v: string) => void; cc: string; setCc: (v: string) => void; phone: string; setPhone: (v: string) => void; phoneOk: boolean; country: typeof countryCodes[number]; pw: string; setPw: (v: string) => void; relationship: string; setRelationship: (v: string) => void; isSelf: boolean; alloeNo: string; setAlloeNo: (v: string) => void; alloeIdOk: boolean; alloeFirst: string; setAlloeFirst: (v: string) => void; alloeLast: string; setAlloeLast: (v: string) => void; termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void; valid: boolean; onContinue: () => void; toLogin: () => void; }) { const [phase, setPhase] = useState<"sso" | "profile">("sso"); const [modal, setModal] = useState(null); function pickSso(provider: "google" | "microsoft" | "apple") { if (startSocial(provider)) return; const mockEmail = `you@${provider === "microsoft" ? "outlook.com" : provider + ".com"}`; p.setSso({ provider, email: mockEmail }); p.setEmail(mockEmail); setPhase("profile"); } if (phase === "sso") { const valid = EMAIL_RE.test(p.email); return (

Create your account

Sign up with a provider or your email to get started.

or continue with email
{ e.preventDefault(); if (valid) { p.setSso(null); setPhase("profile"); } }}>
p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus />

Already registered?

); } return (

Complete your profile

Tell us a bit about you to set up your account.

{p.sso ? (
Connected with {cap(p.sso.provider)} · {p.sso.email}
) : (
Creating account for {p.email}
)}
Profile photo Optional now — becomes mandatory later at KYC.
p.setFirst(e.target.value)} placeholder="First name" />
p.setLast(e.target.value)} placeholder="Last name" />
{/* eslint-disable-next-line @next/next/no-img-element */} {p.country.name}
p.setPhone(e.target.value.replace(/\D/g, ""))} placeholder={p.country.example} />
{p.phone && !p.phoneOk && Enter a valid {p.country.digits}-digit number.}
{p.sso ? (
Signed up with {cap(p.sso.provider)} — no password needed.
) : (
p.setPw(e.target.value)} placeholder="Create a strong password" />
)}
{p.isSelf ? (
Homeowner account — you own this property.
) : (
Registering on behalf of the property owner.
Property Owner Details {p.alloeNo && (p.alloeIdOk ? Valid : Checking…)}
p.setAlloeNo(e.target.value.toUpperCase())} placeholder="Alphanumeric ID" />
p.setAlloeFirst(e.target.value)} />
p.setAlloeLast(e.target.value)} />
)}
{!p.valid &&

Fill all required fields and accept both documents to continue.

} {modal === "terms" && setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />} {modal === "privacy" && setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />}
); } // module-level reviewed flags (per mount lifetime) — enables the checkboxes after a doc is read const reviewed = { terms: false, privacy: false }; /* ====================== STEP 1 — ALLOTMENT ====================== */ function StepAllotment(p: { allotment: string; setAllotment: (v: string) => void; plotVerified: boolean; setPlotVerified: (v: boolean) => void; valid: boolean; onBack: () => void; onContinue: () => void; }) { const [mode, setMode] = useState<"have" | "forgot">("have"); const [houseNo, setHouseNo] = useState(""); const [street, setStreet] = useState(""); const [city, setCity] = useState(""); const [busy, setBusy] = useState(false); const fmtOk = /^LUP-\d{6}$/.test(p.allotment); function findPlot() { if (!houseNo || !street || !city) return; setBusy(true); setTimeout(() => { setBusy(false); p.setPlotVerified(true); }, 800); } return (

Identify the property

Find the property by its job ID, or look it up by address.

{mode === "have" ? (
p.setAllotment(e.target.value.toUpperCase())} placeholder="LUP-123456" /> Format: LUP- followed by 6 digits.
) : (
setHouseNo(e.target.value)} placeholder="123" />
setStreet(e.target.value)} placeholder="Street name" />
setCity(e.target.value)} placeholder="City or ZIP code" />
{!p.plotVerified ? ( ) : (
LUP-****** · Verified · {houseNo} {street}, {city}
)}

Sensitive details stay masked until verified (verify-to-reveal).

)} {mode === "have" && p.allotment && !fmtOk &&

Enter a valid ID like LUP-123456.

}
); } /* ====================== STEP 2 — VERIFY ====================== */ function StepVerify(p: { emailValue: string; cc: string; phone: string; country: typeof countryCodes[number]; emailVerified: boolean; setEmailVerified: (v: boolean) => void; phoneVerified: boolean; setPhoneVerified: (v: boolean) => void; valid: boolean; onBack: () => void; onContinue: () => void; }) { const [remember, setRemember] = useState(false); return (

Verify email & phone

Confirm both so we can secure your account.

p.setEmailVerified(true)} /> p.setPhoneVerified(true)} />
); } type SendState = "idle" | "sending" | "ok" | "invalid_email" | "mailbox_full" | "bounce_risk" | "invalid_mobile"; function VerifyChannel({ kind, initial, country, cc, initialPhone, verified, onVerified }: { kind: "email" | "phone"; initial: string; country: typeof countryCodes[number]; cc: string; initialPhone: string; verified: boolean; onVerified: () => void; }) { const [value, setValue] = useState(kind === "email" ? initial : initialPhone); const [via, setVia] = useState<"primary" | "wa">("primary"); const [state, setState] = useState("idle"); const [otpError, setOtpError] = useState(false); const primaryLabel = kind === "email" ? "Email" : "SMS"; function send() { setState("sending"); setTimeout(() => { if (kind === "email") { if (!EMAIL_RE.test(value)) return setState("invalid_email"); if (value.includes("full")) return setState("mailbox_full"); if (value.includes("bo")) return setState("bounce_risk"); return setState("ok"); } else { if (value.replace(/\D/g, "").length !== country.digits) return setState("invalid_mobile"); return setState("ok"); } }, 700); } if (verified) { return (
{kind === "email" ? "Email" : "Mobile"} Verified

{kind === "email" ? value : `${cc} ${value}`}

); } return (
{kind === "email" ? "Email address" : "Mobile number"}
{kind === "email" ? ( { setValue(e.target.value); setState("idle"); }} placeholder="you@example.com" /> ) : (
{/* eslint-disable-next-line @next/next/no-img-element */} {country.name} {cc} { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
)}
{state === "ok" &&

OTP sent via {via === "wa" ? "WhatsApp" : primaryLabel}.

} {state === "invalid_email" &&
That email address looks invalid.
} {state === "mailbox_full" &&
This mailbox appears full — try another email.
} {state === "bounce_risk" &&
High bounce risk for this address.
} {state === "invalid_mobile" &&
Enter a valid {country.digits}-digit mobile number.
} {state === "ok" && (
{ if (c === "000000") setOtpError(true); else { setOtpError(false); onVerified(); } }} error={otpError} /> {otpError &&
Incorrect code.
}
)}

Demo: any 6 digits verify; “000000” fails. Email with “full”/“bo” shows send errors.

); } /* ====================== STEP 3 — ADDRESS ====================== */ function StepAddress({ onBack, onFinish }: { onBack: () => void; onFinish: () => void }) { const [sameAs, setSameAs] = useState(true); return (

Your addresses

Add your registered address and where we should send mail.

{!sameAs && ( <> )}
Your property address is on record; the mailing address is where we send physical mail.
); } const ADDR_FLAGS: Record = { US: "🇺🇸", IN: "🇮🇳", GB: "🇬🇧", AE: "🇦🇪" }; function AddrSectionHead({ icon, title, sub, tone }: { icon: string; title: string; sub: string; tone: "amber" | "blue" }) { return (
{title} {sub}
); } function AddressBlock({ idPrefix }: { idPrefix: string }) { const [country, setCountry] = useState(addressCountries[0]); const [pin, setPin] = useState(""); const [city, setCity] = useState(""); const [stateName, setStateName] = useState(""); const [localities, setLocalities] = useState([]); const [locality, setLocality] = useState(""); const [line1, setLine1] = useState(""); const [line2, setLine2] = useState(""); const [postal, setPostal] = useState(""); const [suggestions, setSuggestions] = useState<{ line1: string; line2: string; city: string; state: string; postal: string }[]>([]); const debounce = useRef | null>(null); // India: PIN auto-fill useEffect(() => { if (country.lookup !== "pincode" || pin.length !== 6) return; let alive = true; fetch(`/api/geo?pin=${pin}`).then((r) => r.json()).then((d) => { if (!alive || !d.ok) return; setCity(d.city); setStateName(d.state); setLocalities(d.localities ?? []); }).catch(() => {}); return () => { alive = false; }; }, [pin, country]); // Non-India: address search function onSearch(v: string) { setLine1(v); if (country.lookup !== "search") return; if (debounce.current) clearTimeout(debounce.current); if (v.trim().length < 3) { setSuggestions([]); return; } debounce.current = setTimeout(() => { fetch(`/api/geo?addr=${encodeURIComponent(v)}&country=${country.code.toLowerCase()}`).then((r) => r.json()).then((d) => { if (d.ok) setSuggestions(d.suggestions ?? []); }).catch(() => {}); }, 400); } function applySuggestion(s: { line1: string; line2: string; city: string; state: string; postal: string }) { setLine1(s.line1); setLine2(s.line2); setCity(s.city); setStateName(s.state); setPostal(s.postal); setSuggestions([]); } return (
{ADDR_FLAGS[country.code] ?? "🌐"}
{country.lookup === "pincode" ? ( <>
setPin(e.target.value.replace(/\D/g, ""))} placeholder="6-digit PIN" />
City & state auto-fill from your PIN.
{(city || stateName) &&
Location detected · {city}{stateName ? `, ${stateName}` : ""}
}
setCity(e.target.value)} />
{localities.length > 0 && (
)}
setLine1(e.target.value)} placeholder="House / Flat / Building" />
) : ( <>
onSearch(e.target.value)} placeholder="Start typing your address…" />
{suggestions.length > 0 && (
{suggestions.map((s, i) => ( ))}
)}
{(city || stateName) &&
Selected · {city}{stateName ? `, ${stateName}` : ""}
}
setLine2(e.target.value)} />
setCity(e.target.value)} />
{country.states.length > 0 && (
)}
setPostal(e.target.value)} maxLength={country.postalLen} placeholder={country.postalLabel} />
)}
); } /* ====================== stepper ====================== */ function Stepper({ current }: { current: number }) { return (
{STEPS.map((label, i) => { const done = i < current, on = i === current; return (
{done ? : i + 1} {label}
{i < STEPS.length - 1 && }
); })}
); } function cap(s: string) { return s.charAt(0).toUpperCase() + s.slice(1); } // Flag emojis don't render on Windows, so map the emoji's regional-indicator // code points to an ISO-2 code and use a flag image instead. function flagUrl(flag: string): string { const iso = Array.from(flag) .map((ch) => ch.codePointAt(0)) .filter((cp): cp is number => cp != null && cp >= 0x1f1e6 && cp <= 0x1f1ff) .map((cp) => String.fromCharCode(cp - 0x1f1e6 + 97)) .join(""); return `https://flagcdn.com/w40/${iso}.png`; }