<template>
  <Transition name="dialog">
    <div v-if="file" class="image-preview-overlay" @click="$emit('close')">
      <div class="image-preview-container" @click.stop>
        <div class="preview-actions">
          <button class="btn-download-preview" @click="downloadFile" title="Скачать">
            <i data-lucide="download"></i>
          </button>
          <button v-if="showDelete" class="btn-delete-preview" @click="$emit('delete')" title="Удалить">
            <i data-lucide="trash-2"></i>
          </button>
          <button class="btn-close-preview" @click="$emit('close')" title="Закрыть">
            <i data-lucide="x"></i>
          </button>
        </div>
        
        <!-- Архив -->
        <template v-if="isArchive">
          <div class="archive-preview-icon">
            <i data-lucide="archive"></i>
            <span>{{ file.name }}</span>
          </div>
        </template>
        
        <!-- Изображение -->
        <img v-else :src="previewUrl" :alt="file.name" class="image-preview-full">
        
        <div class="image-preview-info">
          <span class="preview-name">{{ file.name }}</span>
          <span class="preview-size">{{ formatFileSize(file.size) }}</span>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup>
import { computed, onMounted, onUpdated } from 'vue'

const props = defineProps({
  file: {
    type: Object,
    default: null
    // Формат: { name, size, type, preview }
  },
  showDelete: {
    type: Boolean,
    default: true
  },
  archiveExtensions: {
    type: Array,
    default: () => ['zip', 'rar']
  },
  getFullUrl: {
    type: Function,
    default: (url) => url
  }
})

const emit = defineEmits(['close', 'delete'])

// URL превью
const previewUrl = computed(() => {
  if (!props.file) return ''
  return props.getFullUrl(props.file.preview)
})

// Проверка архива
const isArchive = computed(() => {
  if (!props.file) return false
  const ext = props.file.name?.split('.').pop()?.toLowerCase() || ''
  return props.archiveExtensions.includes(ext)
})

// Форматирование размера
const formatFileSize = (bytes) => {
  if (!bytes) return ''
  if (bytes < 1024) return bytes + ' Б'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' КБ'
  return (bytes / (1024 * 1024)).toFixed(1) + ' МБ'
}

// Скачивание
const downloadFile = async () => {
  if (!props.file) return
  
  const url = previewUrl.value
  try {
    if (props.file.preview?.startsWith('data:')) {
      const link = document.createElement('a')
      link.href = props.file.preview
      link.download = props.file.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    } else {
      const response = await fetch(url)
      const blob = await response.blob()
      const blobUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = blobUrl
      link.download = props.file.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(blobUrl)
    }
  } catch (error) {
    console.error('Ошибка скачивания:', error)
    window.open(url, '_blank')
  }
}

// Обновление иконок
const refreshIcons = () => {
  if (window.lucide) {
    window.lucide.createIcons()
  }
}

onMounted(refreshIcons)
onUpdated(refreshIcons)
</script>

<style scoped>
.image-preview-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1200;
  padding: 40px;
}

.image-preview-container {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.preview-actions {
  position: absolute;
  top: -50px;
  right: 0;
  display: flex;
  gap: 8px;
}

.btn-close-preview,
.btn-download-preview,
.btn-delete-preview {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 50%;
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.btn-close-preview:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: scale(1.1);
}

.btn-download-preview:hover {
  background: var(--accent);
  color: #000;
  transform: scale(1.1);
}

.btn-delete-preview:hover {
  background: #ef4444;
  transform: scale(1.1);
}

.btn-close-preview i,
.btn-download-preview i,
.btn-delete-preview i {
  width: 20px;
  height: 20px;
}

.image-preview-full {
  max-width: 100%;
  max-height: calc(90vh - 60px);
  object-fit: contain;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}

.archive-preview-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 60px;
  background: var(--bg-card);
  border-radius: 16px;
  color: var(--text-secondary);
}

.archive-preview-icon i {
  width: 64px;
  height: 64px;
  opacity: 0.6;
}

.archive-preview-icon span {
  font-size: 14px;
  font-weight: 500;
}

.image-preview-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 8px;
}

.preview-name {
  font-size: 14px;
  color: var(--text-primary);
  font-weight: 500;
}

.preview-size {
  font-size: 12px;
  color: var(--text-muted);
}

/* Transition */
.dialog-enter-active,
.dialog-leave-active {
  transition: opacity 0.2s ease;
}

.dialog-enter-from,
.dialog-leave-to {
  opacity: 0;
}
</style>
