<script setup>
import { ref, watch, onUnmounted, computed } from 'vue'
import { useEventListener } from '@vueuse/core'
import { useTheme } from 'vuetify'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  qrCode: {
    type: String,
    required: true,
    validator: value => {
      // 允许空值用于初始化状态
      if (!value) return true
      // 扩展支持的路径格式
      return (
        value.startsWith('/') ||
        value.startsWith('http') ||
        value.startsWith('data:image') ||
        value.startsWith('@/') ||
        value.startsWith('src/') ||      // 添加 src/ 路径支持
        value.includes('base64')        // 允许包含 base64 的字符串
      )
    }
  },
  title: {
    type: String,
    default: '微信扫码添加'
  },
  hint: {
    type: String,
    default: '打开微信扫一扫，添加我为好友'
  },
  duration: {
    type: Number,
    default: 0,
    validator: value => value >= 0
  },
  closeOnClickOutside: {
    type: Boolean,
    default: true
  },
  closeOnEsc: {
    type: Boolean,
    default: true
  },
  showCloseButton: {
    type: Boolean,
    default: true
  },
  zIndex: {
    type: Number,
    default: 9999
  }
})

const emit = defineEmits([
  'update:modelValue',
  'closed',
  'opened',
  'qr-loaded',
  'qr-error'
])

const theme = useTheme()
const modalRef = ref(null)
const qrLoaded = ref(false)
let autoCloseTimer = null

const computedStyles = computed(() => ({
  zIndex: props.zIndex
}))

// 关闭模态框
const closeModal = () => {
  clearTimeout(autoCloseTimer)
  emit('update:modelValue', false)
  emit('closed')
}

// 点击外部关闭
const handleClickOutside = (event) => {
  if (
    props.closeOnClickOutside && 
    modalRef.value && 
    !modalRef.value.contains(event.target)
  ) {
    closeModal()
  }
}

// ESC键关闭
const handleKeydown = (event) => {
  if (props.closeOnEsc && event.key === 'Escape') {
    closeModal()
  }
}

// 自动关闭定时器
const startAutoCloseTimer = () => {
  if (props.duration > 0) {
    autoCloseTimer = setTimeout(() => {
      closeModal()
    }, props.duration)
  }
}

// 图片加载处理
const handleImageLoad = () => {
  qrLoaded.value = true
  emit('qr-loaded')
  startAutoCloseTimer()
}

const handleImageError = () => {
  console.error('微信二维码加载失败')
  emit('qr-error')
}

// 监听显示状态变化
watch(() => props.modelValue, (val) => {
  if (val) {
    qrLoaded.value = false
    emit('opened')
    document.body.style.overflow = 'hidden'
    document.documentElement.style.paddingRight = 
      window.innerWidth - document.documentElement.clientWidth + 'px'
  } else {
    document.body.style.overflow = ''
    document.documentElement.style.paddingRight = ''
  }
}, { immediate: true })

// 注册事件监听
useEventListener(document, 'mousedown', handleClickOutside)
useEventListener(document, 'keydown', handleKeydown)

// 组件卸载时清理
onUnmounted(() => {
  clearTimeout(autoCloseTimer)
  document.body.style.overflow = ''
  document.documentElement.style.paddingRight = ''
})
</script>

<template>
  <Transition name="wechat-modal">
    <div 
      v-if="modelValue"
      class="wechat-modal-mask"
      :class="{ 'dark-mode': theme.global.name.value === 'dark' }"
      :style="computedStyles"
    >
      <div 
        ref="modalRef"
        class="wechat-modal-container"
        role="dialog"
        aria-modal="true"
        :aria-label="title"
      >
        <div class="wechat-modal-header">
          <h3 class="modal-title">{{ title }}</h3>
          <button 
            v-if="showCloseButton"
            class="modal-close-btn"
            @click="closeModal"
            aria-label="关闭微信二维码弹窗"
          >
            <i class="ri-close-line"></i>
          </button>
        </div>

        <div class="wechat-modal-body">
          <div class="qr-code-wrapper">
            <img 
              :src="qrCode" 
              alt="微信二维码"
              class="qr-code-image"
              :class="{ 'loaded': qrLoaded }"
              loading="lazy"
              @load="handleImageLoad"
              @error="handleImageError"
            >
            <div v-if="!qrLoaded" class="qr-code-loader">
              <div class="loader-spinner"></div>
            </div>
          </div>
          <p class="qr-hint">{{ hint }}</p>
        </div>

        <div class="wechat-modal-footer">
          <div class="scan-animation" v-if="qrLoaded"></div>
          <p class="footer-text">长按识别二维码</p>
        </div>
      </div>
    </div>
  </Transition>
