<template>
  <Teleport to="body">
    <div 
      v-if="visible" 
      class="image-gallery-modal"
      @click="handleModalClick"
    >
      <div class="image-gallery-container" @click="handleContainerClick">
        <!-- 关闭按钮 -->
        <button class="close-btn" @click="close">
          <Icon icon="tabler:x" />
        </button>
        
        <!-- 图片容器 -->
        <div class="image-wrapper">
          <img 
            :src="currentImage" 
            :alt="`图片 ${currentIndex + 1}`"
            class="gallery-image"
            @load="onImageLoad"
            @click="handleImageClick"
          />
          
          <!-- 左右切换按钮 -->
          <button 
            v-if="images.length > 1"
            class="nav-btn nav-left" 
            @click.stop="prevImage"
          >
            <Icon icon="tabler:chevron-left" />
          </button>
          <button 
            v-if="images.length > 1"
            class="nav-btn nav-right" 
            @click.stop="nextImage"
          >
            <Icon icon="tabler:chevron-right" />
          </button>
        </div>
        
        <!-- 图片索引 -->
        <div v-if="images.length > 1" class="image-index">
          {{ currentIndex + 1 }} / {{ images.length }}
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { Icon } from '@iconify/vue'

const props = defineProps<{
  images: string[]
  initialIndex?: number
}>()

const emit = defineEmits<{
  'close': []
}>()

const visible = ref(false)
const currentIndex = ref(0)
const imageLoaded = ref(false)

const currentImage = computed(() => {
  return props.images[currentIndex.value] || ''
})

// 打开图库
const open = (index = 0) => {
  currentIndex.value = Math.max(0, Math.min(index, props.images.length - 1))
  visible.value = true
  imageLoaded.value = false
}

// 关闭图库
const close = () => {
  visible.value = false
  emit('close')
}

// 上一张图片
const prevImage = () => {
  if (props.images.length <= 1) return
  currentIndex.value = currentIndex.value > 0 ? currentIndex.value - 1 : props.images.length - 1
  imageLoaded.value = false
}

// 下一张图片
const nextImage = () => {
  if (props.images.length <= 1) return
  currentIndex.value = currentIndex.value < props.images.length - 1 ? currentIndex.value + 1 : 0
  imageLoaded.value = false
}

const handleModalClick = (e: MouseEvent) => {
  if (e.target === e.currentTarget) {
    close()
  }
}

const handleContainerClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement
  
  if (target.tagName === 'BUTTON' || target.closest('button')) return
  if (target.classList.contains('image-index') || target.closest('.image-index')) return
  
  if (target.classList.contains('gallery-image')) {
    const img = target as HTMLImageElement
    const rect = img.getBoundingClientRect()
    const x = e.clientX - rect.left
    const width = rect.width
    
    if (x < width / 2) {
      prevImage()
    } else {
      nextImage()
    }
    return
  }
  
  // 其他区域关闭弹窗
  close()
}

// 处理图片点击（左右切换）
const handleImageClick = (e: MouseEvent) => {
  e.stopPropagation()
  const img = e.currentTarget as HTMLElement
  const rect = img.getBoundingClientRect()
  const x = e.clientX - rect.left
  const width = rect.width
  
  if (x < width / 2) {
    prevImage()
  } else {
    nextImage()
  }
}

// 图片加载完成
const onImageLoad = () => {
  imageLoaded.value = true
}

// 键盘事件处理
const handleKeydown = (e: KeyboardEvent) => {
  if (!visible.value) return
  
  switch (e.key) {
    case 'Escape':
      close()
      break
    case 'ArrowLeft':
      prevImage()
      break
    case 'ArrowRight':
      nextImage()
      break
  }
}

// 触摸事件处理（移动端滑动切换）
let touchStartX = 0
let touchEndX = 0

const handleTouchStart = (e: TouchEvent) => {
  if (e.touches.length === 1) {
    touchStartX = e.touches[0].clientX
  }
}

const handleTouchEnd = (e: TouchEvent) => {
  if (e.changedTouches.length === 1) {
    touchEndX = e.changedTouches[0].clientX
    handleSwipe()
  }
}

const handleSwipe = () => {
  const deltaX = touchEndX - touchStartX
  const threshold = 50
  
  if (Math.abs(deltaX) > threshold) {
    if (deltaX < 0) {
      nextImage() // 向左滑动，下一张
    } else {
      prevImage() // 向右滑动，上一张
    }
  }
}

// 监听props变化
watch(() => props.initialIndex, (newIndex) => {
  if (newIndex !== undefined && visible.value) {
    currentIndex.value = Math.max(0, Math.min(newIndex, props.images.length - 1))
  }
})

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  document.addEventListener('touchstart', handleTouchStart, { passive: true })
  document.addEventListener('touchend', handleTouchEnd, { passive: true })
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  document.removeEventListener('touchstart', handleTouchStart)
  document.removeEventListener('touchend', handleTouchEnd)
})

// 暴露方法
defineExpose({
  open,
  close
})
</script>

<style scoped>
.image-gallery-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  user-select: none;
  overflow: auto;
  transition: background 0.2s ease;
}

.image-gallery-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  max-width: 100vw;
  max-height: 100vh;
}

.image-wrapper {
  position: relative;
  display: inline-block;
  max-width: 90vw;
  max-height: 80vh;
  cursor: pointer;
}

.gallery-image {
  max-width: 100%;
  max-height: 100%;
  border: 5px solid #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: opacity 0.2s ease;
  opacity: 1;
  background: #fff;
  object-fit: contain;
  display: block;
}

/* 关闭按钮 */
.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10001;
  font-size: 20px;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: scale(1.1);
}

/* 导航按钮 */
.nav-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  height: 50px;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10001;
  font-size: 24px;
}

.nav-btn:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: translateY(-50%) scale(1.1);
}

.nav-left {
  left: -25px;
}

.nav-right {
  right: -25px;
}

/* 图片索引 */
.image-index {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10001;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-btn {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .nav-left {
    left: -20px;
  }
  
  .nav-right {
    right: -20px;
  }
  
  .close-btn {
    top: 15px;
    right: 15px;
    width: 35px;
    height: 35px;
    font-size: 18px;
  }
  
  .image-index {
    bottom: 15px;
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style>
