<!-- История просмотров: фильтр по периоду, группировка по дням, очистка. Данные пока заглушка -->
<template>
  <div class="history _page _container">
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs"
    />

    <UiSectionTitle
      :title="t('watch_history')"
      :count="total"
      class="history__title"
      icon="history"
    />

    <div class="history__toolbar">
      <LazySectionToolbar
        :sort-items="historyPeriods"
        hydrate-on-idle
      >
        <div class="section-toolbar__filter">
          <FilterBtn
            v-model="isFilterOpen"
            :count="0"
            theme="primary"
          />
        </div>
      </LazySectionToolbar>

      <UiBtn
        :disabled="total === 0"
        :title="t('clear_history')"
        class="history__clear"
        theme="secondary"
        @click="isClearOpen = true"
      >
        <UiIcon
          name="trash-bin"
          size="16"
        />
        <span class="_from-sm">{{ t('clear_history') }}</span>
      </UiBtn>
    </div>

    <template v-if="groups.length > 0">
      <section
        v-for="(group, groupIndex) in groups"
        :id="groupIndex === 0 ? 'anchor' : undefined"
        :key="group.key"
        class="history__group"
      >
        <UiSectionTitle
          :title="getGroupTitle(group)"
          :count="n(group.items.length, 'compact')"
          class="history__group-header"
          icon="video-camera"
          title-tag="h2"
          variant="section"
        />

        <div class="history__grid">
          <CardVideo
            v-for="(item, index) in group.items"
            :key="`history-${item.guid}`"
            :card="item"
            :priority="groupIndex === 0 && index < 4"
            :loading="groupIndex === 0 && index < 4 ? 'eager' : 'lazy'"
            history
            @share="onShare"
            @remove="onRemove"
          />
        </div>
      </section>
    </template>

    <UiEmptyState
      v-else
      without-reset
    />

    <UiPagination
      v-if="allPages > 1"
      :key="`pagination-${allPages}`"
      :total="allPages"
      class="history__pagination _pagination"
      arrow-icon
    />

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

    <UiConfirm
      v-model="isClearOpen"
      :title="t('clear_watch_history')"
      :confirm-text="t('clear_all')"
      @confirm="onClearConfirm"
    >
      <p class="history__confirm">{{ t('clear_history_confirm') }}</p>
      <p class="history__confirm-undone">{{ t('clear_history_undone') }}</p>
      <i18n-t
        keypath="clear_history_hint"
        tag="p"
        scope="global"
        class="history__confirm-hint"
      >
        <NuxtLink
          :to="generateLink('/user/settings')"
          class="history__confirm-link"
        >{{ t('profile_settings') }}</NuxtLink>
      </i18n-t>
    </UiConfirm>
  </div>
</template>

<script setup lang="ts">
import { historyPeriods } from '../lib';
import { getHistoryStub } from '../stubs/history';
import { groupByWatchedDay } from '../utils/history/group-by-watched-day';
import type { HistoryDayGroup } from '../utils/history/group-by-watched-day';
import type { IBreadcrumbItem, IVideoCard } from '../types';

const PER_PAGE = 24;

const { t, n, locale } = useI18n();
const route = useRoute();

const isFilterOpen = ref(false);
const isClearOpen = ref(false);

const { generateLink } = useGenerateLink();

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

const allItems = computed(() => {
  if (isCleared.value) return [];
  return getHistoryStub(String(route.query['period'] || ''))
    .filter(item => !removedGuids.value.includes(item.guid));
});

const total = computed(() => allItems.value.length);
const allPages = computed(() => Math.ceil(total.value / PER_PAGE));

const items = computed(() => {
  const page = Math.min(Math.max(Number(route.query['page']) || 1, 1), allPages.value || 1);
  return allItems.value.slice((page - 1) * PER_PAGE, page * PER_PAGE);
});

const groups = computed(() => groupByWatchedDay(items.value));

function getGroupTitle(group: HistoryDayGroup) {
  if (group.key === 'today') return t('history_group.today');
  if (group.key === 'yesterday') return t('history_group.yesterday');

  return new Date(group.watchedAt * 1000).toLocaleDateString(locale.value, {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
}

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;
}

function onClearConfirm() {
  isCleared.value = true;
  isClearOpen.value = false;
}

useNoindex();

const { brandName } = useAppConfig();

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

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

<style lang="scss">
.history__title {
  margin-bottom: 24px;
}

.history__toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
  margin-bottom: 32px;
}

/* Тулбар несёт свой горизонтальный скролл на мобиле — без этого не даст себя сжать */
.history__toolbar .section-toolbar {
  min-width: 0;
}

.history__clear.ui-btn {
  flex-shrink: 0;
  margin-left: auto;
}

.history__group {
  margin-bottom: 40px;
}

.history__group-header {
  margin-bottom: 16px;
}

.history__grid {
  @include video-card-grid;

  position: relative;
}

.ui-pagination.history__pagination {
  margin-top: auto;
  margin-bottom: 40px;
}

.history__confirm {
  @include font-sm;

  margin-bottom: 8px;
  color: var(--page-history-confirm-text, #{$page-history-confirm-text});
}

.history__confirm-undone {
  @include font-sm;

  margin-bottom: 12px;
  color: var(--page-history-confirm-muted, #{$page-history-confirm-muted});
}

.history__confirm-hint {
  @include font-xs;

  color: var(--page-history-confirm-muted, #{$page-history-confirm-muted});
}

.history__confirm-link {
  color: $page-history-confirm-link;

  @include hover(color) {
    color: $page-history-confirm-link--hover;
  }
}

</style>