</template>

<style scoped>
.wechat-modal-mask {
  position: fixed;
  z-index: v-bind('zIndex');
  inset: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: grid;
  place-items: center;
  backdrop-filter: blur(8px);
  transition: opacity 0.3s ease;
  isolation: isolate;
}

.dark-mode.wechat-modal-mask {
  background-color: rgba(0, 0, 0, 0.8);
}

.wechat-modal-container {
  position: relative;
  width: 400px;
  height: 400px;
  aspect-ratio: 1;
  background-color: var(--v-theme-surface);
  border-radius: 12px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transform: scale(0.95);
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  z-index: v-bind('zIndex + 1');
}

.wechat-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--v-theme-primary);
  color: white;
}

.modal-title {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 500;
}

.modal-close-btn {
  background: transparent;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.2s ease;
  padding: 4px;
  line-height: 1;
}

.modal-close-btn:hover {
  opacity: 1;
}

.wechat-modal-body {
  padding: 24px 20px;
  text-align: center;
}

.qr-code-wrapper {
  position: relative;
  padding: 12px;
  background: white;
  border-radius: 8px;
  display: inline-block;
  margin-bottom: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  width: 320px;
  height: 320px;
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-code-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
  transition: opacity 0.3s ease;
  opacity: 0;
  
  &.loaded {
    opacity: 1;
  }
}

.qr-code-loader {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loader-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(var(--v-theme-primary), 0.2);
  border-top-color: var(--v-theme-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.qr-hint {
  margin: 12px 0 0;
  color: var(--text-secondary);
  font-size: 0.95rem;
  line-height: 1.5;
}

.wechat-modal-footer {
  padding: 12px 20px;
  background-color: rgba(var(--v-theme-primary), 0.08);
  text-align: center;
  position: relative;
}

.scan-animation {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 40px);
  height: 4px;
  background: linear-gradient(
    to bottom,
    rgba(var(--v-theme-primary), 0.8),
    transparent
  );
  border-radius: 100%;
  animation: scan 2s infinite;
}

.footer-text {
  margin: 8px 0 0;
  color: var(--v-theme-primary);
  font-size: 0.9rem;
  font-weight: 500;
}

@keyframes scan {
  0% {
    top: -30px;
    opacity: 1;
  }
  80% {
    top: calc(100% - 30px);
    opacity: 0.8;
  }
  100% {
    top: calc(100% - 30px);
    opacity: 0;
  }
}

/* 独立卡片动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

@keyframes scaleUp {
  from {
    transform: scale(0.95) translateY(10px);
    opacity: 0;
  }
  to {
    transform: scale(1) translateY(0);
    opacity: 1;
  }
}

@keyframes scaleDown {
  from {
    transform: scale(1) translateY(0);
    opacity: 1;
  }
  to {
    transform: scale(0.95) translateY(10px);
    opacity: 0;
  }
}

/* 过渡动画 */
.wechat-modal-enter-active {
  animation: fadeIn 0.3s ease;
}

.wechat-modal-leave-active {
  animation: fadeOut 0.3s ease;
}

.wechat-modal-enter-active .wechat-modal-container {
  animation: scaleUp 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.wechat-modal-leave-active .wechat-modal-container {
  animation: scaleDown 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 响应式布局 */
@media (max-width: 360px) {
  .wechat-modal-container {
    width: 95vw;
    height: 95vw;
    margin: 10px;
  }
  .qr-code-wrapper {
    width: 80%;
    height: 80%;
    padding: 8px;
  }
}

@media (min-width: 361px) {
  .wechat-modal-container {
    width: min(420px, 90vw);
    margin: 20px;
  }
  .qr-code-wrapper {
    width: 280px;
    height: 280px;
  }
}

/* 减少运动偏好设置 */
@media (prefers-reduced-motion: reduce) {
  .wechat-modal-enter-active,
  .wechat-modal-leave-active,
  .wechat-modal-enter-active .wechat-modal-container,
  .wechat-modal-leave-active .wechat-modal-container,
  .wechat-modal-container,
  .wechat-modal-mask,
  .qr-code-image,
  .scan-animation,
  .loader-spinner {
    transition: none !important;
    animation: none !important;
  }
}
</style>