<template>
  <Teleport to="body">
    <div
      v-if="isOpen"
      ref="overlay"
      class="lightbox-overlay"
      tabindex="0"
      @click.self="close"
      @keydown.escape="close"
      @keydown.left="prev"
      @keydown.right="next"
    >
      <button class="lightbox-close-btn" @click="close"><i class="fa-solid fa-xmark"></i></button>

      <button
        v-if="images.length > 1" class="lightbox-nav-btn left-4"
        @click="prev"
      >
        <i class="fa-solid fa-chevron-left"></i>
      </button>

      <img
        :src="images[currentIndex].url"
        :alt="`Image ${currentIndex + 1}`"
        class="lightbox-image"
      />

      <button
        v-if="images.length > 1" class="lightbox-nav-btn right-4"
        @click="next"
      >
        <i class="fa-solid fa-chevron-right"></i>
      </button>

      <div v-if="images.length > 1" class="lightbox-counter">
        {{ currentIndex + 1 }} / {{ images.length }}
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import type { SoftwareImage } from '../../lib/interfaces/software.interface'

const props = defineProps<{
  images: SoftwareImage[]
  isOpen: boolean
  startIndex?: number
}>()

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

const currentIndex = ref(0)
const overlay = ref<HTMLElement | null>(null)

watch(() => props.isOpen, async (open) => {
  if (open) {
    currentIndex.value = props.startIndex ?? 0
    document.body.style.overflow = 'hidden'
    await nextTick()
    overlay.value?.focus()
  } else {
    document.body.style.overflow = ''
  }
})

function close() { emit('close') }
function next() { currentIndex.value = (currentIndex.value + 1) % props.images.length }
function prev() { currentIndex.value = (currentIndex.value - 1 + props.images.length) % props.images.length }
</script>

<style scoped>
.lightbox-overlay {
  @apply fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm;
}
.lightbox-close-btn {
  @apply absolute top-4 right-4 text-white/70 hover:text-white text-3xl font-bold z-10;
}
.lightbox-nav-btn {
  @apply absolute text-white/70 hover:text-white text-5xl font-bold z-10 select-none;
}
.lightbox-image {
  @apply max-h-[85vh] max-w-[90vw] object-contain rounded-lg shadow-2xl;
}
.lightbox-counter {
  @apply absolute bottom-6 text-white/60 text-sm font-mono;
}
</style>
