/**
 * Best-effort detection of the visitor's country as an ISO 3166-1 alpha-2 code
 * (lowercase, e.g. "in"), used to preselect the phone country code.
 *
 * Uses geojs.io — a free, keyless, CORS-enabled IP-geolocation endpoint. Any
 * failure (offline, blocked, rate-limited) resolves to null so the caller can
 * fall back to a static default; detection is a convenience, never required.
 */
export async function detectCountryIso(signal?: AbortSignal): Promise<string | null> {
  try {
    const res = await fetch("https://get.geojs.io/v1/ip/country.json", {
      signal,
      cache: "no-store",
    });
    if (!res.ok) return null;
    const data = (await res.json()) as { country?: string };
    const iso = (data?.country || "").trim().toLowerCase();
    return /^[a-z]{2}$/.test(iso) ? iso : null;
  } catch {
    return null;
  }
}
