"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.
Already registered? Sign in
);
}
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.
Mobile number
{p.phone && !p.phoneOk &&
Enter a valid {p.country.digits}-digit number. }
{p.sso ? (
Signed up with {cap(p.sso.provider)} — no password needed.
) : (
)}
Your role
p.setRelationship(e.target.value)}>
{relationshipOptions.map((r) => {r} )}
{p.isSelf ? (
Homeowner account — you own this property.
) : (
Registering on behalf of the property owner.
)}
p.setTermsOk(e.target.checked)} />
I agree to the setModal("terms")}>Terms of Use {!reviewed.terms && — open & scroll to enable }
p.setPrivacyOk(e.target.checked)} />
I agree to the setModal("privacy")}>Privacy Policy {!reviewed.privacy && — open & scroll to enable }
{!p.valid &&
Fill all required fields and accept both documents to continue.
}
Create Account & Verify
{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.
setMode("have")}>I have a job ID
setMode("forgot")}>Find by address
{mode === "have" ? (
Property / Job ID
p.setAllotment(e.target.value.toUpperCase())} placeholder="LUP-123456" />
Format: LUP- followed by 6 digits.
) : (
City / ZIP setCity(e.target.value)} placeholder="City or ZIP code" />
{!p.plotVerified ? (
{busy ? "Searching…" : "Find my property"}
) : (
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.
}
Continue
);
}
/* ====================== 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)} />
Continue
);
}
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" />
) : (
)}
setVia("primary")}>{primaryLabel}
setVia("wa")}> WhatsApp
{state === "sending" ? "Sending…" : "Send code"}
{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.
setSameAs(e.target.checked)} />
My mailing address is the same as my registered address
{!sameAs && (
<>
>
)}
Your property address is on record; the mailing address is where we send physical mail.
Finish & Enter Portal
);
}
const ADDR_FLAGS: Record = { US: "🇺🇸", IN: "🇮🇳", GB: "🇬🇧", AE: "🇦🇪" };
function AddrSectionHead({ icon, title, sub, tone }: { icon: string; title: string; sub: string; tone: "amber" | "blue" }) {
return (
);
}
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 (
Country / Region
{ADDR_FLAGS[country.code] ?? "🌐"}
{ const c = addressCountries.find((x) => x.code === e.target.value)!; setCountry(c); setSuggestions([]); setCity(""); setStateName(""); setLocalities([]); }}>
{addressCountries.map((c) => {c.name} )}
{country.lookup === "pincode" ? (
<>
{(city || stateName) &&
Location detected · {city}{stateName ? `, ${stateName}` : ""}
}
State
setStateName(e.target.value)}>
Select {country.states.map((s) => {s} )}
{localities.length > 0 && (
Area / Locality
{ setLocality(e.target.value); setLine2(e.target.value); }}>
Select locality {localities.map((l) => {l} )}
)}
>
) : (
<>
Address Line 1 — House No./Street
onSearch(e.target.value)} placeholder="Start typing your address…" />
{suggestions.length > 0 && (
{suggestions.map((s, i) => (
applySuggestion(s)}>
{s.line1} {s.city}{s.state ? `, ${s.state}` : ""} · {s.postal}
))}
)}
{(city || stateName) &&
Selected · {city}{stateName ? `, ${stateName}` : ""}
}
Address Line 2 setLine2(e.target.value)} />
{country.states.length > 0 && (
State / Region
setStateName(e.target.value)}>Select {country.states.map((s) => {s} )}
)}
>
)}
);
}
/* ====================== 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`;
}