<template>
  <div class="px-4 mt-4">
    <ProductsList
        :products="productsStore.products.data"
        :hasMore="productsStore.products.meta.hasMore"
        :isLoading="productsStore.isLoading"
        :isLoadingMore="productsStore.isLoadingMore"
        :categoryName="category?.name"
        @loadMore="productsStore.loadMore"
    />
  </div>
</template>

<script setup>
import ProductsList from "@/components/ProductsList.vue";
import {onMounted, ref} from "vue";
import {useRoute} from "vue-router";
import {useProductsStore} from "@/stores/ProductsStore.js";
import {useCategoriesStore} from "@/stores/CategoriesStore.js";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";

defineOptions({
  name: 'Products'
});

const route = useRoute();
const productsStore = useProductsStore();
const categoriesStore = useCategoriesStore();
const yaMetrika = useYaMetrikaStore();

const categoryId = route.params.category_id ?? null;
const category = ref(null);

onMounted(async () => {
  console.debug("[Category] Category Products Mounted");
  console.debug("[Category] Load products for category: ", categoryId);
  category.value = await categoriesStore.findCategoryById(categoryId);
  console.debug("[Category] Category Name: ", category.value?.name);

  window.document.title = `${category.value?.name ?? 'Неизвестная категория'}`;
  yaMetrika.pushHit(route.path, {
    title: `${category.value?.name ?? 'Неизвестная категория'}`,
  });

  if (productsStore.filtersFullUrl === route.fullPath) {
    await productsStore.loadProducts(productsStore.filters ?? {
      operand: "AND",
      rules: {
        RULE_PRODUCT_CATEGORIES: {
          criteria: {
            product_category_ids: {
              type: "product_categories",
              params: {
                operator: "contains",
                value: [
                  categoryId
                ]
              }
            }
          }
        }
      },
    });
  } else {
    productsStore.reset();
    productsStore.filtersFullUrl = route.fullPath;
    await productsStore.loadProducts({
      operand: "AND",
      rules: {
        RULE_PRODUCT_CATEGORIES: {
          criteria: {
            product_category_ids: {
              type: "product_categories",
              params: {
                operator: "contains",
                value: [
                  categoryId
                ]
              }
            }
          }
        }
      },
    });
  }
});
</script>
