"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, PasswordStrength, LegalModal, } from "./bits"; import { countryCodes, relationshipOptions, addressCountries, TERMS, PRIVACY, passwordStrength, type AddrCountry, } from "./data"; import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react"; import { isShellConfigured } from "@/lib/appshell"; type Addr = { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; locality?: string }; const STEPS = ["Account", "Verify", "Address"]; const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboard" }) { // "onboard" = an already-authenticated OAuth (Google) user completing their CRM // profile: email is skipped (Google-verified), the auth account already exists so // we only SET a password + persist the profile, and the OTP-verify step is skipped. const onboard = mode === "onboard"; const router = useRouter(); const { register, setPassword, getUserEmail } = useAuth(); const { sdk } = useAppShell(); const [step, setStep] = useState(0); const [submitErr, setSubmitErr] = useState(""); // address (lifted from StepAddress/AddressBlock so finish() can persist it) const [regAddr, setRegAddr] = useState({}); const [mailAddr, setMailAddr] = useState({}); const [mailingSame, setMailingSame] = useState(true); // 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("Customer"); const [alloeNo, setAlloeNo] = useState(""); const [alloeFirst, setAlloeFirst] = useState(""); const [alloeLast, setAlloeLast] = useState(""); const [termsOk, setTermsOk] = useState(false); const [privacyOk, setPrivacyOk] = useState(false); // verify step const [emailVerified, setEmailVerified] = useState(false); const [phoneVerified, setPhoneVerified] = useState(false); // Onboarding: prefill the verified email from the Google session (the ACE omits it). useEffect(() => { if (!onboard) return; getUserEmail().then((e) => { if (e) setEmail(e); }).catch(() => { /* ignore */ }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [onboard]); const STEP_LABELS = onboard ? ["Profile", "Address"] : STEPS; const isSelf = relationship === "Customer" || relationship === "Owner"; const isEmployee = relationship === "Employee"; 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).{4,}$/.test(alloeNo); const step0Valid = first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk && termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim())))); const step2Valid = emailVerified && phoneVerified; async function finish() { const finalEmail = sso?.email || email; const profile = { name: `${first} ${last}`.trim(), initials: `${first[0] ?? ""}${last[0] ?? ""}`.toUpperCase(), email: finalEmail, isAllottee: isSelf, allotteeNames: isSelf ? null : `${alloeFirst} ${alloeLast}`.trim(), }; try { localStorage.setItem("lup_profile", JSON.stringify(profile)); } catch { /* ignore */ } if (isShellConfigured()) { setSubmitErr(""); // 1) Auth account. Onboarding users are already authenticated via Google — set // a password so email+password login works too. Everyone else registers now. if (onboard) { try { if (pw) await setPassword(pw); } catch { /* non-fatal — the profile still saves */ } } else if (!sso) { try { await register(finalEmail, pw); } catch { setSubmitErr("We couldn't create that account. The email may already be registered."); return; } } // 2) Persist the full CRM registration payload to be-crm (name, phone, persona, // allottee, both addresses, consent). Non-fatal: the auth account exists either way. try { const mailing = mailingSame ? regAddr : mailAddr; await sdk.command("crm.account.register", { email: finalEmail, firstName: first, lastName: last, phoneCc: cc, phoneNumber: phone.replace(/\D/g, ""), persona: relationship, isAllottee: isSelf, ...(isSelf ? {} : { allotteeId: alloeNo, allotteeFirstName: alloeFirst, allotteeLastName: alloeLast }), registeredAddress: regAddr, mailingAddress: mailing, mailingSameAsRegistered: mailingSame, consentTerms: termsOk, consentPrivacy: privacyOk, }); } catch { if (onboard) { setSubmitErr("Couldn't save your profile. Please try again."); return; } // register mode: non-fatal — the auth account exists; the profile can be filled in later. } } router.push("/dashboard"); } return (
{step === 0 && ( setStep(1)} toLogin={() => router.push("/portal/login")} /> )} {step === 1 && !onboard && ( setStep(0)} onContinue={() => setStep(2)} /> )} {((onboard && step === 1) || (!onboard && step === 2)) && ( <> {submitErr &&
{submitErr}
} setStep(onboard ? 0 : 1)} 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; onboard?: boolean; }) { // Onboarding (OAuth) starts on the profile step — email is already known + verified. const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso"); const [modal, setModal] = useState(null); if (phase === "sso") { const valid = EMAIL_RE.test(p.email); return (

Create your account

Enter your email to get started.

{ 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}
) : (
{p.onboard ? "Signed in as" : "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 ? (
{p.relationship === "Owner" ? "Owner" : "Customer"} account — you own this property.
) : (() => { const isEmployee = p.relationship === "Employee"; const cfg = ({ Employee: { banner: "Registering as a LynkedUp Pro team member.", title: "Employee details", idLabel: "Employee ID", idPh: "EMP-12345" }, Contractor:{ banner: "Registering on behalf of the property owner.", title: "Contractor details", idLabel: "Contractor ID", idPh: "Alphanumeric ID" }, "Sub-Con": { banner: "Registering on behalf of the property owner.", title: "Sub-contractor details", idLabel: "Sub-contractor ID", idPh: "Alphanumeric ID" }, Vendor: { banner: "Registering on behalf of the property owner.", title: "Vendor details", idLabel: "Vendor ID", idPh: "Alphanumeric ID" }, } as Record)[p.relationship] ?? { banner: "Registering on behalf of the property owner.", title: "Property Owner Details", idLabel: "Owner / Property ID", idPh: "Alphanumeric ID" }; return (
{cfg.banner}
{cfg.title} {p.alloeNo && (p.alloeIdOk ? Valid : Checking…)}
p.setAlloeNo(e.target.value.toUpperCase())} placeholder={cfg.idPh} />
{!isEmployee && (
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 — 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.
}
)}
); } /* ====================== STEP 3 — ADDRESS ====================== */ function StepAddress({ sameAs, setSameAs, onRegAddr, onMailAddr, onBack, onFinish }: { sameAs: boolean; setSameAs: (v: boolean) => void; onRegAddr: (a: Addr) => void; onMailAddr: (a: Addr) => void; onBack: () => void; onFinish: () => void }) { 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, onChange }: { idPrefix: string; onChange?: (a: Addr) => void }) { 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); // Report the composed address up so the parent can persist it (postalCode is the // PIN for India, the postal field elsewhere). useEffect(() => { onChange?.({ line1, line2, city, state: stateName, postalCode: postal || pin, country: country.code, locality }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [line1, line2, city, stateName, postal, pin, country, locality]); // 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, labels = STEPS }: { current: number; labels?: string[] }) { return (
{labels.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`; }