import { cdnUrl } from '../core'
import type { IconDefinition } from '../icons'
import { iconsCache } from '../icons'
import { IconReplacements } from '../icons/iconReplacements'
import type { GetIconDetailsResult, IconProp } from './icon.types'

const PREFIX_MAP: Record<string, string> = {
  con: 'con',
  bra: 'brand',
}
/** Optimized prefix normalization with constant time lookup */
function normalizeIconPrefix(prefix: string) {
  return PREFIX_MAP[prefix] || (prefix.startsWith('ui') ? 'fa' : prefix)
}

/**
 * Returns an object with either 'src' or 'customIcon', depending on whether the provided icon is:
 * - not in library:    'src' as CDN url
 * - in library:            'customIcon' as icon definition object
 */
export function getIconDetails(iconName?: IconProp): GetIconDetailsResult {
  if (!iconName) return {}

  const icon = IconReplacements?.[iconName] ?? iconName

  // Compute CDN url if icon is not in library cache
  if (!iconsCache.has(icon)) {
    const prefix = icon.slice(0, 3)
    const normalizedPrefix = normalizeIconPrefix(prefix)

    return {
      src: `${cdnUrl}/common/icons/ui/${normalizedPrefix}/${icon}.svg`,
    }
  }

  // Compute relevant properties based on icon definition from the library
  const { details, name, pathProps = [], svgProps = {} } = iconsCache.get(icon) as IconDefinition
  const [width, height, , , d] = details
  const viewBox = `0 0 ${width} ${height}`

  const customIcon = {
    d: Array.isArray(d) ? d : [d],
    pathProps: Array.isArray(pathProps) ? pathProps : [pathProps],
    svgProps: { 'data-name': name, viewBox, ...svgProps },
  }

  return {
    customIcon,
  }
}
