<template>
  <div
    v-if="publicData"
    class="playlists _page _container"
  >
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs"
    />

    <header class="playlists__header">
      <UiSectionTitle
        v-if="h1"
        :title="h1"
        :count="publicData.items.length"
        icon="playlist"
      />

      <UiLink
        :to="generateLink('/library/my-playlists')"
        theme="secondary"
        class="playlists__my-link"
      >
        <UiIcon
          name="playlist"
          size="16"
        />
        {{ $t('my_playlists') }}
        <span v-if="isMyPlaylistsLoaded">({{ myPlaylists.length }})</span>
        <UiIcon
          name="arrow-right"
          size="16"
        />
      </UiLink>
    </header>

    <SectionCollections :data-items="publicData.items"/>

    <UiSectionTitle
      :title="$t('user_playlists')"
      class="playlists__title"
      title-tag="h2"
      variant="section"
    />

    <SectionNavLinks
      :items="sortPlaylists"
      class="playlists__navigation"
      theme="secondary"
    />

    <div
      v-if="publicData.items?.length > 0"
      :class="{'_loading': status === 'pending'}"
      class="playlists__grid"
      id="anchor"
    >
      <GridPlaylists
        :items="publicData.items"
        priority
      />
    </div>

    <UiPagination
      :key="`pagination-${publicData.allPages}`"
      :total="publicData.allPages"
      class="playlists__pagination _pagination"
      arrow-icon
    />
    <SectionSeoText
      :text="t('playlists_footer_text')"
      links-link="playlists_footer_link"
    />
  </div>
  <div
    v-else
    class="_loading"
  />
</template>

<script setup lang="ts">
import { sortPlaylists } from '../../lib';
import type { IBreadcrumbItem } from '../../types';
import { PlaylistsApiService } from '../../services/api/playlists.service';

const { data: publicData, status } = await useFetchPlaylistsByNiche(PlaylistsApiService.getPlaylistByNiche);

const { t } = useI18n();

const { generateLink } = useGenerateLink();

const { items: myPlaylists, isLoaded: isMyPlaylistsLoaded } = useUserPlaylists();

const pagePureName = useGetPureRouteName();
const { meta, h1 } = useMeta({
  t,
  pageKey: pagePureName,
  brandName: useAppConfig().brandName,
  sortOptions: sortPlaylists,
});

watchEffect(() => {
  useHead(meta.value);
});

const breadcrumbs = [
  {
    name: `${t('navigation.main')}`,
    to: '/',
  },
  {
    name: `${t('navigation.playlists')}`,
  },
] as IBreadcrumbItem[];
</script>

<style lang="scss">
.playlists__header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  row-gap: 12px;
  margin-bottom: 32px;

  @include from-br(xm) {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    column-gap: 16px;
  }
}

.playlists__my-link {
  flex-shrink: 0;
}

.playlists__title {
  margin-bottom: 16px;
}

.playlists__navigation {
  margin-bottom: 32px;
}
</style>
