<template>
    <HoverPopup @before-show="fetch" :class="[{'is-loaded': fetched}, file?.type === 'Markdown' ? 'overflow-auto' : 'overflow-hidden']">
        <template #content>
            <Suspense>
                <div v-if="pending" class="loading w-[550px] h-[450px]"></div>
                <template v-else-if="!!file">
                    <div v-if="file.type === 'Markdown'" class="p-6 ms-6">
                        <ProseH1>{{ file.title }}</ProseH1>
                        <Markdown v-model="file.content"></Markdown>
                    </div>
                    <div v-else-if="file.type === 'Canvas'" class="w-[550px] h-[450px] overflow-hidden">
                        <CanvasRenderer :canvas="JSON.parse(file.content) " />
                    </div>
                    <div class="h-100 w-100 flex flex-1 flex-col justify-center items-center" v-else>
                        <div class="text-3xl font-extralight tracking-wide text-light-60 dark:text-dark-60">Fichier vide</div>
                        <div class="text-lg text-light-60 dark:text-dark-60">Cette page est vide</div>
                    </div>
                </template>
                <div class="h-100 w-100 flex flex-1 flex-col justify-center items-center" v-else>
                    <div class="text-3xl font-extralight tracking-wide text-light-60 dark:text-dark-60">Impossible d'afficher</div>
                    <div class="text-lg text-light-60 dark:text-dark-60">Cette page est impossible à traiter</div>
                </div>
            </Suspense>
        </template>
        <slot></slot>
    </HoverPopup>
</template>

<script setup lang="ts">
import type { CommentedFile } from '~/types/api';

const props = defineProps({
    project: {
        type: Number,
        required: true,
    },
    path: {
        type: String,
        required: true,
    },
    anchor: {
        type: String,
        required: false,
    }
})
const file = ref<CommentedFile | null>();
const pending = ref(false), fetched = ref(false);

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

    const { data } = await useFetch(`/api/project/${props.project}/file/${encodeURIComponent(props.path)}`);

    pending.value = false;
    file.value = data.value;
}
</script>