// src/lib/countryApi.ts

export type CountryItem = {
  name: string;
  code: string; // +91
  iso: string; // IN
  flag: string; // 🇮🇳
};

const COUNTRIES_CACHE_KEY = "countries_cache_v1";
const CACHE_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 7 days

const isoToFlagEmoji = (iso: string) =>
  iso
    .toUpperCase()
    .replace(/./g, (char) =>
      String.fromCodePoint(127397 + char.charCodeAt(0))
    );

const safeCallingCode = (idd: any): string | null => {
  const root = idd?.root;
  const suffix = idd?.suffixes?.[0];

  if (!root || !suffix) return null;

  const code = `${root}${suffix}`;
  if (!code.startsWith("+")) return null;

  return code;
};

export const fetchCountriesFromApi = async (): Promise<CountryItem[]> => {
  const res = await fetch(
    "https://restcountries.com/v3.1/all?fields=name,cca2,idd",
    { cache: "no-store" }
  );

  if (!res.ok) {
    throw new Error("Failed to fetch countries");
  }

  const data = await res.json();

  const list: CountryItem[] = (data || [])
    .map((c: any) => {
      const iso = c?.cca2;
      const name = c?.name?.common;
      const code = safeCallingCode(c?.idd);

      if (!iso || !name || !code) return null;

      return {
        name,
        iso,
        code,
        flag: isoToFlagEmoji(iso),
      };
    })
    .filter(Boolean)
    .sort((a: CountryItem, b: CountryItem) => a.name.localeCompare(b.name));

  // remove duplicates by iso (safe)
  const map = new Map<string, CountryItem>();
  list.forEach((c) => map.set(c.iso, c));

  return Array.from(map.values());
};

export const getCountries = async (): Promise<CountryItem[]> => {
  // localStorage works only in browser
  if (typeof window === "undefined") return [];

  try {
    const cachedRaw = localStorage.getItem(COUNTRIES_CACHE_KEY);

    if (cachedRaw) {
      const cached = JSON.parse(cachedRaw);

      const isValidCache =
        cached?.timestamp &&
        Array.isArray(cached?.data) &&
        Date.now() - cached.timestamp < CACHE_TTL_MS;

      if (isValidCache) {
        return cached.data as CountryItem[];
      }
    }

    const fresh = await fetchCountriesFromApi();

    localStorage.setItem(
      COUNTRIES_CACHE_KEY,
      JSON.stringify({
        timestamp: Date.now(),
        data: fresh,
      })
    );

    return fresh;
  } catch (e) {
    console.log("Country API error:", e);
    return [];
  }
};
