<template>
    <NuxtLink class="text-accent-blue inline-flex items-center" v-if="overview"
    :to="{ name: 'explore-path', params: { path: overview.path }, hash: hash }" :class="class">
        <HoverCard class="max-w-[600px] max-h-[600px] w-full overflow-auto z-[45]" :class="{'overflow-hidden !p-0': overview.type === 'canvas'}" @open="load">
            <template #content>
                <template v-if="loading">
                    <Loading />
                </template>
                <template v-else-if="overview.type === 'markdown'">
                    <div class="px-10">
                        <Markdown :content="content!.content" />
                    </div>
                </template>
                <template v-else-if="overview.type === 'canvas'">
                    <div class="w-[600px] h-[600px] relative">
                        <Canvas :canvas="JSON.parse(content!.content)" />
                    </div>
                </template>
            </template>
            <template #default>
                <slot v-bind="$attrs"></slot>
                <Icon class="w-4 h-4 inline-block" v-if="overview && overview.type !== 'markdown'" :icon="iconByType[overview.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="overview && overview.type !== 'markdown'" :height="20" :width="20" :icon="iconByType[overview.type]" />
    </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 overview = ref<{
    path: string;
    owner: number;
    title: string;
    type: "file" | "folder" | "markdown" | "canvas";
    navigable: boolean;
    private: boolean;
    order: number;
    visit: number;
}>(), content = ref<{
    content: string;
}>(), loading = ref(false), fetched = ref(false);

if(!!pathname && !protocol)
{
    try {
        overview.value = await $fetch(`/api/file/overview/${encodeURIComponent(pathname)}`);
    } catch(e) {}
}

async function load()
{
    if(fetched.value === true)
        return;

    fetched.value = true;
    loading.value = true;
    try {
        content.value = await $fetch(`/api/file/content/${encodeURIComponent(pathname)}`);
    } catch(e) { }
    loading.value = false;
}
</script>