<!-- Библиотека: «продолжить просмотр», коллекции и подписки. Данные пока заглушка -->
<template>
  <div class="library _page _container">
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs"
    />

    <div class="library__header">
      <h1 class="library__title _title">{{ t('navigation.library') }}</h1>

      <UiToggle
        v-model="saveHistory"
        class="library__save"
        left
      >{{ t('history_text') }}</UiToggle>
    </div>

    <section
      v-if="continueWatching.length > 0"
      class="library__section"
    >
      <header class="library__section-header">
        <UiSectionTitle
          :title="t('library.continue_watching')"
          icon="history"
          title-tag="h2"
          variant="section"
        />

        <UiLink
          :to="generateLink('/history')"
          theme="simple"
        >
          {{ t('library.history') }}
          <UiIcon
            name="arrow-right"
            size="16"
          />
        </UiLink>
      </header>

      <div class="library__continue">
        <CardVideo
          v-for="item in continueWatching"
          :key="`continue-${item.guid}`"
          :card="item"
          loading="eager"
          priority
          history
          remaining
          @share="onShare"
          @remove="onRemove"
        />
      </div>
    </section>

    <section class="library__section">
      <header class="library__section-header">
        <UiSectionTitle
          :title="t('library.collections')"
          icon="layers"
          title-tag="h2"
          variant="section"
        />
      </header>

      <ul class="library__grid">
        <li
          v-for="item in collections"
          :key="item.title"
        >
          <LibraryItem
            :to="item.to"
            :icon="item.icon"
            :title="item.title"
            :subtitle="item.subtitle"
          />
        </li>
      </ul>
    </section>

    <section class="library__section">
      <header class="library__section-header">
        <UiSectionTitle
          :title="t('library.following')"
          icon="plus"
          title-tag="h2"
          variant="section"
        />

        <UiLink
          :to="generateLink('/following')"
          theme="simple"
        >
          {{ t('library.whats_new', { count: newTotal }) }}
          <UiIcon
            name="arrow-right"
            size="16"
          />
        </UiLink>
      </header>

      <ul class="library__grid">
        <li
          v-for="item in following"
          :key="item.title"
        >
          <LibraryItem
            :to="item.to"
            :icon="item.icon"
            :title="item.title"
            :subtitle="item.subtitle"
            :avatars="item.avatars"
            :rest-count="item.restCount"
          />
        </li>
      </ul>
    </section>

    <ShareMain
      v-model="isShareOpen"
      :url="shareUrl"
    >
      <template #card>
        <CardVideoMini
          v-if="shareCard"
          :card="shareCard"
        />
      </template>
    </ShareMain>
  </div>
</template>

<script setup lang="ts">
import { getHistoryStub } from '../../stubs/history';
import { getLibraryChannelsStub, getLibraryModelsStub } from '../../stubs/library-follows';
import { libraryStub } from '../../stubs/library';
import type { IBreadcrumbItem, ILibraryItemAvatar, IVideoCard } from '../../types';

/** Карточка-ссылка библиотеки в разметке страницы. */
type LibraryLink = {
  to: string
  icon: string
  title: string
  subtitle?: string
  avatars?: ILibraryItemAvatar[]
  restCount?: number
};

const CONTINUE_LIMIT = 4;

/** Сколько аватарок помещается в ряд «что внутри» — остальные уходят в плашку «+N». */
const AVATARS_LIMIT = 4;

const { t } = useI18n();

const { generateLink } = useGenerateLink();

const saveHistory = ref(true);

const removedGuids = ref<string[]>([]);

/** Недосмотренные ролики: прогресс есть, но до конца не дошли. */
const continueWatching = computed(() => getHistoryStub()
  .filter(item => item.progress > 0 && item.progress < 100)
  .filter(item => !removedGuids.value.includes(item.guid))
  .slice(0, CONTINUE_LIMIT));

const newTotal = computed(() => libraryStub.newModels + libraryStub.newChannels + libraryStub.newPlaylists);

