<template>
  <transition name="fade">
    <div v-if="visible" class="preview-mask" @click.self="close">
      <div class="preview-stage">
        <div class="preview-close" @click="close">×</div>
        <div v-if="urls.length > 1" class="preview-nav preview-prev" @click="prev">‹</div>
        <img class="preview-img" :src="currentUrl" alt="preview" />
        <div v-if="urls.length > 1" class="preview-nav preview-next" @click="next">›</div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'ImagePreviewHost',
  data() {
    return {
      visible: false,
      urls: [],
      index: 0
    }
  },
  computed: {
    currentUrl() {
      return this.urls[this.index] || ''
    }
  },
  methods: {
    open({ urls, current }) {
      this.urls = Array.isArray(urls) ? urls.slice() : [urls]
      const idx = this.urls.indexOf(current)
      this.index = idx >= 0 ? idx : 0
      this.visible = true
      document.addEventListener('keydown', this.handleKey)
    },
    close() {
      this.visible = false
      document.removeEventListener('keydown', this.handleKey)
    },
    prev() {
      this.index = (this.index - 1 + this.urls.length) % this.urls.length
    },
    next() {
      this.index = (this.index + 1) % this.urls.length
    },
    handleKey(e) {
      if (e.key === 'Escape') this.close()
      else if (e.key === 'ArrowLeft') this.prev()
      else if (e.key === 'ArrowRight') this.next()
    }
  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.handleKey)
  }
}
</script>
