<script setup lang="ts">
import { computed, useAttrs } from 'vue';
import { Icon } from '@iconify/vue';

defineOptions({ name: 'SvgIcon', inheritAttrs: false });

/**
 * Props
 *
 * - Support iconify, local svg icon and image icon
 * - If imageIcon is passed, it will be rendered first
 * - If icon and localIcon are passed at the same time, localIcon will be rendered first
 */
interface Props {
  /** Iconify icon name */
  icon?: string;
  /** Local svg icon name */
  localIcon?: string;
  /** Image icon path */
  imageIcon?: string;
  /** Icon font size */
  fontSize?: number;
}

const props = defineProps<Props>();

const attrs = useAttrs();

const bindAttrs = computed(() => {
  const style = (attrs.style as string) || '';
  const fontSizeStyle = props.fontSize ? `font-size: ${props.fontSize}px;` : '';
  return {
    class: (attrs.class as string) || '',
    style: `${style} ${fontSizeStyle}`
  };
});

const symbolId = computed(() => {
  const { VITE_ICON_LOCAL_PREFIX: prefix } = import.meta.env;

  const defaultLocalIcon = 'no-icon';

  const icon = props.localIcon || defaultLocalIcon;

  return `#${prefix}-${icon}`;
});

/** Render priority: imageIcon > localIcon > icon */
const renderImageIcon = computed(() => Boolean(props.imageIcon));
const renderLocalIcon = computed(() => !renderImageIcon.value && (props.localIcon || !props.icon));
</script>

<template>
  <template v-if="renderImageIcon">
    <img
      :src="imageIcon"
      alt="Icon"
      class="inline-block"
      v-bind="bindAttrs"
      style="vertical-align: middle; width: 1em; height: 1em"
    />
  </template>
  <template v-else-if="renderLocalIcon">
    <svg aria-hidden="true" width="1em" height="1em" v-bind="bindAttrs">
      <use :xlink:href="symbolId" fill="currentColor" />
    </svg>
  </template>
  <template v-else>
    <Icon v-if="icon" :icon="icon" v-bind="bindAttrs" />
  </template>
</template>

<style scoped></style>