const collections = computed<LibraryLink[]>(() => [
  {
    to: generateLink('/library/favorites'),
    icon: 'heart-stroke',
    title: t('favorites'),
    subtitle: t('plural.videos', libraryStub.favorites),
  },
  {
    to: generateLink('/library/watch-later'),
    icon: 'clock',
    title: t('watch_later'),
    subtitle: t('plural.videos', libraryStub.watchLater),
  },
  {
    to: generateLink('/library/my-playlists'),
    icon: 'playlist',
    title: t('my_playlists'),
    subtitle: t('library.playlists_visibility', {
      privateCount: libraryStub.privatePlaylists,
      publicCount: libraryStub.publicPlaylists,
    }),
  },
  {
    to: generateLink('/history'),
    icon: 'history',
    title: t('history'),
    subtitle: t('library.watched_today', { count: libraryStub.watchedToday }),
  },
]);

/** Первые подписки раздела: ряд аватарок на карточке показывает, что внутри. */
const modelAvatars: ILibraryItemAvatar[] = getLibraryModelsStub()
  .slice(0, AVATARS_LIMIT)
  .map(model => ({ title: model.title, avatarUrl: model.avatarUrl }));

const channelAvatars: ILibraryItemAvatar[] = getLibraryChannelsStub()
  .slice(0, AVATARS_LIMIT)
  .map(channel => ({ title: channel.title, avatarUrl: channel.avatarUrl }));

const following = computed<LibraryLink[]>(() => [
  {
    to: generateLink('/library/models'),
    icon: 'user',
    title: t('models'),
    subtitle: t('plural.models', libraryStub.models),
    avatars: modelAvatars,
    restCount: Math.max(libraryStub.models - AVATARS_LIMIT, 0),
  },
  {
    to: generateLink('/library/channels'),
    icon: 'play-circle',
    title: t('channels'),
    subtitle: t('plural.channels', libraryStub.channels),
    avatars: channelAvatars,
    restCount: Math.max(libraryStub.channels - AVATARS_LIMIT, 0),
  },
  {
    to: generateLink('/library/categories'),
    icon: 'grid',
    title: t('categories'),
    subtitle: t('plural.categories', libraryStub.categories),
  },
  {
    to: generateLink('/library/playlists'),
    icon: 'playlist',
    title: t('playlists'),
    subtitle: t('plural.playlists', libraryStub.playlists),
  },
]);

function onRemove(card: IVideoCard) {
  removedGuids.value = [...removedGuids.value, card.guid];
}

const isShareOpen = ref(false);
const shareCard = ref<IVideoCard | null>(null);

const shareUrl = computed(() => shareCard.value ? generateLink(`/videos/${shareCard.value.id}`) : '');

function onShare(card: IVideoCard) {
  shareCard.value = card;
  isShareOpen.value = true;
}

useNoindex();

const { brandName } = useAppConfig();

useHead(() => ({
  title: `${t('navigation.library')} — ${brandName}`,
}));

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

<style lang="scss">
.library__header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  column-gap: 16px;
  row-gap: 12px;
  margin-bottom: 24px;
}

.library__title._title {
  margin-bottom: 0;
}

.library__save .ui-toggle__text {
  @include font-sm;

  color: $page-library-toggle-text;
}

.library__section {
  margin-bottom: 48px;
}

.library__section-header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  column-gap: 16px;
  row-gap: 12px;
  margin-bottom: 16px;
}

.library__continue {
  display: grid;
  gap: 16px;
  grid-template-columns: 1fr;

  @include from-br(xm) {
    grid-template-columns: repeat(2, 1fr);
  }

  @include from-br(sm) {
    gap: 24px;
    grid-template-columns: repeat(3, 1fr);
  }

  @include from-br(md) {
    grid-template-columns: repeat(4, 1fr);
  }
}

.library__grid {
  display: grid;
  gap: 16px;
  margin: 0;
  padding: 0;
  list-style: none;
  grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));

  @include from-br(sm) {
    gap: 24px;
    grid-template-columns: repeat(4, 1fr);
  }
}

/* Карточка тянется на всю высоту ряда — иначе соседи с двухстрочным тайтлом разной высоты. */
.library__grid > li {
  display: grid;
}
</style>
