<template>
  <NuxtLayout name="default">
    <NotFound v-if="notFound" />
    <ContentBuilder v-else-if="showContentBuilder" :hero="page?.hero" :content="page?.content" />
    <CollectionDetail v-else :data="detail" />
  </NuxtLayout>
</template>

<script setup lang="ts">
import type Article from "../types/collection/article";
import type Event from "../types/collection/event";
import type Operation from "../types/collection/operation";
import type Vehicle from "../types/collection/vehicle";
import type Page from "../types/collection/page";
import provideGlobal from "../composables/provideGlobal";

const {
  params: { slug: params },
} = useRoute();
const { findOne, find } = useStrapi();

const { navbar } = await provideGlobal();
const navbar_items = computed(() => {
  return navbar?.navbar_items ?? [];
});
const navbar_sub_items = computed(() => {
  return navbar_items.value.find((ni) => ni.URL == params[0])?.navbar_sub_items ?? [];
});
const active_item = computed(() => {
  return navbar_items.value.find((ni) => ni.URL == params[0])?.page;
});
const active_sub_item = computed(() => {
  return navbar_sub_items.value.find((si) => si.URL == params[1])?.page;
});
const active_page_id = computed(() => {
  return active_sub_item.value?.documentId ?? active_item.value?.documentId ?? "";
});

const { data: pages } = await useAsyncData("pages", () =>
  findOne<Page | Array<Page>>("pages", active_page_id.value, {
    populate: {
      populate: "*",
      content: {
        populate: "*",
      },
      hero: {
        populate: "*",
      },
    },
    filters: {
      ...(active_page_id.value == "" ? { slug: params[0] } : {}),
    },
  })
);
const page = computed(() => {
  return Array.isArray(pages.value?.data) ? pages.value.data[0] : pages.value?.data;
});

let detail = ref<Article | Operation | Event | Vehicle | undefined>(undefined);
const searchDetail = computed(() => {
  if (!active_sub_item.value) return params[1];
  return params[2];
});
if (searchDetail.value) {
  let collectionOfDetail = [
    ...new Set(
      page.value?.content
        .filter((c) => c.__component == "shared.list")
        .filter((c) => c.lookup.enable_detail)
        .map((c) => c.lookup.collection)
    ),
  ];

  for (const element of collectionOfDetail) {
    const { data: details } = await useAsyncData("detail", () =>
      find<Article | Operation | Event | Vehicle>(element ?? "", {
        populate: "*",
        filters: {
          slug: params[2] ?? params[1],
        },
      })
    );
    if (details.value?.data[0]) {
      detail.value = details.value?.data[0];
      break;
    }
  }
}

const notFound = computed(() => {
  if (searchDetail.value) return !detail.value;
  else return active_page_id.value == "" && !page.value?.content && !page.value?.hero;
});

const showContentBuilder = computed(() => {
  if (searchDetail.value) return !detail.value;
  else return !!page.value?.content || !!page.value?.hero;
});
</script>
