<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
import { productCardProps, productCardEmits } from "./product-card";
defineOptions({ name: "YhProductCard" });
const props = defineProps(productCardProps);
const emit = defineEmits(productCardEmits);
const ns = useNamespace("product-card");
const { t } = useLocale();
const { themeStyle } = useComponentTheme(
  "product-card",
  computed(() => props.themeOverrides)
);
const cardRef = ref(null);
let observer = null;
const hasExposed = ref(false);
const setupObserver = () => {
  if (!props.exposure || hasExposed.value) return;
  observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && entry.intersectionRatio >= props.exposureThreshold) {
          emit("expose");
          hasExposed.value = true;
          if (props.exposureOnce) observer?.disconnect();
        }
      });
    },
    { threshold: [props.exposureThreshold] }
  );
  if (cardRef.value) observer.observe(cardRef.value);
};
onMounted(setupObserver);
onUnmounted(() => observer?.disconnect());
watch(
  () => props.exposure,
  (val) => {
    if (val) {
      setupObserver();
    } else {
      if (observer) {
        observer.disconnect();
        observer = null;
      }
    }
  }
);
const currentImage = ref(props.image);
const isHovering = ref(false);
const videoActive = ref(false);
watch(
  () => props.image,
  (val) => {
    currentImage.value = val;
  }
);
const handleMouseEnter = () => {
  isHovering.value = true;
  if (props.hoverImage) currentImage.value = props.hoverImage;
  if (props.videoSrc) videoActive.value = true;
};
const handleMouseLeave = () => {
  isHovering.value = false;
  currentImage.value = props.image;
  if (props.videoSrc) videoActive.value = false;
};
const displayPrice = computed(() => {
  const p = Number(props.price);
  return isNaN(p) ? props.price : p.toFixed(2);
});
const displayMarketPrice = computed(() => {
  const p = Number(props.marketPrice);
  return isNaN(p) ? props.marketPrice : p.toFixed(2);
});
const displayVipPrice = computed(() => {
  const p = Number(props.vipPrice);
  return isNaN(p) ? props.vipPrice : p.toFixed(2);
});
const vipLabelText = computed(() => props.vipLabel || t("productcard.vip"));
const soldOutText = computed(() => t("productcard.soldOut"));
const actionText = computed(() => props.actionText || t("productcard.buyNow"));
const stockStyle = computed(() => ({
  width: `${Math.min(100, Math.max(0, props.stockProgress))}%`,
  background: props.stockColor || "var(--yh-color-primary)"
}));
const handleAction = (e) => {
  if (props.soldOut || props.actionLoading) return;
  emit("action", e);
};
const handleClick = (e) => {
  emit("click", e);
};
const badgeImageErrors = ref({});
const handleBadgeImageError = (idx) => {
  badgeImageErrors.value[idx] = true;
};
</script>

