import emojiData from '@app/data/emojis.json';

interface EmojiEntry {
	names: string[];
	surrogates: string;
}

/**
 * Build a shortcode → unicode map once at module load. Old messages
 * store reactions by shortcode (e.g. `"fire"`); the new send path
 * uses unicode surrogates (e.g. `"🔥"`). Both must render as
 * Twemoji images, so we normalise every emojiKey through this lookup
 * at display time.
 */
const NAME_TO_SURROGATES: Record<string, string> = (() => {
	const map: Record<string, string> = {};
	const data = emojiData as unknown as Record<string, EmojiEntry[]>;
	for (const key of Object.keys(data)) {
		for (const entry of data[key] ?? []) {
			for (const name of entry.names) {
				map[name] = entry.surrogates;
			}
		}
	}
	return map;
})();

/**
 * Given a reaction key (shortcode OR unicode), return the unicode
 * surrogates. Returns the input unchanged if it already looks like
 * unicode or is an unknown shortcode.
 */
export function resolveReactionKeyToUnicode(key: string): string {
	if (!key) return key;
	// Heuristic: shortcode is all ASCII letters/digits/underscores.
	// Anything else (emoji characters, mxc URLs, etc.) passes through.
	if (/^[a-zA-Z0-9_]+$/.test(key)) {
		return NAME_TO_SURROGATES[key] ?? key;
	}
	return key;
}

/**
 * Lookup the canonical shortcode for a unicode emoji (used when
 * sending reactions — the server stores by shortcode historically).
 */
export function unicodeToShortcode(surrogates: string): string | null {
	const data = emojiData as unknown as Record<string, EmojiEntry[]>;
	for (const key of Object.keys(data)) {
		for (const entry of data[key] ?? []) {
			if (entry.surrogates === surrogates) {
				return entry.names[0] ?? null;
			}
		}
	}
	return null;
}

/**
 * Friendly label for a reaction key — used in the hover tooltip and
 * the reactions modal. Custom shortcodes pass through unchanged;
 * unicode surrogates are reverse-looked-up to their canonical
 * shortcode (e.g. `👍` → `thumbsup`). Unknown unicode falls back to
 * the raw emoji character.
 */
export function reactionKeyToName(key: string): string {
	if (!key) return key;
	if (/^[a-zA-Z0-9_]+$/.test(key)) return key;
	return unicodeToShortcode(key) ?? key;
}
