<template>
  <div class="category">
    <ui-title>{{ category?.name }}</ui-title>
    <div class="container">
      <div class="category__wrapper">
        <div class="category__list" v-if="category?.children?.length">
          <cards-category
              v-for="cat in category?.children || []"
              :key="cat.uuid"
              :category="cat"
          />
        </div>
        <store v-else />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type {ICategory} from "~/types";
import {usePageTitle} from "~/composables/utils";

const route = useRoute()
const categoryStore = useCategoryStore()

const { setPageTitle } = usePageTitle()

const slug = computed(() => route.params.slug as string)
const roots = computed(() => categoryStore.categories.map(e => e.node))

const category = computed(() => findBySlug(roots.value, slug.value))

setPageTitle(category.value?.name ?? 'Category')

function findBySlug(nodes: ICategory[], slug: string): ICategory | undefined {
  for (const n of nodes) {
    if (n.slug === slug) return n
    if (n.children?.length) {
      const found = findBySlug(n.children, slug)
      if (found) return found
    }
  }
}
</script>

<style scoped lang="scss">
.category {
  &__list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-gap: 20px;
  }
}
</style>