import { useEffect, useState } from 'react';

// Cache module + dédup in-flight : le pays géo-IP n'est récupéré qu'une fois par session,
// partagé entre le champ téléphone et le sélecteur de pays.
let cache: string | null | undefined;
let inflight: Promise<string | null> | null = null;

function fetchGeoCountry(): Promise<string | null> {
  if (cache !== undefined) return Promise.resolve(cache);
  if (!inflight) {
    inflight = fetch('/api/geo')
      .then((r) => r.json())
      .then((d: { country?: string | null }) => {
        cache = d?.country ?? null;
        return cache;
      })
      .catch(() => {
        cache = null;
        return null;
      });
  }
  return inflight;
}

/**
 * Code pays ISO-2 déduit de l'IP (en-tête Vercel `x-vercel-ip-country` via /api/geo).
 * Renvoie d'abord `fallback` (FR), puis le pays réel une fois résolu. Fetch mutualisé/caché.
 */
export function useGeoCountry(fallback = 'FR'): string {
  const [country, setCountry] = useState<string>(cache || fallback);
  useEffect(() => {
    let active = true;
    fetchGeoCountry().then((iso) => {
      if (active && iso) setCountry(iso);
    });
    return () => {
      active = false;
    };
  }, []);
  return country;
}
