<!-- Список видео плейлиста: выбранное видео, режимы воспроизведения, меню -->
<template>
  <div class="player-playlist">
    <div class="player-playlist__wrapper">
      <header class="player-playlist__header">
        <h2 class="player-playlist__title">{{ title }}</h2>
        <span class="player-playlist__user-name">{{ `${$t('by')} ${user}` }}</span>
        <div class="player-playlist__middle">
          <UiBtn
            v-if="featureFlags.FeatureFollowEnabled"
            theme="muted"
            size="s"
            class="player-playlist__middle-button"
            @click="onFollowClick"
          >
            <UiIcon
              name="user-group"
              size="16"
            />
            {{ $t('follow') }}
          </UiBtn>
          <UiBtn
            theme="muted"
            size="s"
            class="player-playlist__middle-button"
            @click="isShareOpen = true"
          >
            <UiIcon
              name="share"
              size="16"
            />
            {{ $t('share') }}
          </UiBtn>
          <PlayerLike
            :dislikes="dislikes"
            :likes="likes"
            class="player-playlist__like"
            :id="playlistId"
            bar
            mini
          />
        </div>

        <UiExpandRow
          v-if="chipsTags && chipsTags.length > 0"
          :items="chipsTags"
          class="player-playlist__chips"
          mini
        />

        <div class="player-playlist__now-wrapper">
          <p class="player-playlist__now">
            {{ $t('now_playing') }}:&nbsp;
            <span class="player-playlist__now-value">{{ currentIndex }}/{{ visibleItems.length }}</span>
          </p>
          <div class="player-playlist__play-buttons">
            <button
              :class="{'--active': playMode === 'cycle'}"
              class="player-playlist__play-button"
              type="button"
              @click="setPlayMode('cycle')"
            >
              <UiIcon
                name="cycle"
                size="16"
              />
            </button>
            <button
              :class="{'--active': playMode === 'random'}"
              class="player-playlist__play-button"
              type="button"
              @click="setPlayMode('random')"
            >
              <UiIcon
                name="random"
                size="16"
              />
            </button>
          </div>
        </div>
      </header>
      <div
        ref="container"
        class="player-playlist__list"
      >
        <div
          v-for="(item, index) in visibleItems"
          :key="`playlist-card-${index}`"
          class="player-playlist__card"
        >
          <UiIcon
            v-if="String(item.id) === String(slug)"
            name="play"
            size="16"
            class="player-playlist__card-play"
          />
          <span
            v-else
            class="player-playlist__card-count"
          >{{ index + 1 }}</span>
          <CardVideoMini
            :card="item"
            :prefix="playlistId"
            class="player-playlist__card-mini"
            link
          />
          <CardDropdownTrigger
            :top="topDropdownIndex === index"
            :card="item"
            :show-remove="isOwner"
            class="player-playlist__card-dropdown"
            show-share
            show-report
            @share="onShareClick(item)"
            @remove="openPlaylistEdit(PlaylistStep.DeleteVideo, false, undefined, item)"
            @click="onDotsClick($event, index)"
          />
        </div>
      </div>
    </div>

    <ShareMain v-model="isShareOpen">
      <template #card>
        <CardPlaylistMini :card="sharePlaylistCard"/>
      </template>
    </ShareMain>

    <ShareMain
      v-model="isVideoShareOpen"
      :url="videoShareUrl"
    >
      <template #card>
        <CardVideoMini
          v-if="videoShareCard"
          :card="videoShareCard"
        />
      </template>
    </ShareMain>

  </div>
</template>

<script setup lang="ts">
import type { IVideoCard, IPlaylistCard, IProfileData } from '../../types';
import { AuthSteps, PlaylistStep, PlaylistType } from '../../runtime';
import { AuthorizationApiService } from '../../services/api/authorization.service';

const props = defineProps<{
  items: IVideoCard[]
  title: string
  playlistId: string
  user?: string
  tags?: string[]
  likes: number
  dislikes: number
}>();

