<template>
  <div v-if="!pending && category">
		<img
        v-if="category?.img"
        :src="category?.img"
        alt="hero image"
        class="hero-image d-block mx-auto"
    >

    <category-details-breadcrumb v-if="category?.id" :category="category" />
    <breadcrumb v-else :subtitle="propCategory" :title="propCategory" />

    <shop-area :category="category" />
  </div>
</template>

<script lang="ts" setup>
import {api} from "@/plugins/api";
import {parseCategoryName} from "@/services/toolsService";
import type {ISiteSettings} from "@/types/site-settings-d-t";
import type {ICategory} from "@/types/category-d-t";

const route = useRoute();
const router = useRouter();
const propCategory = computed(() => String(router.currentRoute.value?.params?.category));
const {title} = useSiteSettings();
const $settings = useNuxtApp()?.$settings as ISiteSettings;
const {updateSlugOnLocale} = $settings;

function setTitle(p: ICategory) {
  if (p && Object.keys(p).length) {

    nextTick(function () {
      useSeoMeta({
        title: title(parseCategoryName(p)),
        // todo:
        description: p?.seo_description || parseCategoryName(p),
        keywords: p?.seo_keywords
      });
    });
  }
}

const {data: category, pending, error, refresh, execute} = useLazyAsyncData(
    `categories_${propCategory?.value}`,
    async (): Promise<ICategory | null> => {
      if (category.value && category.value?.slug && propCategory.value !== category.value?.slug) {
        return Promise.resolve(null);
      }

      return api.categoryData({
        slug: propCategory?.value,
        page: Number(route.query?.page || 1),
        // baseUrl: "http://localhost:3000/api"
      })
          .then((data) => {
            if (!data || data.length === 0) {
              return [{} as ICategory] as ICategory[];
            }

            return data as ICategory[];
          })
          .then((data: ICategory[]) => (data?.[0] || {}) as ICategory)
          .then((data: ICategory) => {
            // debugger
            if (updateSlugOnLocale === true && (data?.slug && data?.slug !== propCategory.value)) {
              navigateTo({params: {category: data.slug}, query: route.query});
              return null;
            }

            if (process.client) {
              setTitle(data)
            }

            return data as ICategory;
          });
    },
    {
      watch: [route],
      immediate: false
    }
);

await execute();

if (category.value && category.value?.id) {
  setTitle(category.value)
}

if (
    (error?.value && error?.value?.message === 'EMPTY')
    // || !(category?.value && category?.value?.id)
) {
  showError({
    statusCode: 404,
    statusMessage: useI18n().t('Category not found'),
    data: 'EMPTY',
    error: error?.value || new Error('EMPTY'),
    fatal: true
  } as any);
}

watch(
    () => router.currentRoute.value?.params,
    (n) => {
      if (category.value && category.value?.slug && propCategory.value !== category.value?.slug) {
        category.value = null;
        // refresh();
      }
    }
);
</script>

<style lang="scss" scoped>
.hero-image {
  max-height: 400px;
  margin: 0;
}
</style>