<template>
  <div class="player-interface">
    <div class="player-interface__header">
      <PlayerLike
        bar
        :video-md5="data.md5"
        :likes="data.likes"
        :dislikes="data.dislikes"
        class="player-interface__like"
      />
      <div class="player-interface__wrapper">
        <button
          :class="{'--favorite': isFavorite}"
          :aria-pressed="isFavorite"
          type="button"
          class="player-interface__button"
          @click="isFavorite = !isFavorite"
        >
          <UiIcon
            :name="isFavorite ? 'heart' : 'heart-stroke'"
            class="player-interface__button-icon"
            size="24"
          />
          <span class="player-interface__button-label _to-sm">{{ t('favorite') }}</span>
          <span class="player-interface__button-label _from-sm">{{ isFavorite ? t('favorite_remove') : t('favorite') }}</span>
        </button>
        <button
          type="button"
          class="player-interface__button"
          @click="onAddPlaylistClick"
        >
          <UiIcon
            class="player-interface__button-icon"
            name="playlist"
            size="24"
          />
          <span class="player-interface__button-label">{{ t('playlist.playlist') }}</span>
        </button>
        <button
          type="button"
          class="player-interface__button"
          @click="isShareOpen = true"
        >
          <UiIcon
            class="player-interface__button-icon"
            name="share"
            size="24"
          />
          <span class="player-interface__button-label">{{ t('share') }}</span>
        </button>
        <button
          type="button"
          class="player-interface__button"
          @click="openReportPopup(videoCard)"
        >
          <UiIcon
            class="player-interface__button-icon"
            name="flag"
            size="24"
          />
          <span class="player-interface__button-label">{{ t('report') }}</span>
        </button>
      </div>
    </div>
    <div
      :class="{'--show': showDescription}"
      class="player-interface__description"
    >
      <p
        v-if="data.description"
        ref="descriptionTextRef"
        class="player-interface__description-text _truncate"
      >{{
        data.description
      }}
      </p>
      <button
        v-if="data.description && isDescriptionOverflowing"
        :title="descriptionButtonText"
        type="button"
        class="player-interface__description-handler"
        @click="showDescription = !showDescription"
      >
        <UiIcon
          class="player-interface__description-icon"
          name="angle-down"
          size="20"
        />
      </button>
    </div>

    <ShareMain v-model="isShareOpen">
      <template #card>
        <CardVideoMini :card="videoCard"/>
      </template>
    </ShareMain>
  </div>
</template>

<script setup lang="ts">
import type { IVideoData } from '../../types';
import { AuthorizationApiService } from '../../services/api/authorization.service';

const props = defineProps<{
  data: IVideoData
}>();

const { t } = useI18n();

const showDescription = ref(false);
const descriptionTextRef = ref<HTMLParagraphElement>();
const isDescriptionOverflowing = ref(false);

const descriptionButtonText = computed(() => showDescription.value ? t('hide_description') : t('show_description'));

function checkDescriptionOverflow() {
  const el = descriptionTextRef.value;
  if (!el || showDescription.value) return;
  isDescriptionOverflowing.value = el.scrollHeight > el.clientHeight;
}

let descriptionObserver: ResizeObserver | null = null;

onMounted(() => {
  checkDescriptionOverflow();
  if (descriptionTextRef.value && 'ResizeObserver' in window) {
    descriptionObserver = new ResizeObserver(checkDescriptionOverflow);
    descriptionObserver.observe(descriptionTextRef.value);
  }
});

onBeforeUnmount(() => {
  descriptionObserver?.disconnect();
});

const videoCard = computed(() => ({
  guid: props.data.guid,
  title: props.data.header,
  duration: props.data.duration,
  thumbUrls: props.data.thumbUrls,
  md5: props.data.md5,
  views: props.data.views,
}));

const { openReportPopup } = useReportPopup();

const isShareOpen = ref(false);

const isFavorite = ref(false);

const { isAuthorized } = useUser(AuthorizationApiService);

function onAddPlaylistClick() {
  usePlaylistAdd().openPlaylistAdd(isAuthorized, props.data);
}
</script>

<style lang="scss">
.player-interface {
  display: grid;
  gap: 12px;
}

/* На мобиле лайк/дизлайк и кнопки действий — единый ряд из шести равных ячеек «иконка над
   подписью»: обе обёртки становятся `display: contents`, чтобы их кнопки легли прямо в грид
   заголовка. От sm возвращается десктопная раскладка — лайк-блок слева, пилюли справа. */
.player-interface__header {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 4px;
  padding-block: 12px;
  border-bottom: 1px solid $video-interface-mobile-border;

  @include from-br(sm) {
    display: flex;
    align-items: center;
    column-gap: 8px;
    justify-content: space-between;
    padding-block: 0;
    border-bottom: none;
  }
}

.player-like.player-interface__like {
  display: contents;

  @include from-br(sm) {
    display: flex;
  }
}

.player-interface__wrapper {
  display: contents;

  @include from-br(sm) {
    display: flex;
    align-items: center;
    column-gap: 8px;
  }
}

/* Нативный `<button>`, а не `<UiBtn>`: на мобиле у кнопки нет ни подложки, ни паддингов
   пилюли, а перебить геометрию `.ui-btn.--s` из компонента-потребителя можно только
   гонкой специфичности. Тему кнопка всё равно спрашивает через `button-variant()`. */
.player-interface__button {
  @include font-xs;

  display: grid;
  justify-items: center;
  row-gap: 6px;
  padding-block: 4px;
  border-radius: $radius-lg;
  color: $video-interface-mobile-icon;
  cursor: pointer;
  transition: var(--transition) opacity;

  @include from-br(sm) {
    @include font-sm;
    @include button-variant(interface-button);

    grid-auto-flow: column;
    align-items: center;
    row-gap: 0;
    column-gap: 6px;
    padding: 6px 12px;
    font-weight: 500;
    white-space: nowrap;
    background-color: var(--button-bg, #{$video-interface-button-bg});
    color: var(--button-text, #{$video-interface-button-text});
  }

  @include hover(background-color, color, opacity) {
    background-color: var(--button-bg--hover, #{$video-interface-button-bg--hover});
    color: var(--button-text--hover, #{$video-interface-button-text--hover});
  }
}

.player-interface__button:active {
  opacity: 0.7;
}

.player-interface__button.--favorite {
  @include from-br(sm) {
    background-color: $video-interface-button-bg--active;
    color: $video-interface-button-text--active;
  }
}

.player-interface__button-icon {
  $size: 24px;

  width: $size;
  height: $size;

  @include from-br(sm) {
    $size: 16px;

    width: $size;
    height: $size;
  }
}

.player-interface__button-label {
  color: $video-interface-mobile-label;

  @include from-br(sm) {
    color: inherit;
  }
}

.player-interface__description {
  display: grid;
  grid-template-columns: 1fr 20px;
  align-items: center;
  column-gap: 8px;
}

.player-interface__description-handler {
  height: 1lh;
  color: $video-info-handler-text;
  cursor: pointer;
}

.player-interface__description-icon {
  transition: var(--transition) transform;

  @include from-br(sm) {
    $size: 16px;

    width: $size;
    height: $size;
  }
}

.player-interface__description-text {
  @include font-sm;

  --line-clamp: 2;

  line-height: 1.625;
  color: $video-info-description-text;
}

.player-interface__description.--show .player-interface__description-text {
  --line-clamp: auto;
}

.player-interface__description.--show .player-interface__description-icon  {
  transform: rotate(180deg);
}
</style>