<template>
  <div
    ref="cardRef"
    :class="[ns.b(), ns.m(props.layout), ns.is('border', props.border), ns.is('shadow', props.shadow), ns.is('sold-out', props.soldOut)]"
    :style="[themeStyle, {
  '--yh-product-card-title-lines': props.titleLines,
  '--yh-product-card-desc-lines': props.descriptionLines
}]"
    @click="handleClick"
    @mouseenter="handleMouseEnter"
    @mouseleave="handleMouseLeave"
  >
    <div
      v-if="props.ribbon"
      :class="ns.e('ribbon')"
      :style="{
  backgroundColor: props.ribbonColor
}"
    >
      {{ props.ribbon }}
    </div>

    <div :class="ns.e('image-wrapper')">
      <img
        :src="currentImage"
        :alt="props.title"
        :class="ns.e('image')"
        :loading="props.lazy ? 'lazy' : 'eager'"
      />

      <Transition name="yh-fade">
        <div v-if="videoActive && props.videoSrc" :class="ns.e('video-overlay')">
          <video :src="props.videoSrc" autoplay muted loop playsinline :class="ns.e('video')" />
        </div>
      </Transition>

      <div v-if="props.soldOut" :class="ns.e('sold-out-mask')">
        <span :class="ns.e('sold-out-text')">{{ soldOutText }}</span>
      </div>
    </div>

    <div :class="ns.e('content')">
      <div
        v-if="(props.tag || props.badges.length) && props.badgePosition === 'top'"
        :class="ns.e('badges')"
      >
        <span v-if="props.tag" :class="[ns.e('badge-tag'), ns.is(props.tagType)]">{{
          props.tag
        }}</span>
        <template v-for="(badge, idx) in props.badges" :key="idx">
          <span v-if="badge.image && !badgeImageErrors[idx]" :class="ns.e('badge-img-wrap')">
            <img
              :src="badge.image"
              :class="ns.e('badge-img')"
              alt="badge"
              @error="handleBadgeImageError(idx)"
            />
          </span>
          <span
            v-if="badge.text"
            :class="[ns.e('badge-tag'), ns.is(badge.type || 'primary')]"
            :style="{
  backgroundColor: badge.color
}"
            >{{ badge.text }}</span
          >
        </template>
      </div>

      <h3 :class="ns.e('title')" :title="props.title">
        <span
          v-if="(props.tag || props.badges.length) && props.badgePosition === 'inline'"
          :class="[ns.e('badges'), ns.is('inline')]"
        >
          <span v-if="props.tag" :class="[ns.e('badge-tag'), ns.is(props.tagType)]">{{
            props.tag
          }}</span>
          <template v-for="(badge, idx) in props.badges" :key="idx">
            <span v-if="badge.image && !badgeImageErrors[idx]" :class="ns.e('badge-img-wrap')">
              <img
                :src="badge.image"
                :class="ns.e('badge-img')"
                alt="badge"
                @error="handleBadgeImageError(idx)"
              />
            </span>
            <span
              v-if="badge.text"
              :class="[ns.e('badge-tag'), ns.is(badge.type || 'primary')]"
              :style="{
  backgroundColor: badge.color
}"
              >{{ badge.text }}</span
            >
          </template>
        </span>
        <slot name="title">{{ props.title }}</slot>
      </h3>

      <div
        v-if="props.description || $slots.description"
        :class="ns.e('description')"
        :title="props.description"
      >
        <slot name="description">{{ props.description }}</slot>
      </div>

      <div :class="ns.e('price-row')">
        <div :class="ns.e('main-price')">
          <span :class="ns.e('currency')">{{ props.currency }}</span>
          <span :class="ns.e('price-val')">{{ displayPrice }}</span>
          <span v-if="props.unit" :class="ns.e('unit')">{{ props.unit }}</span>
        </div>

        <div v-if="props.vipPrice" :class="ns.e('vip-row')">
          <span :class="ns.e('vip-label')">{{ vipLabelText }}</span>
          <span :class="ns.e('currency')">{{ props.currency }}</span>
          <span :class="ns.e('vip-price')">{{ displayVipPrice }}</span>
        </div>

        <div v-if="props.marketPrice" :class="ns.e('market-price')">
          {{ props.currency }}{{ displayMarketPrice }}
        </div>
      </div>

      <div v-if="props.stockProgress" :class="ns.e('stock-area')">
        <div :class="ns.e('stock-bar-bg')">
          <div :class="ns.e('stock-bar-inner')" :style="stockStyle" />
        </div>
        <span v-if="props.stockText" :class="ns.e('stock-text')">{{ props.stockText }}</span>
      </div>

      <div v-if="!props.readonly" :class="ns.e('footer')">
        <slot name="footer">
          <button
            :class="[ns.e('action-btn'), ns.is('loading', props.actionLoading), ns.is('disabled', props.soldOut)]"
            @click.stop="handleAction"
          >
            <span v-if="props.actionLoading" :class="ns.e('loading-spinner')" />
            {{ actionText }}
          </button>
        </slot>
      </div>
    </div>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-product-card {
  --yh-product-card-bg: var(--yh-bg-color-overlay);
  --yh-product-card-radius: var(--yh-radius-base);
  --yh-product-card-title-size: 15px;
  --yh-product-card-price-color: var(--yh-color-danger);
  --yh-product-card-vip-color: #f7d081;
  --yh-product-card-btn-bg: var(--yh-color-primary);
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: var(--yh-product-card-bg);
  border-radius: var(--yh-product-card-radius);
  overflow: hidden;
  transition: all var(--yh-transition-base);
  cursor: pointer;
}
.yh-product-card.is-border {
  border: 1px solid var(--yh-border-color-lighter);
}

