<template>
	<NuxtLink class="text-accent-blue inline-flex items-center"
	:to="overview ? { name: 'explore-path', params: { path: overview.path }, hash: hash } : href" :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" :disabled="!overview">
			<template #content>
				<Loading v-if="loading" />
				<MarkdownRenderer v-else-if="overview?.type === 'markdown'" class="px-10" :content="content!.content" :filter="hash.substring(1)" />
				<Canvas v-else-if="overview?.type === 'canvas'" class="w-[600px] h-[600px] relative" :canvas="JSON.parse(content!.content)" />
			</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>
</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>