<template>
  <section class="px-4">
    <header class="mb-4">
      <div v-if="block.title" class="font-bold uppercase">{{ block.title }}</div>
      <div v-if="block.description" class="text-sm">{{ block.description }}</div>
    </header>
    <main>
      <ProductsList
          :products="products"
          :hasMore="hasMore"
          :isLoading="isLoading"
          :isLoadingMore="isLoadingMore"
          @loadMore="onLoadMore"
      />
    </main>
  </section>
</template>

<script setup>
import {onMounted, ref, toRaw} from "vue";
import ProductsList from "@/components/ProductsList.vue";
import {useProductFiltersStore} from "@/stores/ProductFiltersStore.js";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";
import {useSettingsStore} from "@/stores/SettingsStore.js";
import ftch from "@/utils/ftch.js";

const filtersStore = useProductFiltersStore();
const yaMetrika = useYaMetrikaStore();
const settings = useSettingsStore();

const products = ref([]);
const hasMore = ref(false);
const isLoading = ref(false);
const isLoadingMore = ref(false);
const page = ref(1);
const perPage = 10;

const props = defineProps({
  block: {
    type: Object,
    required: true,
  }
});

async function fetchProducts() {
  try {
    isLoading.value = true;
    console.debug('[Products Feed]: Start to load products for page 1. Filters: ', toRaw(filtersStore.applied));
    const response = await ftch('products', null, toRaw({
      page: 1,
      maxPages: props.block.data.max_page_count,
      perPage: perPage,
      filters: filtersStore.applied,
    }));
    products.value = response.data;
    hasMore.value = response.meta.hasMore;
    console.debug('[Products Feed]: Products loaded for page 1. Has More: ', hasMore.value);

    yaMetrika.dataLayerPush({
      ecommerce: {
        currencyCode: settings.currency_code,
        impressions: products.value.map((product, index) => {
          return {
            id: product.id,
            name: product.name,
            price: product.final_price_numeric,
            brand: product.manufacturer_name,
            category: product.category_name,
            list: 'Главная страница',
            position: index,
            discount: product.price_numeric - product.final_price_numeric,
            quantity: product.product_quantity,
          };
        }),
      },
    });
  } catch (error) {
    console.error(error);
  } finally {
    isLoading.value = false;
  }
}

async function onLoadMore() {
  try {
    console.debug('[Products Feed]: onLoadMore');
    if (isLoading.value === true || isLoadingMore.value === true || hasMore.value === false) return;
    isLoadingMore.value = true;
    page.value++;
    console.debug('[Products Feed]: Load more for page ', page.value, ' using filters: ', toRaw(filtersStore.applied));
    const response = await ftch('products', null, toRaw({
      page: page.value,
      perPage: perPage,
      maxPages: props.block.data.max_page_count,
      filters: filtersStore.applied,
    }));
    products.value.push(...response.data);
    hasMore.value = response.meta.hasMore;
    console.debug(`[Products Feed]: Products loaded for page ${page.value}. Has More: `, hasMore.value);
  } catch (error) {
    console.error(error);
  } finally {
    isLoadingMore.value = false;
  }
}

onMounted(async () => {
  console.debug("[Products Feed] Mounted");
  await fetchProducts();
});
</script>
