<template>
  <template v-if="isExternalLink(to)">
    <a
      :href="to as string"
      :class="computedClasses"
      :target="target"
      v-bind="$attrs"
    >
      <slot />
    </a>
  </template>
  <template v-else>
    <router-link custom v-slot="{ href, navigate }" :to="to">
      <a
        :href="href"
        @click="navigate"
        :class="computedClasses"
        :target="target"
        v-bind="$attrs"
      >
        <slot />
      </a>
    </router-link>
  </template>
</template>

<script setup lang="ts">
import { RouteLocationRaw } from 'vue-router';
import { isExternalLink } from '@/helpers';
import { computed } from 'vue';

interface ClassesRepresentation {
  [key: string]: boolean;
}

interface Props {
  to: RouteLocationRaw | string;
  target?: string;
  classes?: string | ClassesRepresentation;
}

const props = withDefaults(defineProps<Props>(), {
  classes: '',
  target: '_self',
});

const computedClasses = computed(() => {
  const bmsLinkType = isExternalLink(props.to)
    ? 'external-link'
    : 'internal-link';
  if (typeof props.classes === 'string') {
    return `${props.classes} ${bmsLinkType}`;
  } else {
    const classes = { ...props.classes };
    classes[bmsLinkType] = true;
    return classes;
  }
});
</script>
