<template>
  <div class="all _page _container">
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="all__breadcrumbs _breadcrumbs"
    />
    <UiSectionTitle
      :title="h1"
      :count="totalCount"
      class="all__title"
      icon="grid"
    />

    <div class="_nav-filter">
      <CategoryNav
        v-if="categoriesGroupByLetterChips"
        :items="categoriesGroupByLetterChips as IChipsItem[]"
      />
      <div
        v-else
        class="categories__loading _loading"
      />
    </div>

    <LazyCategoryByLetter
      v-if="categoriesGroupByLetter"
      :categories="categoriesGroupByLetter as Record<string,ICategoryCard[]>"
      hydrate-on-visible
    />

    <LazySectionSeoText
      :text="t('all_footer_text')"
      links-link="all_footer_links"
      hydrate-on-visible
    />

    <section
      v-if="dataModels"
      class="all__popular-models"
    >
      <LazySectionModels
        :data-items="dataModels.items"
        :title="t('categories_popular_models')"
        hydrate-on-visible
      />
    </section>
  </div>
</template>

<script setup lang="ts">
import type { IBreadcrumbItem, ICategoryCard, IChipsItem } from '../../types';
import { ModelsApiService } from '../../services/api/models.service';
import { CategoriesApiService } from '../../services/api/categories.service';
import { AsyncData } from '../../runtime';

const pageName = useRoute().name;

const { t } = useI18n();

const [
  { data: dataModels },
  { data: categoriesGroupByLetterChips },
  { data: categoriesGroupByLetter },
] = await Promise.all([
  useFetchTopModels(ModelsApiService.getTop, 25, AsyncData.TopModels, String(pageName)),
  useFetchCategoriesGroupByLetter(AsyncData.GroupsCategoriesByLetterChips, CategoriesApiService.getListGroupedByLetterChips),
  useFetchCategoriesGroupByLetter(AsyncData.GroupsCategoriesByLetter, CategoriesApiService.getListGroupedByLetter),
]);

const pagePureName = useGetPureRouteName();
const { meta, h1 } = useMeta({ t, pageKey: pagePureName, brandName: useAppConfig().brandName });

watchEffect(() => {
  useHead(meta.value);
});

const totalCount = computed(() =>
  Object.values(categoriesGroupByLetter.value || {}).reduce((sum, arr) => sum + arr.length, 0)
);

const breadcrumbs = [
  {
    name: `${t('navigation.main')}`,
    to: '/',
  },
  {
    name: `${t('navigation.categories')}`,
    to: '/categories',
  },
  {
    name: `${t('all_categories')}`,
  },
] as IBreadcrumbItem[];
</script>

<style lang="scss">
.all__popular-models {
  margin-top: 32px;
}

.all__title {
  margin-bottom: 16px;
}
</style>