const featureFlags = useRuntimeConfig().public.featureFlags;

const isShareOpen = ref(false);

const sharePlaylistCard = computed<IPlaylistCard>(() => ({
  id: props.playlistId,
  name: props.title,
  username: props.user || '',
  videosCount: props.items.length,
  thumbUrls: props.items.slice(0, 4).map(item => item.thumbUrls || { webp: {} }),
  created: 0,
  playlistType: PlaylistType.Public,
}));

const { isAuthorized } = useUser(AuthorizationApiService);
const { openAuthPopup } = useAuthPopup();
const { openPlaylistEdit, deletedVideo, isPlaylistEditOpen } = usePlaylistEdit();

const hiddenVideoIds = ref<Set<string>>(new Set());

watch(isPlaylistEditOpen, (open) => {
  if (!open && deletedVideo.value) {
    hiddenVideoIds.value.add(String(deletedVideo.value.id));
  }
});

const visibleItems = computed(() =>
    props.items.filter(item => !hiddenVideoIds.value.has(String(item.id)))
);
const userProfileData = computed(() => useState<IProfileData>('profileData').value);
const isOwner = computed(() => isAuthorized.value && !!userProfileData.value?.username && userProfileData.value.username === props.user);

const slug = useSlug();
const { mode: playMode, setMode: setPlayMode } = usePlaylistMode();

const currentIndex = computed(() => {
  const idx = visibleItems.value.findIndex(item => String(item.id) === String(slug.value));
  return idx >= 0 ? idx + 1 : 1;
});

const chipsTags = computed(() => props.tags?.map(item => ({
  value: item,
  title: item,
  prefix: 'tag'
})));

// const container = ref();
//
// onMounted(() => {
//   nextTick(() => {
//     requestAnimationFrame(() => {
//       const activeEl = document.querySelector('.router-link-active.card-video-mini') as HTMLElement;
//       const containerEl = container.value as HTMLElement;
//
//       if (activeEl && containerEl) {
//         const PADDING_TOP = 8;
//         const offset = activeEl.offsetTop - containerEl.offsetTop - PADDING_TOP;
//
//         containerEl.scrollTo({
//           top: offset,
//           behavior: 'smooth'
//         });
//       }
//     });
//   });
// });

// Dropdown position relative to scroll container
const container = ref<HTMLElement>();
const topDropdownIndex = ref<number | null>(null);
const MENU_HEIGHT_APPROX = 150;

function onDotsClick(event: Event, index: number) {
  const button = event.currentTarget as HTMLElement;
  const listEl = container.value;
  if (!listEl) return;

  const buttonRect = button.getBoundingClientRect();
  const listRect = listEl.getBoundingClientRect();
  const spaceBelow = listRect.bottom - buttonRect.bottom;

  topDropdownIndex.value = spaceBelow < MENU_HEIGHT_APPROX ? index : null;
}

// Video share from dropdown
const isVideoShareOpen = ref(false);
const videoShareCard = ref<IVideoCard | null>(null);

const videoShareUrl = computed(() => {
  if (!videoShareCard.value) return '';
  const videoPath = videoShareCard.value[ featureFlags.FetchByUrlEnabled ? 'url' : 'id' ];
  return `/videos/${videoPath}`;
});

function onShareClick(item: IVideoCard) {
  videoShareCard.value = item;
  isVideoShareOpen.value = true;
}

const authPopupText = 'register_first';

function onFollowClick() {
  if (isAuthorized.value) {
    console.log('чото делать');
  } else {
    openAuthPopup(AuthSteps.Login, authPopupText);
  }
}
</script>

<style lang="scss">
.player-playlist {
  display: flex;
  flex-direction: column;

  @include from-br(md) {
    height: 100%;
  }
}

.player-playlist__wrapper {
  background-color: $video-playlist-bg;
  border-radius: $radius-lg;
  border: 1px solid $video-playlist-border;
}

