<template>
  <div>
    <div>
      <h2 v-if="categoryName" class="text-lg font-bold mb-5">{{ categoryName }}</h2>

      <template v-if="products.length > 0">
        <div class="products-grid grid grid-cols-2 gap-x-3 gap-y-3">
          <RouterLink
              v-for="(product, index) in products"
              :key="product.id"
              class="radius-box bg-base-100 shadow-sm p-2"
              :to="`/product/${product.id}`"
              @click="productClick(product, index)"
          >
            <ProductImageSwiper :images="product.images"/>
            <PriceTitle :product="product"/>
          </RouterLink>
          <div ref="bottom" style="height: 1px;"></div>
        </div>

        <div v-if="isLoadingMore" class="text-center mt-5">
          <span class="loading loading-spinner loading-md"></span> Загрузка товаров...
        </div>

        <div v-else-if="hasMore === false" class="text-xs text-center mt-4 pt-4 mb-2 border-t">
          {{ settings.texts.text_no_more_products }}
        </div>
      </template>

      <div v-else-if="isLoading === true"
           class="grid grid-cols-2 gap-x-6 gap-y-10">
        <div v-for="n in 8" :key="n" class="animate-pulse space-y-2">
          <div class="aspect-square bg-gray-200 rounded-md"></div>
          <div class="h-4 bg-gray-200 rounded w-3/4"></div>
          <div class="h-4 bg-gray-200 rounded w-1/2"></div>
        </div>
      </div>

      <NoProducts v-else/>
    </div>

    <div v-if="false" class="fixed z-50 w-full opacity-90" style="bottom: calc(var(--tg-safe-area-inset-bottom, 0px) + 80px);">
      <div class="flex justify-center">
        <button
            @click="showFilters"
            class="btn shadow-xl relative"
            :class="{'btn-accent' : filtersStore.isFiltersChanged}"
        >
          <IconFunnel/>
          Фильтры
          <span v-if="filtersStore.isFiltersChanged" class="status status-primary"></span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import NoProducts from "@/components/NoProducts.vue";
import ProductImageSwiper from "@/components/ProductImageSwiper.vue";
import {useSettingsStore} from "@/stores/SettingsStore.js";
import {ref} from "vue";
import {useIntersectionObserver} from '@vueuse/core';
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";
import IconFunnel from "@/components/Icons/IconFunnel.vue";
import {useProductFiltersStore} from "@/stores/ProductFiltersStore.js";
import {useRouter} from "vue-router";
import PriceTitle from "@/components/ProductItem/PriceTitle.vue";
import {useHapticFeedback} from "@/composables/useHapticFeedback.js";

const router = useRouter();
const haptic = useHapticFeedback();
const yaMetrika = useYaMetrikaStore();
const settings = useSettingsStore();
const filtersStore = useProductFiltersStore();
const bottom = ref(null);

const emits = defineEmits(['loadMore']);

const props = defineProps({
  products: {
    type: Array,
    default: () => [],
  },

  hasMore: {
    type: Boolean,
    default: false,
  },

  categoryName: {
    type: String,
    default: () => '',
  },

  isLoading: {
    type: Boolean,
    default: false,
  },

  isLoadingMore: {
    type: Boolean,
    default: false,
  }
});

function productClick(product, index) {
  haptic.selectionChanged();
  yaMetrika.dataLayerPush({
    "ecommerce": {
      "currencyCode": settings.currency_code,
      "click": {
        "products": [
          {
            "id": product.id,
            "name": product.name,
            "price": product.final_price_numeric,
            "brand": product.manufacturer_name,
            "category": product.category_name,
            "list": "Главная страница",
            "position": index,
          }
        ]
      }
    }
  });
}

useIntersectionObserver(
    bottom,
    ([entry]) => {
      console.debug('[Product List]: Check Intersection: ', entry?.isIntersecting);
      if (entry?.isIntersecting === true
          && props.hasMore === true
          && props.isLoading === false
          && props.isLoadingMore === false
      ) {
        console.debug('[Product List]: Send Load More signal');
        emits('loadMore');
      }
    },
    {
      root: null, // viewport
      rootMargin: '200px 0px 400px 0px', // top right bottom left
      threshold: 0, // срабатывает, как только элемент пересекает viewport
    }
);

function showFilters() {
  haptic.impactOccurred('soft');
  router.push({name: 'filters'});
}
</script>

<style scoped>
.product-grid-card {

}
</style>
