import type { Translation } from "../types/translation-types";

export function searchTranslationLabels(labels: Translation[], search: string): Translation[] {
  const keyword = search.trim().toLocaleLowerCase();
  if (!keyword) return labels;

  return labels
    .map((item, index) => {
      const fields = [item.translationKey, item.englishText, item.khmerText]
        .map((value) => value.toLocaleLowerCase());
      const rank = fields.some((value) => value === keyword)
        ? 0
        : fields.some((value) => value.startsWith(keyword))
          ? 1
          : fields.some((value) => value.includes(keyword))
            ? 2
            : 3;
      return { item, index, rank };
    })
    .filter(({ rank }) => rank < 3)
    .sort((a, b) => a.rank - b.rank || a.index - b.index)
    .map(({ item }) => item);
}
