<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, onActivated, onDeactivated, ref, nextTick} 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);

// Опционально сохраняем позицию при деактивации (KeepAlive автоматически сохраняет DOM состояние)
onDeactivated(() => {
  const currentCategoryId = route.params.category_id ?? null;
  if (currentCategoryId) {
    const scrollY = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;
    if (scrollY > 0) {
      productsStore.saveScrollPosition(currentCategoryId, scrollY);
    }
  }
});

// Обработчик активации компонента (KeepAlive)
onActivated(async () => {
  console.debug("[Category] Products component activated");
  const currentCategoryId = route.params.category_id ?? null;
  
  // Если категория изменилась, загружаем новые товары
  if (currentCategoryId !== categoryId) {
    console.debug("[Category] Category changed, reloading products");
    const newCategory = await categoriesStore.findCategoryById(currentCategoryId);
    category.value = newCategory;
    window.document.title = `${newCategory?.name ?? 'Неизвестная категория'}`;
    yaMetrika.pushHit(route.path, {
      title: `${newCategory?.name ?? 'Неизвестная категория'}`,
    });
    
    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: [currentCategoryId]
              }
            }
          }
        }
      },
    });
    productsStore.lastCategoryId = currentCategoryId;
    return;
  }
  
  // Если возвращаемся на ту же категорию - не перезагружаем товары
  const isReturningToSameCategory = productsStore.lastCategoryId === currentCategoryId && 
                                     productsStore.products.data.length > 0 &&
                                     productsStore.filtersFullUrl === route.fullPath;
  
  if (isReturningToSameCategory) {
    // KeepAlive должен восстановить позицию автоматически, но если нужно - восстанавливаем явно
    await nextTick();
    const savedPosition = productsStore.getScrollPosition(currentCategoryId);
    if (savedPosition > 0) {
      // Используем requestAnimationFrame для плавного восстановления
      requestAnimationFrame(() => {
        window.scrollTo({
          top: savedPosition,
          behavior: 'instant'
        });
      });
    }
    return;
  }
  
  // Первая загрузка категории
  category.value = await categoriesStore.findCategoryById(currentCategoryId);
  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: [currentCategoryId]
              }
            }
          }
        }
      },
    });
  } 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: [currentCategoryId]
              }
            }
          }
        }
      },
    });
  }
  
  productsStore.lastCategoryId = currentCategoryId;
});

onMounted(async () => {
  // Только для первой загрузки, если компонент не был в KeepAlive
  const currentCategoryId = route.params.category_id ?? null;
  category.value = await categoriesStore.findCategoryById(currentCategoryId);
  window.document.title = `${category.value?.name ?? 'Неизвестная категория'}`;
  yaMetrika.pushHit(route.path, {
    title: `${category.value?.name ?? 'Неизвестная категория'}`,
  });
});
</script>
