const ARABIC_MAP: Record<string, string> = {
  'ا': 'a', 'أ': 'a', 'إ': 'a', 'آ': 'a', 'ء': 'a',
  'ب': 'b',
  'ت': 't',
  'ث': 'th',
  'ج': 'j',
  'ح': 'h',
  'خ': 'kh',
  'د': 'd',
  'ذ': 'th',
  'ر': 'r',
  'ز': 'z',
  'س': 's',
  'ش': 'sh',
  'ص': 's',
  'ض': 'd',
  'ط': 't',
  'ظ': 'z',
  'ع': 'a',
  'غ': 'gh',
  'ف': 'f',
  'ق': 'q',
  'ك': 'k',
  'ل': 'l',
  'م': 'm',
  'ن': 'n',
  'ه': 'h',
  'و': 'w',
  'ي': 'y',
  'ى': 'a',
  'ة': 'a',
  'ئ': 'y',
  'ؤ': 'w',
  'لا': 'la',
};

function randomSuffix(len = 4): string {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let s = '';
  for (let i = 0; i < len; i++) s += chars[Math.floor(Math.random() * chars.length)];
  return s;
}

function isEmoji(str: string, index: number): { emoji: string; len: number } | null {
  const codePoint = str.codePointAt(index);
  if (!codePoint) return null;
  const len = codePoint > 0xFFFF ? 2 : 1;
  // Emoji ranges: Miscellaneous Symbols, Emoticons, Supplemental Symbols, etc.
  if (
    (codePoint >= 0x2600 && codePoint <= 0x27BF) ||
    (codePoint >= 0x1F300 && codePoint <= 0x1FAFF) ||
    (codePoint >= 0x1F000 && codePoint <= 0x1F02F) ||
    (codePoint >= 0x1F0A0 && codePoint <= 0x1F0FF) ||
    (codePoint >= 0x1F100 && codePoint <= 0x1F1FF) ||
    (codePoint >= 0x1F200 && codePoint <= 0x1F2FF) ||
    (codePoint >= 0xFE00 && codePoint <= 0xFE0F) ||
    (codePoint >= 0x200D && codePoint <= 0x200D)
  ) {
    return { emoji: str.slice(index, index + len), len };
  }
  return null;
}

export function toInviteSlug(name: string): string {
  let result = '';
  let i = 0;
  while (i < name.length) {
    // Check two-char Arabic combination first
    const two = name.slice(i, i + 2);
    if (ARABIC_MAP[two]) {
      result += ARABIC_MAP[two];
      i += 2;
      continue;
    }
    const ch = name[i];
    if (ARABIC_MAP[ch]) {
      result += ARABIC_MAP[ch];
      i++;
      continue;
    }
    if (/[a-zA-Z0-9]/.test(ch)) {
      result += ch.toLowerCase();
      i++;
      continue;
    }
    if (/\s/.test(ch)) {
      result += '-';
      i++;
      continue;
    }
    // Check for emoji (multi-char codepoints)
    const emojiMatch = isEmoji(name, i);
    if (emojiMatch) {
      result += emojiMatch.emoji;
      i += emojiMatch.len;
      continue;
    }
    // Skip unsupported characters (punctuation, diacritics, etc.)
    i++;
  }
  result = result.replace(/-{2,}/g, '-').replace(/^-|-$/g, '');
  if (!result) result = 'guest';
  const suffix = randomSuffix(4);
  const base = result.slice(0, 55);
  return `${base}-${suffix}`;
}
