<script setup lang="ts">
import { ref } from 'vue';
// @ts-expect-error swiper 模块导出与类型声明解析
import { Navigation, Pagination } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

export type MediaItem = { type: 'image' | 'video'; url: string };

defineProps<{
  mediaList: MediaItem[];
  initialIndex: number;
}>();

const carouselRef = ref<HTMLElement | null>(null);
const swiperModules = [Navigation, Pagination];

function onSlideChange() {
  carouselRef.value?.querySelectorAll('video').forEach((v) => v.pause());
}
</script>

<template>
  <div ref="carouselRef" class="review-preview-carousel">
    <swiper
      v-if="mediaList?.length"
      :modules="swiperModules"
      :initial-slide="initialIndex"
      :slides-per-view="1"
      :space-between="0"
      navigation
      pagination
      class="review-preview-swiper"
      @slide-change="onSlideChange"
    >
      <swiper-slide v-for="(media, i) in mediaList" :key="i" class="review-preview-slide">
        <div v-if="media.type === 'image'" class="review-preview-inner">
          <img :src="media.url" alt="" class="review-preview-img" />
        </div>
        <div v-else class="review-preview-inner review-preview-video-wrap">
          <video :src="media.url" controls class="review-preview-video" />
        </div>
      </swiper-slide>
    </swiper>
  </div>
</template>

<style scoped lang="scss">
.review-preview-carousel {
  width: 100%;
  height: 70vh;
  min-height: 300px;

  .review-preview-swiper {
    width: 100%;
    height: 100%;
    --swiper-navigation-size: 36px;
    --swiper-theme-color: #1890ff;
  }

  .review-preview-slide {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #000;
    box-sizing: border-box;
  }

  .review-preview-inner {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
  }

  .review-preview-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }

  .review-preview-video-wrap {
    width: 100%;
    height: 100%;
  }

  .review-preview-video {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }

  :deep(.swiper-wrapper) {
    height: 100%;
  }

  :deep(.swiper-slide) {
    height: 100%;
  }

  :deep(.swiper-button-prev),
  :deep(.swiper-button-next) {
    color: #fff;
  }

  :deep(.swiper-pagination-bullet) {
    background: #fff;
    opacity: 0.5;
  }

  :deep(.swiper-pagination-bullet-active) {
    opacity: 1;
  }
}
</style>
