<template>
    <div v-if="overviewStatus === 'pending'" class="flex">
        <Head>
            <Title>d[any] - Chargement</Title>
        </Head>
        <Loading />
    </div>
    <div class="flex flex-1 justify-start items-start" v-else-if="overview">
        <Head>
            <Title>d[any] - {{ overview.title }}</Title>
        </Head>
        <template v-if="overview.type === 'markdown'">
            <div class="flex flex-1 justify-start items-start flex-col xl:px-24 md:px-8 px-4 py-6">
                <div class="flex flex-1 flex-row justify-between items-center">
                    <ProseH1>{{ overview.title }}</ProseH1>
                    <div class="flex gap-4">
                        <NuxtLink :href="{ name: 'explore-edit', hash: '#' + overview.path }" v-if="isOwner"><Button>Modifier</Button></NuxtLink>
                    </div>
                </div>
                <Markdown v-if="content" :content="content.content" />
                <Loading v-else />
            </div>
        </template>
        <template v-else-if="overview.type === 'canvas'">
            <Canvas v-if="content" :canvas="JSON.parse(content.content)" />
            <Loading v-else />
        </template>
        <template v-else>
            <ProseH2 class="flex-1 text-center">Impossible d'afficher le contenu demandé</ProseH2>
        </template>
    </div>
    <div v-else-if="overviewStatus === 'error'">
        <Head>
            <Title>d[any] - Erreur</Title>
        </Head>
        <span>{{ overviewError?.message }}</span>
    </div>
    <div v-else-if="contentStatus === 'error'">
        <Head>
            <Title>d[any] - Erreur</Title>
        </Head>
        <span>{{ contentError?.message }}</span>
    </div>
    <div v-else>
        <Head>
            <Title>d[any] - Erreur</Title>
        </Head>
        <div><ProseH2>Impossible d'afficher le contenu demandé</ProseH2></div>
    </div>
</template>

<script setup lang="ts">
const route = useRouter().currentRoute;
const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path);

const { user } = useUserSession();

const { data: overview, status: overviewStatus, error: overviewError } = await useFetch(`/api/file/overview/${encodeURIComponent(path.value)}`, { watch: [route, path], });
const { data: content, status: contentStatus, error: contentError } = await useFetch(`/api/file/content/${encodeURIComponent(path.value)}`, { watch: [route, path], });
const isOwner = computed(() => user.value?.id === overview.value?.owner);
</script>