<template>
  <!-- Overlay -->
  <div
    ref="overlayRef"
    class="fixed inset-0 bg-black/60 z-50 flex flex-col"
    role="dialog"
    aria-modal="true"
    aria-label="Document preview"
    @click="handleOverlayClick"
  >
    <!-- Header bar -->
    <div class="bg-white border-b border-gray-200 px-6 py-3 flex items-center justify-between shrink-0">
      <span class="text-sm font-medium text-gray-900 truncate max-w-xs">{{ doc.filename || doc.original_name }}</span>
      <button
        @click="emit('close')"
        aria-label="Close preview"
        class="text-gray-400 hover:text-gray-600 transition-colors ml-4 shrink-0"
      >
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>

    <!-- iframe content -->
    <div class="flex-1 overflow-hidden relative">
      <!-- Loading state -->
      <div
        v-if="loading"
        class="absolute inset-0 flex items-center justify-center bg-gray-50"
      >
        <div class="flex flex-col items-center gap-3 text-gray-400">
          <svg class="w-8 h-8 animate-spin" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span class="text-sm">Loading preview…</span>
        </div>
      </div>

      <!-- Error state -->
      <div
        v-else-if="loadError"
        class="absolute inset-0 flex items-center justify-center bg-gray-50"
      >
        <div class="text-center text-red-500">
          <p class="font-medium">Preview failed</p>
          <p class="text-sm mt-1">{{ loadError }}</p>
        </div>
      </div>

      <!-- iframe: shown only when blobUrl is ready -->
      <iframe
        v-if="blobUrl"
        class="w-full h-full border-0"
        :src="blobUrl"
        title="Document preview"
      ></iframe>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { fetchDocumentContent } from '../../api/client.js'

const props = defineProps({
  doc: {
    type: Object,
    required: true,
  },
})

const emit = defineEmits(['close'])

const overlayRef = ref(null)
const blobUrl = ref(null)
const loadError = ref(null)
const loading = ref(true)

async function loadContent(docId) {
  loading.value = true
  loadError.value = null

  // Revoke previous blob URL to free memory
  if (blobUrl.value) {
    URL.revokeObjectURL(blobUrl.value)
    blobUrl.value = null
  }

  try {
    const res = await fetchDocumentContent(docId)
    if (!res.ok) {
      loadError.value = `Failed to load document (HTTP ${res.status})`
      return
    }
    const blob = await res.blob()
    blobUrl.value = URL.createObjectURL(blob)
  } catch (err) {
    loadError.value = err.message || 'Failed to load document'
  } finally {
    loading.value = false
  }
}

function handleOverlayClick(e) {
  if (e.target === overlayRef.value) {
    emit('close')
  }
}

function handleKeydown(e) {
  if (e.key === 'Escape') {
    emit('close')
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
  loadContent(props.doc.id)
})

// Reload if the document changes while modal is open
watch(() => props.doc.id, (newId) => {
  loadContent(newId)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  // Release the object URL to free browser memory
  if (blobUrl.value) {
    URL.revokeObjectURL(blobUrl.value)
    blobUrl.value = null
  }
})
</script>