.player-playlist__wrapper .ui-expand-row__more-wrapper {
  background: linear-gradient(90deg, $video-playlist-row-shadow-start 0%, $video-playlist-row-shadow-end 22.64%);
}

.player-playlist__header {
  display: grid;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid $video-playlist-header-border;
}

.player-playlist__now-wrapper {
  @include font-sm;

  display: flex;
  justify-content: space-between;
  padding-top: 12px;
  border-top: 1px solid $video-playlist-now-border;
}

.player-playlist__now {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  column-gap: 4px;
  color: $video-playlist-now-text;
}

.player-playlist__now-value {
  color: $video-playlist-now-value;
}

.player-playlist__user-name {
  @include font-sm;

  color: $video-playlist-now-text;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin-bottom: 12px;
}

.player-playlist__title {
  @include font-base;

  margin-bottom: 4px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: $video-playlist-title-text;
  font-weight: 700;
}

.player-playlist__now,
.player-playlist__title {
  max-width: 100%;
}

.player-playlist__list {
  --card-height: 97px;

  overflow-y: auto;
  flex: 1;
  max-height: calc(var(--card-height) * 3);
  background-color: $video-playlist-list-bg;

  @include from-br(md) {
    aspect-ratio: 384/564;
    max-height: none;
  }

}

.player-playlist__card {
  padding: 8px;
  display: flex;
  column-gap: 8px;
  align-items: start;
  background-color: $video-playlist-card-bg;
  border-left: 2px solid $video-playlist-card-border;

  @include hover(background-color) {
    background-color: $video-playlist-card-bg--hover;
    border-color: $video-playlist-card-border--hover;
  }

  @include from-br(md) {
    cursor: pointer;
  }
}

.player-playlist__card-count {
  @include font-sm;

  color: $video-playlist-card-count-text;
}

.player-playlist__card-play,
.player-playlist__card-count {
  padding-top: 8px;
  width: 24px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 24px;
  text-align: center;
}

.player-playlist__card:has(.router-link-active) {
  background-color: $video-playlist-card-bg--active;
  border-color: $video-playlist-card-border--active;
  border-bottom-color: transparent;
}

.player-playlist__card:has(.router-link-active) .card-video-mini__title {
  color: $video-playlist-card-title--active;
}

.player-playlist__card-mini {
  column-gap: 8px;
  min-width: 0;
}

.player-playlist__card-mini .card-video-mini__img {
  width: 144px;
  border-radius: 4px;
}

.player-playlist__card-dropdown {
  flex-shrink: 0;
  align-self: center;
  margin-left: auto;

  @media (hover: hover) {
    opacity: 0;
    transition: var(--transition) opacity;
    color: $video-playlist-card-dropdown-text;
  }

  @include hover(color) {
    color: $video-playlist-card-dropdown-text--hover;
  }
}

.player-playlist__card:is(:hover, :focus-visible) .player-playlist__card-dropdown,
.player-playlist__card-dropdown.--open,
.player-playlist__card-dropdown:focus-within {
  @media (hover: hover) {
    opacity: 1;
  }
}

.player-playlist__chips {
  margin-bottom: 12px;
}

.player-playlist__play-buttons {
  display: flex;
  align-items: center;
  column-gap: 2px;
}

.player-playlist__play-button {
  padding: 6px;
  border-radius: 4px;
  color: $video-playlist-header-button-text;

  @include hover(background-color, color) {
    background-color: $video-playlist-header-button-bg--hover;
    color: $video-playlist-header-button-text--hover;
  }
}

.player-playlist__play-button.--active {
  color: $video-playlist-header-button-text--active;
  background-color: $video-playlist-header-button-bg--active;
}

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

.player-playlist__like {
  margin-left: auto;
}

.player-playlist__middle-button {
  @include button-variant(playlist-button)
}
</style>
