<template>
    <NuxtLink class="text-accent-blue" v-if="data && data[0] && status !== 'pending'"
        :to="{ path: `/explorer/${project}/${data[0].path}`, hash: hash }" :class="class">
        <PreviewContent :project="project" :path="data[0].path" :anchor="hash">
            <div class="inline-flex items-center">
                <slot v-bind="$attrs"></slot>
                <ThemeIcon class="w-4 h-4 inline-block" v-if="data && data[0] && data[0].type !== 'Markdown'" :height="20" :width="20"
                    :icon="`link-${data[0].type.toLowerCase()}`" />
            </div>
        </PreviewContent>
    </NuxtLink>
    <NuxtLink v-else-if="href" :to="href" :class="class" class="text-accent-blue inline-flex items-center">
        <slot v-bind="$attrs"></slot>
        <ThemeIcon class="w-4 h-4 inline-block" v-if="data && data[0] && data[0].type !== 'Markdown'" :height="20" :width="20"
            :icon="`link-${data[0].type.toLowerCase()}`" />
    </NuxtLink>
    <slot :class="class" v-else v-bind="$attrs"></slot>
</template>

<script setup lang="ts">
import { parseURL } from 'ufo';

const props = defineProps({
    href: {
        type: String,
        required: false,
    },
    class: {
        type: String,
        required: false,
    }
});

const route = useRoute();
const { hash, pathname, protocol } = parseURL(props.href);
const project = computed(() => parseInt(Array.isArray(route.params.projectId) ? '0' : route.params.projectId));
const { data, status } = await useFetch(`/api/project/${project.value}/file`, {
    method: 'GET',
    query: {
        search: `%${pathname}`
    },
    transform: (data) => data?.map(e => ({ path: e.path, type: e.type })),
    key: `file:${project.value}:%${pathname}`,
    dedupe: 'defer'
});
</script>

<style>
.tag
{
    @apply bg-accent-blue;
    @apply bg-opacity-10;
    @apply hover:bg-opacity-20;
    @apply text-accent-blue;
    @apply text-sm;
    @apply px-1;
    @apply ms-1;
    @apply pb-0.5;
    @apply rounded-full;
    @apply rounded-se-none;
    @apply border;
    @apply border-accent-blue;
    @apply border-opacity-30;
}
</style>