.yh-product-card.is-shadow:hover {
  box-shadow: var(--yh-shadow-base);
  transform: translateY(-5px);
}

.yh-product-card.is-sold-out {
  cursor: not-allowed;
}
.yh-product-card.is-sold-out .yh-product-card__image {
  filter: grayscale(0.8);
  opacity: 0.8;
}

.yh-product-card.is-sold-out .yh-product-card__title {
  opacity: 0.6;
}

.yh-product-card.is-sold-out .yh-product-card__price-row {
  opacity: 0.6;
}

.yh-product-card__ribbon {
  position: absolute;
  top: 12px;
  right: -28px;
  z-index: 10;
  width: 100px;
  padding: 2px 0;
  background-color: var(--yh-color-danger);
  color: #fff;
  font-size: 11px;
  text-align: center;
  transform: rotate(45deg);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-weight: bold;
  pointer-events: none;
}

.yh-product-card__image-wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 1/1;
  overflow: hidden;
  background-color: var(--yh-fill-color-light);
}
.yh-product-card__image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--yh-transition-slow);
}

.yh-product-card__image-wrapper:hover .yh-product-card__image {
  transform: scale(1.08);
}

.yh-product-card__video-overlay {
  position: absolute;
  inset: 0;
  z-index: 5;
  background: rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  justify-content: center;
}
.yh-product-card__video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.yh-product-card__sold-out-mask {
  position: absolute;
  inset: 0;
  z-index: 8;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}
.yh-product-card__sold-out-text {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border: 2px solid #fff;
  padding: 4px 12px;
  border-radius: 4px;
  letter-spacing: 2px;
}

.yh-product-card__content {
  flex: 1;
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.yh-product-card__badges {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}
.yh-product-card__badges.is-inline {
  display: inline-flex;
  vertical-align: middle;
  margin-right: 8px;
  margin-bottom: 0;
}

.yh-product-card__badge-img-wrap {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  vertical-align: middle;
  overflow: hidden;
}

.yh-product-card__badge-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.yh-product-card__badge-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 16px;
  font-size: 10px;
  padding: 0 6px;
  border-radius: 2px;
  white-space: nowrap;
  font-weight: 500;
}
.yh-product-card__badge-tag.is-primary {
  background: var(--yh-color-primary-light-9);
  color: var(--yh-color-primary);
}

.yh-product-card__badge-tag.is-danger {
  background: var(--yh-color-danger-light-9);
  color: var(--yh-color-danger);
}

.yh-product-card__badge-tag.is-success {
  background: var(--yh-color-success-light-9);
  color: var(--yh-color-success);
}

.yh-product-card__badge-tag.is-warning {
  background: var(--yh-color-warning-light-9);
  color: var(--yh-color-warning);
}

.yh-product-card__badge-tag.is-info {
  background: var(--yh-color-info-light-9);
  color: var(--yh-color-info);
}

