<script setup lang="ts">
import { computed } from 'vue'
import icons, { type IconMap } from '../../assets/icons'
import type { FdsIconProps } from './types'

const props = withDefaults(defineProps<FdsIconProps>(), {
  size: 24,
  title: undefined,
  dataTestid: undefined,
})

function normalizeSvg(svg: string): string {
  // Replace explicit width/height with 100% to allow container sizing
  return svg.replace(/width="(.*?)"/g, 'width="100%"').replace(/height="(.*?)"/g, 'height="100%"')
}

const svgHtml = computed(() => {
  const map = icons as IconMap
  const entry = map[props.name]
  if (!entry) return ''
  const raw = typeof entry === 'function' ? entry() : entry
  const withTitle = props.title ? raw.replace('<svg', `<svg aria-label="${props.title}" role="img"`) : raw
  return normalizeSvg(withTitle)
})

const pixelSize = computed(() => (typeof props.size === 'number' ? `${props.size}px` : props.size))

const rootAttrs = computed(() => {
  const attrs: Record<string, string> = {}
  if (props.dataTestid) {
    attrs['data-testid'] = props.dataTestid
  }
  return attrs
})
</script>

<template>
  <span
    class="flex items-center justify-center align-middle"
    :style="{ width: pixelSize, height: pixelSize }"
    v-bind="rootAttrs"
    v-html="svgHtml"
  ></span>
</template>
