import { getChampionAssetKey } from '@/lib/lol-assets';

const DDRAGON_CHAMPION_URL =
  'https://ddragon.leagueoflegends.com/cdn/16.9.1/data/ko_KR/champion.json';

type ChampionPayload = {
  data: Record<
    string,
    {
      id: string;
      name: string;
      image: { full: string };
    }
  >;
};

export async function getChampionDisplayNames(championNames: Array<string | null | undefined>) {
  const uniqueNames = [...new Set(championNames.filter((value): value is string => Boolean(value?.trim())))];
  if (uniqueNames.length === 0) return {} as Record<string, string>;

  const response = await fetch(DDRAGON_CHAMPION_URL, { cache: 'force-cache' });
  const payload = (await response.json()) as ChampionPayload;
  const lookup = new Map<string, string>();

  Object.values(payload.data).forEach((champion) => {
    lookup.set(champion.id.toLowerCase(), champion.name);
    lookup.set(champion.image.full.replace(/\.png$/i, '').toLowerCase(), champion.name);
  });

  const result: Record<string, string> = {};
  uniqueNames.forEach((championName) => {
    const assetKey = getChampionAssetKey(championName)?.toLowerCase() ?? championName.toLowerCase();
    result[championName] = lookup.get(assetKey) ?? championName;
  });

  return result;
}

export function localizeChampionTextWithMap(
  text: string | null | undefined,
  championDisplayNames: Record<string, string>,
  championNames: Array<string | null | undefined>,
) {
  if (!text) return '';

  let localized = text;
  const uniqueNames = [...new Set(championNames.filter((value): value is string => Boolean(value?.trim())))];

  uniqueNames.forEach((championName) => {
    const displayName = championDisplayNames[championName] ?? championName;
    const assetKey = getChampionAssetKey(championName) ?? championName;
    const variants = new Set([
      championName,
      championName.toUpperCase(),
      assetKey,
      assetKey.toUpperCase(),
    ]);

    variants.forEach((variant) => {
      if (!variant || variant === displayName) return;
      localized = localized.replace(new RegExp(escapeRegExp(variant), 'g'), displayName);
    });
  });

  return localized;
}

function escapeRegExp(value: string) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
