<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"
          :style="{ height: heightCss }"
        >
          <div v-for="it in normalizedItems" :key="it.src" class="carousel-item" :style="{ height: heightCss }">
            <NuxtLink
              v-if="it.href && !isExternal(it.href)"
              :to="it.href"
              class="carousel-link"
              aria-label="carousel-slide"
            >
              <img class="carousel-img" :src="it.src" :alt="it.alt || 'slide'" loading="lazy" />
            </NuxtLink>
            <a
              v-else-if="it.href"
              class="carousel-link"
              :href="it.href"
              target="_blank"
              rel="noopener noreferrer"
              aria-label="carousel-slide"
            >
              <img class="carousel-img" :src="it.src" :alt="it.alt || 'slide'" loading="lazy" />
            </a>
            <img v-else class="carousel-img" :src="it.src" :alt="it.alt || 'slide'" loading="lazy" />
          </div>
        </a-carousel>

        <template #fallback>
          <img class="carousel-img" :style="{ height: heightCss }" :src="fallbackSrc" alt="slide" />
        </template>
      </ClientOnly>
    </div>
  </section>
</template>

<script setup lang="ts">
type CarouselItem = {
  src: string
  href?: string
  alt?: 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;
  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-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

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