<!-- Страница списка моделей: топ-аватары, фильтры, сортировка, пагинация -->
<template>
  <div class="view-models _page _container">
    <header class="view-models__header">
      <SectionSwiperCards
        v-if="topCards.length >= MINIMUM_TOP_THUMBS"
        :items="topCards"
        class="view-models__popular"
        placeholder-avatar="/img/model-placeholder.webp"
        only-grid
      />

      <UiSectionTitle
        :count="data?.total"
        :title="h1"
        class="view-models__title"
        icon="user"
      />

      <div class="view-models__options">
        <LazySectionToolbar
          :sort-items="sortModels"
          hydrate-on-idle
        >
          <div class="section-toolbar__filter">
            <FilterBtn
              v-if="data && data.filters && data.filters.length"
              v-model="showFilters"
              :count="filterCount"
              class="view-models__filter-button"
              theme="primary"
            />
          </div>
        </LazySectionToolbar>
        <FilterSelects
          v-if="data && data.filters"
          :filters="data.filters"
        />
      </div>

      <LazyUiExpandRow
        v-if="!hideAlphabet"
        :class="{'_from-sm': !isSortByTitle && !letter}"
        :items="alphabetModelsItems"
        class="view-models__chips-panel"
        alphabet
        hydrate-on-idle
      >
        <template #prepend>
          <UiChips
            v-for="(item, index) in navigationChips"
            :key="`models-chips-${index}`"
            :item="item"
            :class="{ '--all': item.value === '' }"
            is-link
            alphabet
          />
        </template>
      </LazyUiExpandRow>

      <FilterModel
        v-if="data && data.filters && data.filters.length > 0 && (showFilters || filterCount > 0)"
        v-model="showFilters"
        :data="data"
        :status="status"
      />
    </header>

    <CategoryLetterGroups
      v-if="data && data.items?.length > 0 && isSortByTitle"
      :class="{'_loading': status === 'pending'}"
      :items="data.items"
      class="view-models__letter-groups"
      id="anchor"
    >
      <template #default="{ items }">
        <GridModels :items="items"/>
      </template>
    </CategoryLetterGroups>

    <template v-else-if="data && data.items?.length > 0">
      <UiLetter
        v-if="letter"
        :text="letter"
        class="view-models__letter-title"
      />
      <GridModels
        :class="{'_loading': status === 'pending'}"
        :items="data.items"
        class="view-models__grid"
        id="anchor"
        priority
      />
    </template>

    <div
      v-else-if="status === 'pending'"
      class="view-models__loading _loading"
    />
    <UiEmptyState
      without-reset
      v-else
    />

    <LazyUiPagination
      v-if="data"
      arrow-icon
      :key="`pagination-${data.allPages}`"
      :total="data.allPages"
      class="view-models__pagination _pagination"
      hydrate-on-visible
    />
  </div>
</template>

<script setup lang="ts">
import { sortModels, alphabetItems } from '../../lib';
import type {
  IModelCard,
  PaginatedResponse,
} from '../../types';
import { convertStringArrayToChips, convertModelToRoundCard } from '../../runtime';
import { computed } from 'vue';

const props = defineProps<{
  // TODO потом перейдем все равно на два запроса отдельных, отдельно фильтр и отдельно модели
  data: PaginatedResponse<IModelCard> | null,
  status: string,
  h1: string,
  topModelItems?: IModelCard[] | undefined,
  hideAlphabet?: boolean,
  letter?: string,
}>();

const { t } = useI18n();

const MINIMUM_TOP_VIDEOS_COUNT = 30;
const MINIMUM_TOP_THUMBS = 3;
const MAXIMUM_TOP_THUMBS = 12;

const showFilters = ref(false);
const route = useRoute();

const navigationChips = [
  {
    title: t('all'),
    value: '',
    prefix: 'models',
  },
  {
    title: '#',
    value: 'post',
    prefix: 'models/letter',
    resetPath: 'models'
  },
];

const alphabetModelsItems = convertStringArrayToChips(alphabetItems || {}, 'models/letter', 'models');

const filterCount = computed(() => {
  const filterKeys = Object.keys(route.query).filter(item => item.startsWith('filter'));
  const uniqueFilters = new Set(
      filterKeys.map(k => k.replace(/_(from|to)$/, ''))
  );

  return uniqueFilters.size;
});

const isFiltered = computed(() => filterCount.value > 0);
const isSortByTitle = computed(() => route.query.sort === 'title');

const filteredTopFromData = computed(() =>
    (props.data?.items || [])
        .filter(item => item.videosCount >= MINIMUM_TOP_VIDEOS_COUNT)
        .slice(0, MAXIMUM_TOP_THUMBS)
);

const topCards = computed(() => {
  if (isFiltered.value || props.letter) {
    return filteredTopFromData.value.map(convertModelToRoundCard);
  }
  return props.topModelItems?.map(convertModelToRoundCard) || [];
});
</script>

<style lang="scss">
.view-models__header {
  display: grid;
  gap: 16px;
  align-items: center;
  margin-bottom: 24px;

  @include from-br(sm) {
    justify-items: start;
  }
}

.view-models__pagination {
  margin-top: 32px;
}

.view-models__grid {
  margin-bottom: 48px;
}

.view-models__letter-title {
  margin-bottom: 12px;
}

.view-models__letter-groups {
  margin-bottom: 48px;
}

.view-models__options {
  display: grid;
  align-items: start;
  column-gap: 4px;
  row-gap: 8px;

  @include from-br(md) {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    justify-content: space-between;
  }
}

.view-models__options:has(+ .filter-model) {
  margin-bottom: 0;
}

.view-models__popular {
  padding-bottom: 16px;
  border-bottom: 1px solid $page-models-popular-border;
}
</style>
