<!-- Инфо-карточка: аватар, заголовок, соцсети, описание, параметры -->
<template>
  <div
    :class="{
      '--model': type === 'model',
    }"
    class="info-main"
  >
    <div
      :class="{
        '--img': card.img,
      }"
      class="info-main__content"
    >
      <UiImg
        v-if="card.img"
        :src="currentImage"
        :alt="title"
        class="info-main__img"
        width="80"
        height="80"
        sizes="80px"
        @error="imageError = true"
      />

      <div class="info-main__header">
        <h1 class="info-main__title _truncate">{{ title }}</h1>
        <div class="info-main__header-wrapper">
          <UiCount
            class="info-main__count"
            icon="video-camera"
          >{{ videosCount || card.videosCount }}</UiCount>
          <UiBtn
            theme="muted"
            size="s"
            class="info-main__header-button"
            @click="isShareOpen = true"
          >
            <UiIcon
              name="share"
              size="16"
            />
            {{ t('share') }}
          </UiBtn>
          <UiFollowBtn
            v-if="featureFlags.FeatureFollowEnabled"
            :following="isFollowing"
            :name="title"
            class="info-main__header-follow"
            size="s"
            @toggle="onFollowClick"
          />
        </div>
      </div>

      <InfoSocials
        v-if="socialItems && socialItems.length > 0"
        :items="socialItems"
        :known-icons="knownIcons"
        class="info-main__social"
        icon-size="16"
      />
      <p
        v-if="card.akaNames"
        class="info-main__also"
      >
        <span class="info-main__also-title">{{ $t('also_known_as') }}&nbsp;</span>
        <span class="info-main__also-text">{{ card.akaNames }}</span>
      </p>
      <p
        v-if="card.birthSummary"
        class="info-main__born"
      >
        <UiIcon
          class="info-main__born-title-icon"
          name="geo"
          size="14"
        />
        <span class="info-main__born-text">{{ card.birthSummary }}</span>
        <img
          v-for="(item, index) in card.nationalityIsoCodes"
          :key="`nationalityIsoCodes-${index}`"
          :src="`/icons/flags/${item}.svg`"
          :alt="item"
          class="info-main__born-flag"
          width="20"
          height="14"
        >
      </p>
      <p
        v-if="cardDescription"
        class="info-main__description"
      >{{ cardDescription }}</p>
    </div>

    <div
      v-if="card.parameters && card.parameters.length > 0"
      class="info-main__parameters"
    >
      <div
        v-if="isParameterShow"
        class="info-main__parameters-wrapper"
      >
        <InfoGrid
          :groups="groupedParameters"
          :iso-codes="card.nationalityIsoCodes"
        />
      </div>
      <div class="info-main__parameters-wrapper">
        <button
          class="info-main__parameters-button"
          type="button"
          @click="showParameters"
        >
          {{ isParameterShow ? t('show_less') : t('show_more') }}
          <UiIcon
            :class="{'--more': isParameterShow}"
            class="info-main__parameters-button-icon"
            name="angle-down"
            size="12"
          />
        </button>
      </div>
    </div>

    <ShareMain v-model="isShareOpen">
      <template
        v-if="type"
        #card
      >
        <CardModelMini
          v-if="type === 'model'"
          :card="shareModelCard"
        />
        <CardChannelMini
          v-else-if="type === 'channel'"
          :card="shareChannelCard"
        />
        <CardCategoryMini
          v-else-if="type === 'category'"
          :card="shareCategoryCard"
        />
      </template>
    </ShareMain>
  </div>
</template>

<script setup lang="ts">
import { AuthSteps } from '../../runtime';
import type {
  ICardInfo,
  IGroupedParameter,
  ILinkItem,
  IModelCard,
  IChannelCard,
  ICategoryCard
} from '../../types';
import { AuthorizationApiService } from '../../services/api/authorization.service';
import { groupParametersByGroup } from '../../utils/info-main/group-parameters-by-group';

const { t } = useI18n();

const props = defineProps<{
  card: ICardInfo
  title?: string
  type?: 'model' | 'channel' | 'category'
  videosCount?: number
}>();

const groupedParameters = computed<IGroupedParameter[]>(() =>
  groupParametersByGroup(props.card.parameters ?? []),
);

const featureFlags = useRuntimeConfig().public.featureFlags;

const isShareOpen = ref(false);

const { isAuthorized } = useUser(AuthorizationApiService);
const { openAuthPopup } = useAuthPopup();
const isParameterShow = ref(false);

function showParameters() {
  isParameterShow.value = !isParameterShow.value;
}

const authPopupText = 'register_first';

/** Заглушка вместо ручки подписки: состояние живёт только в компоненте, на бэк ничего не уходит */
const isFollowing = ref(false);

function onFollowClick() {
  if (isAuthorized.value) {
    isFollowing.value = !isFollowing.value;
  } else {
    openAuthPopup(AuthSteps.Login, authPopupText);
  }
}

const placeholders: Record<string, string> = {
  model: '/img/model-placeholder.webp',
  channel: '/img/logo-placeholder.svg',
};
const placeholder = computed(() => placeholders[ props.type || 'channel' ]);
const imageError = ref(false);
const currentImage = computed(() => {
  if (imageError.value) return placeholder.value;
  return props.card.img || placeholder.value;
});

