/** Localized menu label: primary name for locale + English line for international guests. */

export type MenuNameFields = {
  name: string;
  nameEn?: string | null;
  nameAr?: string | null;
};

export function getMenuPrimaryName(
  item: MenuNameFields,
  locale: string
): string {
  const en = item.nameEn?.trim();
  const ar = item.nameAr?.trim();
  const fa = item.name.trim();

  if (locale === "en") return en || fa;
  if (locale === "ar") return ar || fa;
  return fa;
}

/** English subtitle when primary is fa/ar (helps staff and international customers). */
export function getMenuEnglishSubtitle(
  item: MenuNameFields,
  locale: string
): string | undefined {
  const en = item.nameEn?.trim();
  if (!en) return undefined;

  const primary = getMenuPrimaryName(item, locale);
  if (primary === en) return undefined;

  if (locale === "en") return undefined;

  return en;
}

/** Case-insensitive match for POS / menu search (fa, en, ar, description). */
export function menuItemMatchesSearch(
  item: MenuNameFields & { description?: string | null },
  query: string,
  locale: string
): boolean {
  const q = query.trim().toLowerCase();
  if (!q) return true;
  const haystack = [
    item.name,
    item.nameEn,
    item.nameAr,
    item.description,
    getMenuPrimaryName(item, locale),
    getMenuEnglishSubtitle(item, locale),
  ]
    .filter((s): s is string => typeof s === "string" && s.length > 0)
    .join(" ")
    .toLowerCase();
  return haystack.includes(q);
}
