"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"; import { MOCK_OTP, DEMO_OTP } from "@/lib/otp"; 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, addPhone, verifyPhone } = useAuth(); const { sdk } = useAppShell(); const [step, setStep] = useState(0); const [submitErr, setSubmitErr] = useState(""); // Verifying a phone via Supabase needs a live session. Onboarding already has one // (Google OAuth); registration creates the account when leaving the Account step, // then attaches + verifies the phone on it. `creating` guards the Account button. const [creating, setCreating] = useState(false); // 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 (email is trusted without an OTP — see verifyValid below) const [phoneVerified, setPhoneVerified] = useState(false); // Onboarding: prefill the verified email — from the session-storage hint the login // page stashed at OAuth time, then confirmed via the live Supabase session. useEffect(() => { if (!onboard) return; try { const cached = sessionStorage.getItem("onboard_email"); if (cached) setEmail(cached); } catch { /* ignore */ } getUserEmail().then((e) => { if (e) setEmail(e); }).catch(() => { /* ignore */ }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [onboard]); const STEP_LABELS = onboard ? ["Profile", "Verify", "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())))); // Email is already trusted in both flows (registration: Supabase auto-confirms on // signup; onboarding: Google-verified), so the Verify step only gates on the phone. const verifyValid = phoneVerified; // Registration: create the auth account when leaving the Account step, so the phone // can be attached + verified against a live session at the Verify step. Onboarding // is already authenticated, so it just advances. async function leaveAccountStep() { if (onboard || !isShellConfigured() || sso) { setStep(1); return; } setSubmitErr(""); setCreating(true); try { await register(email, pw); setStep(1); } catch { setSubmitErr("We couldn't create that account. The email may already be registered."); } finally { setCreating(false); } } 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 already exists at this point — registration created it when // leaving the Account step; onboarding users signed in via Google. Onboarding // additionally sets a password so email+password login works too (the phone was // just verified against the same live session). if (onboard && pw) { try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ } } // 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. } } // Consume the OAuth→onboarding handoff so a stale hint can't re-open onboarding. try { sessionStorage.removeItem("onboard_email"); } catch { /* ignore */ } router.push("/dashboard"); } return (
{step === 0 && ( <> {submitErr &&
{submitErr}
} router.push("/portal/login")} /> )} {step === 1 && ( setStep(0)} onContinue={() => setStep(2)} /> )} {step === 2 && ( <> {submitErr &&
{submitErr}
} setStep(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; creating?: 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 (
{/* Non-onboarding users can step back to the email screen; onboarding starts here (email came from Google), so there's nothing to go back to. */} {!p.onboard && setPhase("sso")} />}

Complete your profile

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

{p.onboard ? "Verified with Google — this can't be changed." : "The email you're registering with."}
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 PHONE ====================== Email is already trusted (registration: Supabase auto-confirms on signup; onboarding: Google-verified), so this step only verifies the phone via a real SMS OTP: addPhone() → Twilio texts a code → verifyPhone() confirms it. Both run against the live Supabase session established in the previous step. */ function StepVerify(p: { cc: string; phone: string; country: typeof countryCodes[number]; phoneVerified: boolean; setPhoneVerified: (v: boolean) => void; valid: boolean; onBack: () => void; onContinue: () => void; }) { const [remember, setRemember] = useState(false); return (

Verify your phone

We'll text a one-time code to confirm your number. Your email is already verified.

p.setPhoneVerified(true)} />
); } type SendState = "idle" | "sending" | "sent" | "invalid_mobile" | "send_error"; function PhoneVerify({ cc, country, initialPhone, verified, onVerified }: { cc: string; country: typeof countryCodes[number]; initialPhone: string; verified: boolean; onVerified: () => void; }) { const { addPhone, verifyPhone } = useAuth(); const [value, setValue] = useState(initialPhone); const [state, setState] = useState("idle"); const [otpError, setOtpError] = useState(""); const e164 = `${cc}${value.replace(/\D/g, "")}`; async function send() { if (value.replace(/\D/g, "").length !== country.digits) { setState("invalid_mobile"); return; } setState("sending"); setOtpError(""); if (MOCK_OTP) { setState("sent"); return; } // demo: skip Twilio entirely try { await addPhone(e164); // Supabase → Twilio sends the SMS OTP setState("sent"); } catch { setState("send_error"); } } async function submit(code: string) { setOtpError(""); if (MOCK_OTP) { if (code === DEMO_OTP) onVerified(); else setOtpError(`Demo mode — enter ${DEMO_OTP} to verify.`); return; } try { await verifyPhone(e164, code); // confirm the OTP (phone_change) onVerified(); } catch { setOtpError("That code didn't match. Check the SMS and try again."); } } if (verified) { return (
Mobile Verified

{cc} {value}

); } return (
Mobile number
{/* eslint-disable-next-line @next/next/no-img-element */} {country.name} {cc} { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
{MOCK_OTP ? "Demo verification (no SMS sent)." : "Standard SMS rates may apply."}
{state === "sent" &&

{MOCK_OTP ? `Demo mode — enter ${DEMO_OTP} to verify (SMS temporarily disabled).` : `Code sent to ${cc} ${value} by SMS.`}

} {state === "invalid_mobile" &&
Enter a valid {country.digits}-digit mobile number.
} {state === "send_error" &&
Couldn't send the code. Check the number and try again.
} {state === "sent" && (
{otpError &&
{otpError}
}
)}
); } /* ====================== 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`; }