function getParameter(name: string) {
  return props.card.parameters?.find(p => p.name === name)?.values?.[ 0 ]?.name;
}

const shareModelCard = computed<IModelCard>(() => ({
  title: props.card.title,
  videosCount: props.card.videosCount,
  thumbUrl: props.card.img || '',
  guid: props.card.guid || '',
  parameters: [],
  country: props.card.nationalityIsoCodes || '',
  age: getParameter('age'),
}));

const shareChannelCard = computed<IChannelCard>(() => ({
  guid: props.card.guid || '',
  name: props.card.title,
  url: props.card.url || '',
  videosCount: props.card.videosCount,
  isNetwork: props.card.isNetwork || false,
  updated: props.card.updated || 0,
  avatarUrl: props.card.img || '',
  thumbUrl: props.card.img || '',
  description: props.card.description,
}));

const shareCategoryCard = computed<ICategoryCard>(() => ({
  guid: props.card.guid || '',
  name: props.card.title,
  title: props.card.miniCardTitle,
  videosCount: props.card.videosCount,
}));

const knownIcons = ['facebook', 'instagram', 'tiktok', 'twitter', 'x', 'youtube', 'snapchat'];

const cardDescription = computed(() => props.card?.description);

const title = computed(() => props.title || props.card?.title);

const socialItems = computed<ILinkItem[]>(() => {
  return Object.entries(props.card?.social || {}).map(([key, value]: [string, string]) => ({
    name: value,
    title: key,
    icon: key,
  }));
});
</script>

<style lang="scss">
.info-main.--model {
  border: 1px solid $info-border;
  border-radius: $radius-xl;
  background-color: $info-bg;
}

.info-main__content {
  display: grid;
  column-gap: 16px;
  align-content: start;
  align-items: start;
}

.info-main.--model .info-main__content {
  padding: 16px;

  @include from-br(sm) {
    padding: 20px;
  }

}

.info-main__content.--img {
  grid-template-columns: auto 1fr;
}

.info-main__img {
  border-radius: $radius-full;
  object-fit: cover;
  background-color: $info-img-bg;
  border: 2px solid $info-img-border;

  @include to-br(sm) {
    margin-inline: auto;
    grid-row: 1/3;
  }

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

    width: var(--size);
    height: var(--size);
    grid-row: 1/6;
  }
}

.info-main__wrapper {
  display: grid;
  align-content: start;
}

.info-main__header-wrapper {
  @include to-br(sm) {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: start;
  }

  @include from-br(sm) {
    display: contents;
    column-gap: 12px;
  }
}

.info-main__header {
  display: grid;
  column-gap: 12px;
  row-gap: 8px;
  align-items: center;

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

.info-main__title {
  @include font-lg;

  font-weight: 700;
  text-transform: uppercase;
  overflow-wrap: break-word;
}

.info-main__title._truncate {
  @include to-br(sm) {
    display: block !important;
    animation: none;
  }
}

.info-main__count {
  padding: 7px 12px;
  flex-shrink: 0;
}

.info-main__social {
  margin-top: 8px;
  grid-column: 2;
}

.info-main__description {
  @include font-sm;

  margin-top: 12px;
  line-height: 1.625;
  color: $info-description;

  @include to-br(sm) {
    grid-column: 1/-1;
  }
}

.--avatar .info-main__description {
  @include from-br(sm) {
    grid-column: 2;
  }
}

.info-main__parameters-wrapper {
  padding: 20px;
  border-top: 1px solid $info-parameters-border;

  @include from-br(sm) {
    grid-column: 1/-1;
  }
}

.info-main__parameters-button {
  @include font-sm;

  display: flex;
  margin: 0 auto;
  align-items: center;
  flex-wrap: nowrap;
  column-gap: 4px;
  color: $info-parameters-text;

  @include hover(color) {
    color: $info-parameters-text--hover;
  }
}

.info-main__parameters-button-icon {
  transition: var(--transition) transform;
}

.info-main__parameters-button-icon.--more {
  transform: rotate(180deg);
}

.info-main__also {
  @include font-sm;

  color: $info-parameters-also;
  margin-top: 16px;

  @include to-br(sm) {
    grid-column: 1/-1;
  }
}

.info-main__also-title {
  color: $info-parameters-also-title;
}

.info-main__born {
  @include font-sm;

  color: $info-parameters-born;
  margin-top: 8px;

  @include to-br(sm) {
    grid-column: 1/-1;
  }
}

.info-main__born-title {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  column-gap: 6px;
}

.info-main__born-title-icon {
  display: inline-block;
  margin-right: 6px;
  color: $info-parameters-born-icon;
  vertical-align: middle;
}

.info-main__born-text {
  display: inline;
  vertical-align: middle;
}

.info-main__born-flag {
  display: inline;
  margin-left: 6px;
  vertical-align: middle;
}

.info-main__header-button {
  @include button-variant(info-button);
}

.info-main__header-follow {
  @include to-br(sm) {
    margin-inline-start: auto;
  }
}
</style>
