export const LOCALES = ["en", "es", "zh"] as const;
export type Locale = (typeof LOCALES)[number];

export const DEFAULT_LOCALE: Locale = "en";

// Validación estricta para evitar cosas raras en URLs/cookies
export function isLocale(x: string): x is Locale {
  return (LOCALES as readonly string[]).includes(x);
}

// Parse simple de Accept-Language -> elige el primer match
export function pickFromAcceptLanguage(header: string | null): Locale | null {
  if (!header) return null;

  // Ej: "es-AR,es;q=0.9,en;q=0.8"
  const parts = header
    .split(",")
    .map((p) => p.trim().toLowerCase())
    .map((p) => p.split(";")[0]);

  for (const p of parts) {
    if (p.startsWith("es")) return "es";
    if (p.startsWith("zh")) return "zh";
    if (p.startsWith("en")) return "en";
  }
  return null;
}

// Fallback por país (IP->country via Cloudflare/Vercel)
export function localeFromCountry(country: string | null): Locale | null {
  if (!country) return null;
  const c = country.toUpperCase();

  // China / HK / Macau / Taiwan: zh (ajustalo a tu criterio)
  if (["CN", "HK", "MO", "TW", "SG"].includes(c)) return "zh";

  // Países hispanohablantes (no exhaustivo)
  const ES_COUNTRIES = new Set([
    "AR","BO","CL","CO","CR","CU","DO","EC","ES","GT","HN","MX","NI","PA","PE","PR","PY","SV","UY","VE"
  ]);
  if (ES_COUNTRIES.has(c)) return "es";

  // Default
  return "en";
}
