/**
 * Strips native emoji from any text saved through the admin panel, so the
 * "Insert Icon" picker + icon_library is the only way icons reach the site,
 * even if an editor pastes emoji from elsewhere.
 *
 * Covers the main emoji Unicode blocks plus variation selectors and ZWJ,
 * without touching ordinary punctuation or non-Latin scripts.
 */
const EMOJI_PATTERN =
  /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{2190}-\u{21FF}\u{2B00}-\u{2BFF}\u{FE0F}\u{200D}]/gu;

export function stripEmoji(input: string): string {
  return input.replace(EMOJI_PATTERN, "").replace(/[ \t]{2,}/g, " ").trim();
}

/** Recursively sanitizes every string value in an object/array before save. */
export function sanitizeDeep<T>(value: T): T {
  if (typeof value === "string") return stripEmoji(value) as unknown as T;
  if (Array.isArray(value)) return value.map(sanitizeDeep) as unknown as T;
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, sanitizeDeep(v)])
    ) as T;
  }
  return value;
}
