import type { Emoji } from '@/hooks/useAvatars'
import type { AvatarPlaybackEvent } from '@/lib/protocol'

export function resolveAvatarEmoji(
  emojis: Emoji[],
  event?: AvatarPlaybackEvent | null,
): Emoji | null {
  if (!Array.isArray(emojis) || emojis.length === 0) {
    return null
  }

  const normalized = [...emojis].sort((a, b) => {
    if (a.sort_order !== b.sort_order) {
      return a.sort_order - b.sort_order
    }
    return a.created_at - b.created_at
  })

  if (event) {
    const exactMatch = normalized.find(emoji =>
      emoji.trigger_type === event.type
      && (emoji.trigger_result ?? null) === (event.result ?? null),
    )

    if (exactMatch) {
      return exactMatch
    }

    const typeMatch = normalized.find(emoji =>
      emoji.trigger_type === event.type
      && emoji.trigger_result == null,
    )

    if (typeMatch) {
      return typeMatch
    }
  }

  return normalized.find(emoji => emoji.trigger_type === 'default') ?? normalized[0] ?? null
}
