"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() {
  const router = useRouter();
  const { register } = 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<Addr>({});
  const [mailAddr, setMailAddr] = useState<Addr>({});
  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);

  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 — appshell → Supabase (SSO users already have a session).
      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 {
        // Non-fatal: the auth account already exists; the domain profile can be filled in later.
      }
    }
    router.push("/dashboard");
  }

  return (
    <div className="card anim-fade-up">
      <Stepper current={step} />

      {step === 0 && (
        <StepAccount
          sso={sso} setSso={setSso} email={email} setEmail={setEmail}
          first={first} setFirst={setFirst} last={last} setLast={setLast}
          cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country}
          pw={pw} setPw={setPw}
          relationship={relationship} setRelationship={setRelationship} isSelf={isSelf}
          alloeNo={alloeNo} setAlloeNo={setAlloeNo} alloeIdOk={alloeIdOk}
          alloeFirst={alloeFirst} setAlloeFirst={setAlloeFirst} alloeLast={alloeLast} setAlloeLast={setAlloeLast}
          termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk}
          valid={!!step0Valid}
          onContinue={() => setStep(1)} toLogin={() => router.push("/portal/login")}
        />
      )}

      {step === 1 && (
        <StepVerify
          emailValue={sso?.email || email} cc={cc} phone={phone} country={country}
          emailVerified={emailVerified} setEmailVerified={setEmailVerified}
          phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
          valid={step2Valid} onBack={() => setStep(0)} onContinue={() => setStep(2)}
        />
      )}

      {step === 2 && (
        <>
          {submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
          <StepAddress sameAs={mailingSame} setSameAs={setMailingSame} onRegAddr={setRegAddr} onMailAddr={setMailAddr} onBack={() => setStep(1)} onFinish={finish} />
        </>
      )}
    </div>
  );
}

