<template>
    <NuxtLink class="text-accent-blue inline-flex items-center" v-if="data && data[0]"
    :to="{ name: 'explore-path', params: { path: data[0].path }, hash: hash }" :class="class">
        <HoverCard class="max-w-[600px] max-h-[600px] w-full overflow-auto z-[45]" :class="{'overflow-hidden !p-0': data[0].type === 'canvas'}">
            <template #content>
                <template v-if="data[0].type === 'markdown'">
                    <div class="px-10">
                        <Markdown :content="data[0].content" />
                    </div>
                </template>
                <template v-else-if="data[0].type === 'canvas'">
                    <div class="w-[600px] h-[600px] relative">
                        <Canvas :canvas="JSON.parse(data[0].content)" />
                    </div>
                </template>
            </template>
            <template #default>
                <slot v-bind="$attrs"></slot>
                <Icon class="w-4 h-4 inline-block" v-if="data && data[0] && data[0].type !== 'markdown'" :icon="iconByType[data[0].type]" />
            </template>
        </HoverCard>
    </NuxtLink>
    <NuxtLink v-else-if="href" :to="href" :class="class" class="text-accent-blue inline-flex items-center">
        <slot v-bind="$attrs"></slot>
        <Icon class="w-4 h-4 inline-block" v-if="data && data[0] && data[0].type !== 'markdown'" :height="20" :width="20"
            :icon="`icons/link-${data[0].type.toLowerCase()}`" />
    </NuxtLink>
    <slot :class="class" v-else v-bind="$attrs"></slot>
</template>

<script setup lang="ts">
import { parseURL } from 'ufo';
import { Icon } from '@iconify/vue/dist/iconify.js';
import { iconByType } from '#shared/general.utils';

const { href } = defineProps<{
    href: string
    class?: string
}>();

const { hash, pathname, protocol } = parseURL(href);
const data = ref(), loading = ref(false);

if(!!pathname && !protocol)
{
    loading.value = true;
    try {
        data.value = await $fetch(`/api/file`, {
            query: {
                search: `%${pathname}`
            },
        });
    } catch(e) { }
    loading.value = false;
}
</script>