<template>
    <Teleport to="#teleports">
        <div class="popover hover-popover" :class="{'is-loaded': pending === false && content !== ''}" :style="{'top': (pos?.y ?? 0) - 4, 'left': (pos?.y ?? 0) + 4}">
            <template v-if="display">
                <div v-if="pending" class="loading"></div>
                <div class="markdown-embed" v-else-if="content !== ''">
                    <div class="markdown-preview-view markdown-rendered">
                        <div class="markdown-embed-content">
                            <h1>{{ title }}</h1>
                            <Markdown v-model="content"></Markdown>
                        </div>
                    </div>
                </div>
                <div class="not-found-container" v-else>
                    <div class="not-found-image"></div>
                    <div class="not-found-title">Impossible d'afficher (ou vide)</div>
                    <div class="not-found-description">Cette page est actuellement vide ou impossible à traiter</div>
                </div>
            </template>
        </div>
    </Teleport>
    <span ref="el" @mouseenter="show" @mouseleave="hide">
        <slot></slot>
    </span>
</template>

<script setup lang="ts">
import { useDebounceFn as debounce } from '@vueuse/core';

const props = defineProps({
    project: {
        type: Number,
        required: true,
    },
    path: {
        type: String,
        required: true,
    },
    anchor: {
        type: String,
        required: false,
    }
})
const content = ref(''), title = ref(''), display = ref(false), pending = ref(false);
const el = ref(), pos = ref<DOMRect>();
watch(display, () => display.value && !pending.value && content.value === '' && fetch());

onMounted(() => {
    if(el && el.value)
    {
        pos.value = (el.value as HTMLDivElement).getBoundingClientRect();
        debugger;
    }
})

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

    const data = await $fetch(`/api/project/${props.project}/file`, {
        method: 'get',
        query: {
            path: props.path,
        },
    });

    pending.value = false;

    if(data && data[0])
    {
        content.value = data[0].content;
        title.value = data[0].title;
    }
}
const show = debounce(() => display.value = true, 250), hide = debounce(() => display.value = false, 250);
</script>