<template>
  <div v-if="!pending && Object.keys(brand||{}).length">
		<img
        v-if="brand?.imageUrl"
        :src="brand?.imageUrl"
        alt="hero image"
        class="hero-image d-block mx-auto"
    >

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

    <shop-area :brand="brand || {} as IBrand" />
  </div>
</template>

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

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

// todo:
function setTitle(p: IBrand) {
  if (p && Object.keys(p).length) {
    nextTick(function () {
      useSeoMeta({
        title: title(parseBrandName(p)),
        // todo:
        description: p?.seo_description,
        keywords: p?.seo_keywords,
      });
    });
  }
}

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

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

            return data as IBrand[];
          })
          .then((data: IBrand[]) => (data?.[0] || {}) as IBrand)
          .then((data: IBrand) => {
            if (updateSlugOnLocale === true && (data?.slug && data?.slug !== propBrand.value)) {
              navigateTo({params: {brand: data.slug}, query: route.query});
              return null;
            }

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

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

await execute();

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

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

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

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