import type { Directive } from 'vue'

interface PreviewElement extends HTMLElement {
  _previewHandler?: EventListener
  _previewImage?: HTMLImageElement
}

const vPreview: Directive<PreviewElement> = {
  mounted(el, binding) {
    const img = new Image()
    img.src = binding.value
    img.style.position = 'fixed'
    img.style.zIndex = '9999'
    img.style.pointerEvents = 'none'
    img.style.boxShadow = '0 0 10px rgba(0,0,0,0.2)'
    img.style.maxWidth = '300px'
    img.style.maxHeight = '200px'
    img.style.display = 'none'
    document.body.appendChild(img)

    const showPreview = (e: MouseEvent) => {
      img.style.display = 'block'
      img.style.left = `${e.clientX + 15}px`
      img.style.top = `${e.clientY + 15}px`
    }

    const hidePreview = () => {
      img.style.display = 'none'
    }

    el._previewHandler = showPreview
    el._previewImage = img

    el.addEventListener('mouseenter', showPreview)
    el.addEventListener('mousemove', showPreview)
    el.addEventListener('mouseleave', hidePreview)
  },
  unmounted(el) {
    if (el._previewImage) {
      document.body.removeChild(el._previewImage)
    }
    el.removeEventListener('mouseenter', el._previewHandler!)
    el.removeEventListener('mousemove', el._previewHandler!)
    el.removeEventListener('mouseleave', el._previewHandler!)
  }
}

export default vPreview
