"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, 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<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 [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);
  // When arriving from a team invite, the email is fixed to the invited address.
  const [invitedEmail, setInvitedEmail] = useState("");

  useEffect(() => {
    if (onboard) return;
    try { const e = sessionStorage.getItem("invite_email"); if (e) { setEmail(e); setInvitedEmail(e); } } catch { /* ignore */ }
  }, [onboard]);

  // 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 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 step0Valid =
    first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk &&
    termsOk && privacyOk;

  // 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,
    };
    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 CRM registration payload to be-crm (name, phone, addresses,
      //    consent). No role/persona — a new user has no permissions until invited.
      //    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, ""),
          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.
      }

      // 3) If the user arrived from a team invitation link, redeem it now — this
      //    creates their membership with the invited role(s). Non-fatal.
      try {
        const inviteToken = sessionStorage.getItem("invite_token");
        if (inviteToken) {
          await sdk.command("crm.team.invitation.accept", { token: inviteToken });
          sessionStorage.removeItem("invite_token");
          sessionStorage.removeItem("invite_email");
        }
      } catch { /* invitation expired/used — they can still be invited again */ }
    }
    // 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 (
    <div className="card anim-fade-up">
      <Stepper current={step} labels={STEP_LABELS} />

      {step === 0 && (
        <>
          {submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
          <StepAccount
            onboard={onboard} creating={creating} invited={!!invitedEmail}
            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}
            termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk}
            valid={!!step0Valid}
            onContinue={leaveAccountStep} toLogin={() => router.push("/portal/login")}
          />
        </>
      )}

      {step === 1 && (
        <StepVerify
          cc={cc} phone={phone} country={country}
          phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
          valid={verifyValid} 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;
  termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void;
  valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean; invited?: 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 | "terms" | "privacy">(null);

  if (phase === "sso") {
    const valid = EMAIL_RE.test(p.email);
    return (
      <div>
        <StepBack onClick={p.toLogin} />
        <h1>{p.invited ? "Accept your invitation" : "Create your account"}</h1>
        <p className="sub">{p.invited ? "You've been invited to the team. Set up your account to join." : "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={!p.invited} disabled={p.invited} readOnly={p.invited} />
              </div>
              {p.invited && <span className="faint" style={{ fontSize: 12 }}>This is the address you were invited with.</span>}
            </div>
            <button className="btn btn-primary" style={{ marginTop: 12 }} disabled={!valid}>Continue <Icon name="arrowR" size={16} /></button>
          </form>
        </div>
        {!p.invited && <p className="foot-note">Already registered? <button className="link" onClick={p.toLogin}>Sign in</button></p>}
      </div>
    );
  }

  return (
    <div>
      {/* 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 && <StepBack onClick={() => setPhase("sso")} />}
      <h1>Complete your profile</h1>
      <p className="sub">Tell us a bit about you to set up your account.</p>

      <div className="field" style={{ marginTop: 16 }}>
        <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} disabled readOnly aria-label="Email address" />
        </div>
        <span className="faint" style={{ fontSize: 12 }}>{p.onboard ? "Verified with Google — this can't be changed." : "The email you're registering with."}</span>
      </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="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 || p.creating} onClick={p.onContinue}>
        {p.creating ? "Creating account…" : p.onboard ? "Continue" : "Create Account & Verify"} {!p.creating && <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 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 (
    <div>
      <StepBack onClick={p.onBack} />
      <h1>Verify your phone</h1>
      <p className="sub">We&apos;ll text a one-time code to confirm your number. Your email is already verified.</p>

      <div className="col gap-4" style={{ marginTop: 16 }}>
        <PhoneVerify cc={p.cc} country={p.country} 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" | "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<SendState>("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 (
      <div className="vchannel verified">
        <div className="row between">
          <span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name="phone" size={16} /> Mobile</span>
          <Badge tone="green"><Icon name="check" size={12} /> Verified</Badge>
        </div>
        <p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{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="phone" size={16} /> Mobile number</span>
      </div>

      <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} disabled={state === "sent"} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
      </div>

      <div className="row between" style={{ marginTop: 12 }}>
        <span className="faint" style={{ fontSize: 12 }}>{MOCK_OTP ? "Demo verification (no SMS sent)." : "Standard SMS rates may apply."}</span>
        <button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "sent"} onClick={send}>
          {state === "sending" ? "Sending…" : state === "sent" ? "Sent" : "Send code"}
        </button>
      </div>

      {state === "sent" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>{MOCK_OTP ? `Demo mode — enter ${DEMO_OTP} to verify (SMS temporarily disabled).` : `Code sent to ${cc} ${value} by SMS.`}</p>}
      {state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>}
      {state === "send_error" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Couldn&apos;t send the code. Check the number and try again.</FlashNote></div>}

      {state === "sent" && (
        <div style={{ marginTop: 14 }}>
          <OtpBoxes onComplete={submit} error={!!otpError} />
          {otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">{otpError}</FlashNote></div>}
          <div style={{ marginTop: 12 }}><ResendLink seconds={60} onResend={send} /></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, labels = STEPS }: { current: number; labels?: string[] }) {
  return (
    <div className="steps">
      {labels.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`;
}
