<script lang="ts" setup>
interface Props {
  visible?: boolean
  autoHide?: boolean
  autoHideDelay?: number
  icon?: string
  iconSize?: string
  width?: string
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  autoHide: true,
  autoHideDelay: 10000,
  icon: '/static/icons/gift.png',
  width: '600rpx',
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'hide': []
}>()

const internalVisible = ref(props.visible)
let hideTimer: number | null = null

// 监听 visible prop 变化
watch(() => props.visible, (newVal) => {
  internalVisible.value = newVal
  if (newVal && props.autoHide) {
    startAutoHideTimer()
  }
  else {
    clearAutoHideTimer()
  }
})

// 监听内部 visible 变化
watch(internalVisible, (newVal) => {
  emit('update:visible', newVal)
  if (!newVal) {
    emit('hide')
    clearAutoHideTimer()
  }
})

// 启动自动隐藏定时器
function startAutoHideTimer() {
  clearAutoHideTimer()
  if (props.autoHide && props.autoHideDelay > 0) {
    hideTimer = setTimeout(() => {
      hide()
    }, props.autoHideDelay)
  }
}

// 清除自动隐藏定时器
function clearAutoHideTimer() {
  if (hideTimer) {
    clearTimeout(hideTimer)
    hideTimer = null
  }
}

// 显示提示框
function show() {
  internalVisible.value = true
  if (props.autoHide) {
    startAutoHideTimer()
  }
}

// 隐藏提示框
function hide() {
  internalVisible.value = false
}

// 切换显示状态
function toggle() {
  if (internalVisible.value) {
    hide()
  }
  else {
    show()
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  clearAutoHideTimer()
})

// 暴露方法给父组件
defineExpose({
  show,
  hide,
  toggle,
})
</script>

<template>
  <view
    v-if="internalVisible"
    class="absolute bottom-full left-1/2 mb-20rpx transform rounded-full bg-black bg-opacity-80 px-20rpx py-12rpx text-24rpx text-white -translate-x-1/2"
    :style="{ width }"
  >
    <view class="flex items-end justify-center">
      <image
        v-if="icon"
        :src="icon"
        class="mr-12rpx h-35rpx w-32rpx flex-shrink-0"
      />
      <view class="text-center">
        <text>{{ $t('productDetail.fullRefundText') }} </text>
      </view>
    </view>
    <!-- 倒三角箭头 -->
    <view
      class="absolute left-445rpx top-full h-0 w-0 -translate-x-1/2"
      style="border-left: 16rpx solid transparent; border-right: 16rpx solid transparent; border-top: 16rpx solid rgba(0, 0, 0, 0.8);"
    />
  </view>
</template>
