<template>
    <div v-if="status === 'pending'" class="flex">
        <Head>
            <Title>d[any] - Chargement</Title>
        </Head>
        <Loading />
    </div>
    <div class="flex flex-1 justify-start items-start" v-else-if="page">
        <Head>
            <Title>d[any] - {{ page.title }}</Title>
        </Head>
        <template v-if="page.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>{{ page.title }}</ProseH1>
                    <NuxtLink :href="{ name: 'explore-edit-path', params: { path: path } }"><Button v-if="isOwner">Modifier</Button></NuxtLink>
                </div>
                <Markdown :content="page.content" />
            </div>
        </template>
        <template v-else-if="page.type === 'canvas'">
            <Canvas :canvas="JSON.parse(page.content)" />
        </template>
        <template v-else>
            <ProseH2 class="flex-1 text-center">Impossible d'afficher le contenu demandé</ProseH2>
        </template>
    </div>
    <div v-else-if="status === 'error'">
        <Head>
            <Title>d[any] - Erreur</Title>
        </Head>
        <span>{{ error?.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);

watch(path, () => {
    if(path.value === 'index')
    {
        useRouter().push({ name: 'explore' });
    }
}, { immediate: true });

const { loggedIn, user } = useUserSession();

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