/* ====================== 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 | "terms" | "privacy">(null);

  if (phase === "sso") {
    const valid = EMAIL_RE.test(p.email);
    return (
      <div>
        <h1>Create your account</h1>
        <p className="sub">Enter your email to get started.</p>
        <div style={{ marginTop: 20 }}>
          <form onSubmit={(e) => { e.preventDefault(); if (valid) { p.setSso(null); setPhase("profile"); } }}>
            <div className="field">
              <label className="label">Email address</label>
              <div className="input-wrap">
                <span className="input-ico"><Icon name="mail" size={17} /></span>
                <input className="input" type="email" value={p.email} onChange={(e) => p.setEmail(e.target.value)} placeholder="you@example.com" autoFocus />
              </div>
            </div>
            <button className="btn btn-primary" style={{ marginTop: 12 }} disabled={!valid}>Continue <Icon name="arrowR" size={16} /></button>
          </form>
        </div>
        <p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>
      </div>
    );
  }

  return (
    <div>
      <h1>Complete your profile</h1>
      <p className="sub">Tell us a bit about you to set up your account.</p>

      <div style={{ marginTop: 16 }}>
        {p.sso ? (
          <div className="conn-banner conn-green"><Icon name="check" size={16} /> Connected with {cap(p.sso.provider)} · {p.sso.email}</div>
        ) : (
          <div className="conn-banner conn-blue"><Icon name="mail" size={16} /> Creating account for {p.email}</div>
        )}
      </div>

      <div className="row gap-3" style={{ marginTop: 18, alignItems: "center" }}>
        <div className="avatar-edit">
          <Avatar initials={`${p.first[0] ?? "U"}${p.last[0] ?? ""}`.toUpperCase()} size={72} />
          <span className="fab"><Icon name="camera" size={13} /></span>
        </div>
        <div className="col" style={{ gap: 2 }}>
          <span style={{ fontWeight: 600, fontSize: 14 }}>Profile photo</span>
          <span className="faint" style={{ fontSize: 12 }}>Optional now — becomes mandatory later at KYC.</span>
        </div>
      </div>

      <div className="row gap-3" style={{ marginTop: 16 }}>
        <div className="field grow"><label className="label">First name</label><input className="input" value={p.first} onChange={(e) => p.setFirst(e.target.value)} placeholder="First name" /></div>
        <div className="field grow"><label className="label">Last name</label><input className="input" value={p.last} onChange={(e) => p.setLast(e.target.value)} placeholder="Last name" /></div>
      </div>

      <div className="field" style={{ marginTop: 14 }}>
        <label className="label">Mobile number</label>
        <div className="phone-row">
          <div className="cc-field">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img className="cc-flag-img" src={flagUrl(p.country.flag)} alt={p.country.name} width={22} height={16} />
            <select className="input cc-select" value={p.cc} onChange={(e) => p.setCc(e.target.value)}>
              {countryCodes.map((c) => <option key={c.code} value={c.code}>{c.code}</option>)}
            </select>
          </div>
          <input className="input grow" inputMode="numeric" value={p.phone} onChange={(e) => p.setPhone(e.target.value.replace(/\D/g, ""))} placeholder={p.country.example} />
        </div>
        {p.phone && !p.phoneOk && <span style={{ fontSize: 12, color: "#fca5a5" }}>Enter a valid {p.country.digits}-digit number.</span>}
      </div>

      {p.sso ? (
        <div style={{ marginTop: 14 }}><FlashNote tone="success">Signed up with {cap(p.sso.provider)} — no password needed.</FlashNote></div>
      ) : (
        <div className="field" style={{ marginTop: 14 }}>
          <label className="label">Password</label>
          <input className="input" type="password" value={p.pw} onChange={(e) => p.setPw(e.target.value)} placeholder="Create a strong password" />
          <PasswordStrength pw={p.pw} />
        </div>
      )}

      <div className="field" style={{ marginTop: 14 }}>
        <label className="label">Your role</label>
        <select className="input" value={p.relationship} onChange={(e) => p.setRelationship(e.target.value)}>
          {relationshipOptions.map((r) => <option key={r}>{r}</option>)}
        </select>
      </div>

      {p.isSelf ? (
        <div style={{ marginTop: 12 }}><FlashNote tone="success">{p.relationship === "Owner" ? "Owner" : "Customer"} account — you own this property.</FlashNote></div>
      ) : (() => {
        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<string, { banner: string; title: string; idLabel: string; idPh: string }>)[p.relationship]
          ?? { banner: "Registering on behalf of the property owner.", title: "Property Owner Details", idLabel: "Owner / Property ID", idPh: "Alphanumeric ID" };
        return (
          <div style={{ marginTop: 12 }}>
            <FlashNote tone="info">{cfg.banner}</FlashNote>
            <div className="dashed-block" style={{ marginTop: 12 }}>
              <div className="row between" style={{ marginBottom: 12 }}>
                <strong style={{ fontSize: 13.5 }}>{cfg.title}</strong>
                {p.alloeNo && (p.alloeIdOk ? <Badge tone="green"><Icon name="check" size={12} /> Valid</Badge> : <Badge tone="gray">Checking…</Badge>)}
              </div>
              <div className="field">
                <label className="label">{cfg.idLabel}</label>
                <input className="input" value={p.alloeNo} onChange={(e) => p.setAlloeNo(e.target.value.toUpperCase())} placeholder={cfg.idPh} />
              </div>
              {!isEmployee && (
                <div className="row gap-3" style={{ marginTop: 12 }}>
                  <div className="field grow"><label className="label">Owner first name</label><input className="input" value={p.alloeFirst} onChange={(e) => p.setAlloeFirst(e.target.value)} /></div>
                  <div className="field grow"><label className="label">Owner last name</label><input className="input" value={p.alloeLast} onChange={(e) => p.setAlloeLast(e.target.value)} /></div>
                </div>
              )}
            </div>
          </div>
        );
      })()}

      <div className="col gap-2" style={{ marginTop: 16 }}>
        <label className="check-row">
          <input type="checkbox" checked={p.termsOk} disabled={!reviewed.terms} onChange={(e) => p.setTermsOk(e.target.checked)} />
          <span>I agree to the <button type="button" className="link" onClick={() => setModal("terms")}>Terms of Use</button>{!reviewed.terms && <span className="faint"> — open &amp; scroll to enable</span>}</span>
        </label>
        <label className="check-row">
          <input type="checkbox" checked={p.privacyOk} disabled={!reviewed.privacy} onChange={(e) => p.setPrivacyOk(e.target.checked)} />
          <span>I agree to the <button type="button" className="link" onClick={() => setModal("privacy")}>Privacy Policy</button>{!reviewed.privacy && <span className="faint"> — open &amp; scroll to enable</span>}</span>
        </label>
      </div>

      {!p.valid && <p className="hint-line">Fill all required fields and accept both documents to continue.</p>}

      <button className="btn btn-primary" style={{ marginTop: 14 }} disabled={!p.valid} onClick={p.onContinue}>Create Account &amp; Verify <Icon name="arrowR" size={16} /></button>

      {modal === "terms" && <LegalModal doc={TERMS} onClose={() => setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />}
      {modal === "privacy" && <LegalModal doc={PRIVACY} onClose={() => setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />}
    </div>
  );
}
// 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 (
    <div>
      <StepBack onClick={p.onBack} />
      <h1>Verify email &amp; phone</h1>
      <p className="sub">Confirm both so we can secure your account.</p>

      <div className="col gap-4" style={{ marginTop: 16 }}>
        <VerifyChannel kind="email" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.emailVerified} onVerified={() => p.setEmailVerified(true)} />
        <VerifyChannel kind="phone" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.phoneVerified} onVerified={() => p.setPhoneVerified(true)} />
      </div>

      <div style={{ marginTop: 14 }}><RememberDevice checked={remember} onChange={setRemember} /></div>
      <button className="btn btn-primary" style={{ marginTop: 16 }} disabled={!p.valid} onClick={p.onContinue}>Continue <Icon name="arrowR" size={16} /></button>
    </div>
  );
}

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<SendState>("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 (
      <div className="vchannel verified">
        <div className="row between">
          <span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email" : "Mobile"}</span>
          <Badge tone="green"><Icon name="check" size={12} /> Verified</Badge>
        </div>
        <p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{kind === "email" ? value : `${cc} ${value}`}</p>
      </div>
    );
  }

  return (
    <div className="vchannel">
      <div className="row between" style={{ marginBottom: 12 }}>
        <span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email address" : "Mobile number"}</span>
      </div>

      {kind === "email" ? (
        <input className="input" value={value} onChange={(e) => { setValue(e.target.value); setState("idle"); }} placeholder="you@example.com" />
      ) : (
        <div className="phone-row">
          <span className="input cc-select" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img className="cc-flag-img static" src={flagUrl(country.flag)} alt={country.name} width={22} height={16} />
            {cc}
          </span>
          <input className="input grow" inputMode="numeric" value={value} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
        </div>
      )}

      <div className="row between" style={{ marginTop: 12 }}>
        <div className="seg">
          <button className={via === "primary" ? "on" : ""} onClick={() => setVia("primary")}>{primaryLabel}</button>
          <button className={via === "wa" ? "on" : ""} onClick={() => setVia("wa")}><Icon name="whatsapp" size={14} /> WhatsApp</button>
        </div>
        <button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "ok"} onClick={send}>
          {state === "sending" ? "Sending…" : "Send code"}
        </button>
      </div>

      {state === "ok" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>OTP sent via {via === "wa" ? "WhatsApp" : primaryLabel}.</p>}
      {state === "invalid_email" && <div style={{ marginTop: 10 }}><FlashNote tone="error">That email address looks invalid.</FlashNote></div>}
      {state === "mailbox_full" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">This mailbox appears full — try another email.</FlashNote></div>}
      {state === "bounce_risk" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">High bounce risk for this address.</FlashNote></div>}
      {state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>}

      {state === "ok" && (
        <div style={{ marginTop: 14 }}>
          <OtpBoxes onComplete={(c) => { if (c === "000000") setOtpError(true); else { setOtpError(false); onVerified(); } }} error={otpError} />
          {otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">Incorrect code.</FlashNote></div>}
          <div style={{ marginTop: 12 }}><ResendLink seconds={60} /></div>
        </div>
      )}
    </div>
  );
}

/* ====================== 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 (
    <div>
      <StepBack onClick={onBack} />
      <h1>Your addresses</h1>
      <p className="sub">Add your registered address and where we should send mail.</p>

      <AddrSectionHead icon="home" tone="amber" title="Registered address" sub="Where your property is registered" />
      <AddressBlock idPrefix="reg" onChange={onRegAddr} />

      <label className="check-row" style={{ marginTop: 16 }}>
        <input type="checkbox" checked={sameAs} onChange={(e) => setSameAs(e.target.checked)} />
        <span>My mailing address is the same as my registered address</span>
      </label>

      {!sameAs && (
        <>
          <AddrSectionHead icon="mail" tone="blue" title="Mailing / correspondence address" sub="Where we send physical mail" />
          <AddressBlock idPrefix="mail" onChange={onMailAddr} />
        </>
      )}

      <div style={{ marginTop: 14 }}><FlashNote tone="info">Your property address is on record; the mailing address is where we send physical mail.</FlashNote></div>

      <button className="btn btn-primary" style={{ marginTop: 16 }} onClick={onFinish}>Finish &amp; Enter Portal <Icon name="arrowR" size={16} /></button>
    </div>
  );
}

const ADDR_FLAGS: Record<string, string> = { US: "🇺🇸", IN: "🇮🇳", GB: "🇬🇧", AE: "🇦🇪" };

function AddrSectionHead({ icon, title, sub, tone }: { icon: string; title: string; sub: string; tone: "amber" | "blue" }) {
  return (
    <div className="addr-section-head">
      <span className={`addr-tile addr-tile-${tone}`}><Icon name={icon} size={18} /></span>
      <div className="col" style={{ gap: 1 }}>
        <strong style={{ fontSize: 14.5 }}>{title}</strong>
        <span className="faint" style={{ fontSize: 12 }}>{sub}</span>
      </div>
    </div>
  );
}

function AddressBlock({ idPrefix, onChange }: { idPrefix: string; onChange?: (a: Addr) => void }) {
  const [country, setCountry] = useState<AddrCountry>(addressCountries[0]);
  const [pin, setPin] = useState("");
  const [city, setCity] = useState("");
  const [stateName, setStateName] = useState("");
  const [localities, setLocalities] = useState<string[]>([]);
  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<ReturnType<typeof setTimeout> | 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 (
    <div className="addr-block">
      <div className="field"><label className="label">Country / Region</label>
        <div className="country-field">
          <span className="country-flag">{ADDR_FLAGS[country.code] ?? "🌐"}</span>
          <select className="input" style={{ paddingLeft: 44 }} value={country.code} onChange={(e) => { const c = addressCountries.find((x) => x.code === e.target.value)!; setCountry(c); setSuggestions([]); setCity(""); setStateName(""); setLocalities([]); }}>
            {addressCountries.map((c) => <option key={c.code} value={c.code}>{c.name}</option>)}
          </select>
        </div>
      </div>

      {country.lookup === "pincode" ? (
        <>
          <div className="field" style={{ marginTop: 12 }}><label className="label">{country.postalLabel}</label>
            <div className="input-wrap">
              <span className="input-ico"><Icon name="mapPin" size={17} /></span>
              <input className="input" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value.replace(/\D/g, ""))} placeholder="6-digit PIN" />
            </div>
            <span className="faint" style={{ fontSize: 12 }}>City &amp; state auto-fill from your PIN.</span>
          </div>
          {(city || stateName) && <div className="addr-located"><Icon name="check" size={13} /> Location detected · {city}{stateName ? `, ${stateName}` : ""}</div>}
          <div className="row gap-3" style={{ marginTop: 12 }}>
            <div className="field grow"><label className="label">City</label>
              <div className="input-wrap"><span className="input-ico"><Icon name="building" size={16} /></span><input className="input" value={city} onChange={(e) => setCity(e.target.value)} /></div>
            </div>
            <div className="field grow"><label className="label">State</label>
              <select className="input" value={stateName} onChange={(e) => setStateName(e.target.value)}>
                <option value="">Select</option>{country.states.map((s) => <option key={s}>{s}</option>)}
              </select>
            </div>
          </div>
          {localities.length > 0 && (
            <div className="field" style={{ marginTop: 12 }}><label className="label">Area / Locality</label>
              <select className="input" value={locality} onChange={(e) => { setLocality(e.target.value); setLine2(e.target.value); }}>
                <option value="">Select locality</option>{localities.map((l) => <option key={l}>{l}</option>)}
              </select>
            </div>
          )}
          <div className="field" style={{ marginTop: 12 }}><label className="label">House / Flat no.</label>
            <div className="input-wrap"><span className="input-ico"><Icon name="home" size={16} /></span><input className="input" value={line1} onChange={(e) => setLine1(e.target.value)} placeholder="House / Flat / Building" /></div>
          </div>
        </>
      ) : (
        <>
          <div className="field" style={{ marginTop: 12, position: "relative" }}><label className="label">Address Line 1 — House No./Street</label>
            <div className="input-wrap">
              <span className="input-ico"><Icon name="search" size={16} /></span>
              <input className="input" value={line1} onChange={(e) => onSearch(e.target.value)} placeholder="Start typing your address…" />
            </div>
            {suggestions.length > 0 && (
              <div className="suggest">
                {suggestions.map((s, i) => (
                  <button key={i} className="suggest-item" onClick={() => applySuggestion(s)}>
                    <Icon name="mapPin" size={16} />
                    <span className="si-text"><b>{s.line1}</b><span>{s.city}{s.state ? `, ${s.state}` : ""} · {s.postal}</span></span>
                  </button>
                ))}
              </div>
            )}
          </div>
          {(city || stateName) && <div className="addr-located"><Icon name="check" size={13} /> Selected · {city}{stateName ? `, ${stateName}` : ""}</div>}
          <div className="field" style={{ marginTop: 12 }}><label className="label">Address Line 2</label><input className="input" value={line2} onChange={(e) => setLine2(e.target.value)} /></div>
          <div className="row gap-3" style={{ marginTop: 12 }}>
            <div className="field grow"><label className="label">City</label>
              <div className="input-wrap"><span className="input-ico"><Icon name="building" size={16} /></span><input className="input" value={city} onChange={(e) => setCity(e.target.value)} /></div>
            </div>
            {country.states.length > 0 && (
              <div className="field grow"><label className="label">State / Region</label>
                <select className="input" value={stateName} onChange={(e) => setStateName(e.target.value)}><option value="">Select</option>{country.states.map((s) => <option key={s}>{s}</option>)}</select>
              </div>
            )}
          </div>
          <div className="field" style={{ marginTop: 12 }}><label className="label">{country.postalLabel}</label>
            <div className="input-wrap"><span className="input-ico"><Icon name="mail" size={16} /></span><input className="input" value={postal} onChange={(e) => setPostal(e.target.value)} maxLength={country.postalLen} placeholder={country.postalLabel} /></div>
          </div>
        </>
      )}
    </div>
  );
}

/* ====================== stepper ====================== */
function Stepper({ current }: { current: number }) {
  return (
    <div className="steps">
      {STEPS.map((label, i) => {
        const done = i < current, on = i === current;
        return (
          <div key={label} style={{ display: "contents" }}>
            <div className={`step ${on ? "on" : ""} ${done ? "done" : ""}`}>
              <span className="step-dot">{done ? <Icon name="check" size={14} /> : i + 1}</span>
              <span className="step-label">{label}</span>
            </div>
            {i < STEPS.length - 1 && <span className={`step-bar ${done ? "fill" : ""}`} />}
          </div>
        );
      })}
    </div>
  );
}

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`;
}
