<!-- Чипсы фильтра видео (категории/длительность/дата) с парсингом из query -->
<template>
  <FilterChips
    :items="chipsItems"
    @click="(e: IChipsItem) => onChipsClick(e)"
  >
    <slot/>
  </FilterChips>
</template>

<script setup lang="ts">
import type { IChipsItem, ISelectItem, IFilterScheme } from '../../types';
import { parseFilterCategories } from '../../utils/parse-filter-categories';

const route = useRoute();
const router = useRouter();
const { t } = useI18n();

const props = defineProps<{
  addedItems: ISelectItem[]
  durationItems: ISelectItem[]
  scheme: IFilterScheme[]
}>();

const chipsItems = computed(() => {
  const items: IChipsItem[] = [];

  // categories
  const categories = parseFilterCategories(route.query);
  if (categories.length) {
    categories.forEach(cat => {
      const value = cat.split('_')[1] ?? cat;
      const groupCategory = cat.split('_')[0];
      const title = props.scheme.find(item => {
        return item.name.toLowerCase() === groupCategory.toLowerCase();
      })?.items.find((item: ISelectItem) => item.value === value)?.title;

      items.push({
        title: title || '',
        value: cat,
        key: 'categories'
      });
    });
  }

  // duration
  const durationParam = route.query.duration;
  if (durationParam) {
    const title = props.durationItems.find(item => item.value === durationParam)?.title;
    items.push({
      title: t(title || ''),
      value: String(durationParam),
      key: 'duration'
    });
  }

  // added
  const addedParam = route.query.added;
  if (addedParam) {
    const title = props.addedItems.find(item => item.value === addedParam)?.title;
    items.push({
      title: t(title || ''),
      value: String(addedParam),
      key: 'added'
    });
  }

  return items;
});

function onChipsClick(item: IChipsItem & { key?: string }) {
  const query = { ...route.query };

  if (item.key === 'categories') {
    const categories = parseFilterCategories(route.query);
    if (!categories.length) return;

    const updatedCategories = categories.filter(cat => cat !== item.value);

    if (updatedCategories.length > 0) {
      query.categories = updatedCategories.join(',');
    } else {
      delete query.categories;
    }
  }

  if (item.key === 'duration') {
    delete query.duration;
  }

  if (item.key === 'added') {
    delete query.added;
  }

  router.replace({ query });
}
</script>
