<template>
  <BaseViewWrapper title="Категории">
    <div v-if="categoriesStore.isLoading" class="flex flex-col gap-4">
      <div class="skeleton h-14 w-full"></div>
      <div class="skeleton h-14 w-full"></div>
      <div class="skeleton h-14 w-full"></div>
      <div class="skeleton h-14 w-full"></div>
      <div class="skeleton h-14 w-full"></div>
    </div>

    <template v-else>
      <button
          v-if="parentCategory && parentCategory.children?.length && settings.show_category_products_button"
          class="btn btn-soft btn-block btn-sm mb-3 justify-start"
          @click.prevent="showProductsInParentCategory"
      >
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5 shrink-0">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
        </svg>
        <span>Показать все товары категории</span>
      </button>

      <TransitionGroup
          name="stagger"
          tag="ul"
          appear
          class="space-y-3"
      >
        <li
            v-for="(category, i) in categories"
            :key="category.id"
            :style="{ '--i': i }"

        >
          <CategoryItem
              :category="category"
              @onSelect="onSelect"
              class="block transition hover:bg-base-100/60 will-change-transform"
          />
        </li>
      </TransitionGroup>
    </template>
  </BaseViewWrapper>
</template>

<script setup>
import {computed, onMounted} from "vue";
import {router} from "@/router.js";
import {useCategoriesStore} from "@/stores/CategoriesStore.js";
import {useRoute} from "vue-router";
import CategoryItem from "@/components/CategoriesList/CategoryItem.vue";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";
import {useSettingsStore} from "@/stores/SettingsStore.js";
import BaseViewWrapper from "@/views/BaseViewWrapper.vue";

const route = useRoute();
const categoriesStore = useCategoriesStore();
const yaMetrika = useYaMetrikaStore();
const settings = useSettingsStore();

const parentId = computed(() => route.params.id ? Number(route.params.id) : null);

// 🔧 Рекурсивный поиск по всему дереву
function findCategoryById(id, list = categoriesStore.categories) {
  if (id == null) return null;
  for (const cat of list) {
    if (cat.id === id) return cat;
    if (cat.children?.length) {
      const found = findCategoryById(id, cat.children);
      if (found) return found;
    }
  }
  return null;
}

const parentCategory = computed(() => findCategoryById(parentId.value));

// Если мы в корне — показываем корневые категории,
// если внутри — показываем детей найденной категории (или пустой массив, если не нашли)
const categories = computed(() => {
  if (!parentId.value) return categoriesStore.categories;
  return parentCategory.value?.children ?? [];
});

function onSelect(category) {
  if (!category?.children?.length) {
    router.push({name: "product.categories.show", params: {category_id: category.id}});
  } else {
    router.push({name: "category.show", params: {id: category.id}});
  }
}

function showProductsInParentCategory() {
  if (parentId.value != null) {
    router.push({name: "product.categories.show", params: {category_id: parentId.value}});
  }
}

onMounted(async () => {
  window.document.title = 'Каталог';
  yaMetrika.pushHit(route.path, {
    title: 'Каталог',
  });
  await categoriesStore.fetchCategories();
});
</script>

<style scoped>
/* Стаггер для элементов списка */
.stagger-enter-from,
.stagger-leave-to {
  opacity: 0;
  transform: translateY(8px) scale(0.98);
}
.stagger-enter-active {
  transition: opacity .28s ease, transform .28s cubic-bezier(.22,.61,.36,1);
  transition-delay: calc(var(--i) * 40ms); /* задержка по индексу */
}
.stagger-leave-active {
  position: absolute;           /* чтобы соседей не дёргало */
  width: 100%;
  transition: opacity .18s ease, transform .18s ease;
}
.stagger-move {
  transition: transform .28s ease; /* анимация перестановки элементов */
}
</style>