<template>
  <div class="flex">
    <UButton :icon="icon" target="_blank" :to="link.url">
      <span>{{ link.display }}</span>
      <span v-if="link.type === 'cargo'"><UIcon name="i-mdi-download" /> {{ crateDownloads }}</span>
    </UButton>
  </div>
</template>

<script setup lang="ts">
import type { ProjectLink, ProjectLinkType } from '~/types/project';

const crates = useCrates();

const iconDict: Record<ProjectLinkType, string> = {
  github: 'mdi:github',
  gitea: 'simple-icons:gitea',
  cargo: 'simple-icons:rust',
  melpa: 'file-icons:melpa',
};

const icon = computed(() => iconDict[link.type]);

const { link } = defineProps<{
  link: ProjectLink;
}>();

const cratesData = computed(() => (link.type === 'cargo' ? crates.getCrateInfo(link.display) : null));
const crateDownloads = computed(
  () => cratesData.value?.data?.value?.crate.downloads ?? (cratesData.value?.loading ? 'loading' : 'error'),
);
</script>
