<template>
  <Teleport to="body">
    <div
      v-if="isOpen"
      class="pdf-reader"
      @keydown.escape="close"
      tabindex="0"
      ref="overlayRef"
    >
        <!-- Top bar -->
        <div class="pdf-bar">
          <div class="pdf-bar-title">
            <div class="i-lucide-book-open h-4 w-4 text-accent" />
            <span>{{ bpContent?.pdf.barTitle }}</span>
          </div>
          <button class="pdf-close" @click="close" aria-label="Fermer">
            <div class="i-lucide-x h-5 w-5" />
          </button>
        </div>

        <!-- PDF embed -->
        <div class="pdf-viewport">
          <iframe
            :key="pdfUrl"
            :src="pdfUrl"
            class="pdf-frame"
            :title="bpContent?.pdf.iframeTitle"
            ref="iframeRef"
            @load="iframeRef?.focus()"
          />
        </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
const props = defineProps<{ modelValue: boolean; page?: number }>()
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()

const { data: bpContent } = await usePageContent('book-player')
const bookData = useBookData()
await bookData.init()
const { trackPdfOpen, trackPdfClose } = useTracking()

const overlayRef = ref<HTMLElement>()
const iframeRef = ref<HTMLIFrameElement>()

const isOpen = computed({
  get: () => props.modelValue,
  set: (v) => emit('update:modelValue', v),
})

const pdfUrl = computed(() => {
  const base = bookData.getPdfUrl()
  const viewerBase = `/pdfjs/viewer.html?file=${encodeURIComponent(base)}`
  if (props.page) return `${viewerBase}#page=${props.page}`
  return viewerBase
})

function close() {
  isOpen.value = false
}

// Tracking state
let pdfOpenedAt = 0

watch(isOpen, (open) => {
  if (open) {
    nextTick(() => overlayRef.value?.focus())
    trackPdfOpen(props.page ? `chapter-p${props.page}` : 'direct')
    pdfOpenedAt = Date.now()
  }
  else if (pdfOpenedAt > 0) {
    trackPdfClose(0, Date.now() - pdfOpenedAt)
    pdfOpenedAt = 0
  }
  if (import.meta.client) {
    document.body.style.overflow = open ? 'hidden' : ''
  }
})

onUnmounted(() => {
  if (import.meta.client) document.body.style.overflow = ''
})
</script>

<style scoped>
.pdf-reader {
  position: fixed;
  inset: 0;
  z-index: 60;
  background: hsl(20 8% 4%);
  display: flex;
  flex-direction: column;
  outline: none;
}

.pdf-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1.25rem;
  background: hsl(20 8% 6% / 0.95);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid hsl(20 8% 14%);
  flex-shrink: 0;
}

.pdf-bar-title {
  display: flex;
  align-items: center;
  gap: 0.625rem;
  font-family: var(--font-display, 'Syne', sans-serif);
  font-size: 0.9rem;
  font-weight: 600;
  color: white;
}

.pdf-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.25rem;
  height: 2.25rem;
  border-radius: 50%;
  background: hsl(20 8% 10%);
  color: hsl(20 8% 55%);
  border: 1px solid hsl(20 8% 18%);
  cursor: pointer;
  transition: all 0.3s;
}

.pdf-close:hover {
  background: hsl(12 76% 48% / 0.2);
  color: white;
  border-color: hsl(12 76% 48% / 0.3);
}

.pdf-viewport {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.pdf-frame {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

</style>
