<template>
  <NuxtLayout v-if="page" :name="page.meta?.layout ?? 'default'">
    <ContentRenderer :value="page" />
  </NuxtLayout>
  <div v-else>
    <h1>Page not found</h1>
    <p>This page doesn&apos;t exist in {{ locale }} language.</p>
  </div>
</template>

<script setup lang="ts">
import { withLeadingSlash } from 'ufo';
import type { Collections } from '@nuxt/content';

const route = useRoute();
const { locale } = useI18n();
const slug = computed(() => withLeadingSlash(String(route.params.slug)));

const { data: page } = await useAsyncData(
  'page-' + slug.value,
  async () => {
    const collection = ('content_' + locale.value) as keyof Collections;
    const content = await queryCollection(collection).path(slug.value).first();
    if (!content && locale.value !== 'en') {
      return await queryCollection('content_en').path(slug.value).first();
    }
    return content;
  },
  {
    watch: [locale], // Refresh when locale changes
  },
);

useMeta({ title: page.value?.title, description: page.value?.description });
</script>
