<template>
  <section class="carousel-wrap">
    <div class="carousel-panel" :style="{ height: heightCss }">
      <ClientOnly>
        <a-carousel
          class="carousel"
          :autoplay="autoplayEnabled"
          :autoplay-speed="autoplaySpeed"
          :dots="dotsEnabled"
          :effect="effect"
        >
          <div v-for="it in normalizedItems" :key="it.src" class="carousel-item">
            <NuxtLink
              v-if="it.href && !isExternal(it.href)"
              :to="it.href"
              class="carousel-link"
              aria-label="carousel-slide"
            >
              <div class="carousel-bg" :style="{ backgroundImage: `url(${it.src})` }"></div>
            </NuxtLink>
            <a
              v-else-if="it.href"
              class="carousel-link"
              :href="it.href"
              target="_blank"
              rel="noopener noreferrer"
              aria-label="carousel-slide"
            >
              <div class="carousel-bg" :style="{ backgroundImage: `url(${it.src})` }"></div>
            </a>
            <div v-else class="carousel-bg" :style="{ backgroundImage: `url(${it.src})` }"></div>
          </div>
        </a-carousel>

        <template #fallback>
          <div class="carousel-bg" :style="{ height: heightCss, backgroundImage: `url(${fallbackSrc})` }"></div>
        </template>
      </ClientOnly>
    </div>
  </section>
</template>

<script setup lang="ts">
type CarouselItem = {
  src: string
  href?: string
}

const props = withDefaults(
  defineProps<{
    items: CarouselItem[]
    height?: number | string
    autoplaySpeed?: number
    effect?: 'scrollx' | 'fade'
  }>(),
  {
    height: 360,
    autoplaySpeed: 4500,
    effect: 'fade'
  }
)

const heightCss = computed(() => (typeof props.height === 'number' ? `${props.height}px` : props.height))

const normalizedItems = computed(() => (props.items || []).filter((it) => it && typeof it.src === 'string' && it.src))

const autoplayEnabled = computed(() => normalizedItems.value.length > 1)
const dotsEnabled = computed(() => normalizedItems.value.length > 1)

const fallbackSrc = computed(() => normalizedItems.value[0]?.src || '')

function isExternal(href: string) {
  return /^https?:\/\//i.test(href)
}
</script>

<style scoped>
.carousel-panel {
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
}

.carousel {
  height: 100%;
}

.carousel-item {
  height: 100%;
}

.carousel-link {
  display: block;
  height: 100%;
}

.carousel-bg {
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.carousel :deep(.slick-list),
.carousel :deep(.slick-track),
.carousel :deep(.slick-slide),
.carousel :deep(.slick-slide > div) {
  height: 100%;
}
</style>