.yh-product-card__title {
  margin: 0;
  font-size: var(--yh-product-card-title-size);
  color: var(--yh-text-color-primary);
  line-height: 1.4;
  font-weight: 500;
  display: -webkit-box;
  -webkit-line-clamp: var(--yh-product-card-title-lines, 2);
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.yh-product-card__description {
  font-size: 12px;
  color: var(--yh-text-color-secondary);
  display: -webkit-box;
  -webkit-line-clamp: var(--yh-product-card-desc-lines, 1);
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.yh-product-card__price-row {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 4px;
}

.yh-product-card__main-price {
  color: var(--yh-product-card-price-color);
  display: flex;
  align-items: baseline;
  gap: 1px;
}
.yh-product-card__currency {
  font-size: 12px;
  font-weight: bold;
}

.yh-product-card__price-val {
  font-size: 20px;
  font-weight: bold;
  font-family: "Din", sans-serif;
}

.yh-product-card__unit {
  font-size: 11px;
  color: var(--yh-text-color-placeholder);
  margin-left: 2px;
}

.yh-product-card__vip-row {
  display: inline-flex;
  align-items: center;
  background: #1a1a1a;
  color: var(--yh-product-card-vip-color);
  padding: 0 6px;
  border-radius: 2px;
  font-size: 10px;
  width: fit-content;
}
.yh-product-card__vip-label {
  font-weight: bold;
  margin-right: 4px;
}

.yh-product-card__vip-price {
  font-weight: bold;
  font-family: "Din";
}

.yh-product-card__market-price {
  font-size: 11px;
  color: var(--yh-text-color-placeholder);
  text-decoration: line-through;
}

.yh-product-card__stock-area {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}
.yh-product-card__stock-bar-bg {
  flex: 1;
  height: 6px;
  background: var(--yh-fill-color-darker);
  border-radius: 10px;
  overflow: hidden;
}

.yh-product-card__stock-bar-inner {
  height: 100%;
  border-radius: 10px;
  transition: width var(--yh-transition-slow) ease-in-out;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) inset;
}

.yh-product-card__stock-text {
  font-size: 10px;
  color: var(--yh-text-color-secondary);
  flex-shrink: 0;
}

.yh-product-card__footer {
  margin-top: 8px;
}

.yh-product-card__action-btn {
  width: 100%;
  height: 36px;
  border: none;
  background-color: var(--yh-product-card-btn-bg);
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: filter var(--yh-transition-fast);
}
.yh-product-card__action-btn:hover {
  filter: brightness(1.1);
}
.yh-product-card__action-btn:active {
  filter: brightness(0.9);
}
.yh-product-card__action-btn.is-disabled {
  background: var(--yh-fill-color-dark) !important;
  cursor: not-allowed;
  filter: none;
}

.yh-product-card__action-btn.is-loading {
  cursor: wait;
  opacity: 0.8;
}

.yh-product-card__loading-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: #fff;
  border-radius: 50%;
  animation: yh-rotate 0.8s linear infinite;
}

.yh-product-card {
  /* --- 布局适配 --- */
}
.yh-product-card--horizontal {
  flex-direction: row;
  height: 160px;
}
.yh-product-card--horizontal .yh-product-card__image-wrapper {
  width: 160px;
  height: 100%;
}

.yh-product-card--horizontal .yh-product-card__content {
  padding: 12px 16px;
  justify-content: space-between;
}

.yh-product-card--horizontal .yh-product-card__action-btn {
  width: auto;
  padding: 0 24px;
  align-self: flex-end;
}

.yh-product-card--compact .yh-product-card__content {
  padding: 8px;
  gap: 4px;
}

.yh-product-card--compact .yh-product-card__title {
  font-size: 13px;
  -webkit-line-clamp: 1;
}

.yh-product-card--compact .yh-product-card__description {
  font-size: 11px;
  opacity: 0.8;
}

.yh-product-card--compact .yh-product-card__price-val {
  font-size: 16px;
  font-weight: 600;
}

.yh-product-card--compact .yh-product-card__footer {
  margin-top: 4px;
}

.yh-product-card--compact .yh-product-card__action-btn {
  height: 26px;
  font-size: 12px;
}

@keyframes yh-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
@keyframes yh-fade {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
