<template>
  <div class="brands">
    <ui-title>
      <h1>{{ t('brands.title') }}</h1>
      <p>{{ t('brands.text') }}</p>
      <div class="brands__top-search">
        <input
            type="text"
            inputmode="text"
            :placeholder="t('fields.brandsSearch')"
            v-model="searchInput"
        >
        <icon name="tabler:search" size="20" />
      </div>
    </ui-title>
    <div class="brands__main">
      <div class="container">
        <div class="brands__main-wrapper">
          <cards-brand
              v-for="brand in brands"
              :key="brand.node.uuid"
              :brand="brand.node"
          />
          <div v-if="pending" class="brands__loading">
            <skeletons-cards-brand
                v-for="idx in 8"
                :key="idx"
            />
          </div>
          <div class="brands__list-observer" ref="observer"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {usePageTitle} from "@composables/utils";
import {useBrands} from "@composables/brands";

const {t} = useI18n();

const observer = ref(null);
const name = useRouteQuery<string>('name', '');
const searchInput = ref<string>(name.value);

const { setPageTitle } = usePageTitle();
const { brands, pending, pageInfo, variables, getBrands } = useBrands({
  brandSearch: name.value
});

await getBrands();

useIntersectionObserver(
    observer,
    async ([{ isIntersecting }]) => {
      if (isIntersecting && pageInfo.value?.hasNextPage && !pending.value) {
        variables.brandAfter = pageInfo.value.endCursor;
        await getBrands();
      }
    },
);

const updateNameDebounced = useDebounceFn(() => {
  name.value = searchInput.value;
}, 500);
watch(searchInput, newVal => {
  updateNameDebounced();
});
watch(name, async (newVal) => {
  variables.brandName = newVal || '';
  variables.brandAfter = '';
  brands.value = [];
  await getBrands();
});

setPageTitle(t('breadcrumbs.brands'));
</script>

<style lang="scss" scoped>
.brands {
  &__main {
    background-color: $main;
    padding-block: 70px;
    border-top: 1px solid $border;

    &-wrapper {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 24px;
    }
  }
}
</style>