/**
 * 图片懒加载指令
 * 使用 IntersectionObserver API 实现高性能懒加载
 * 
 * 使用方式：
 * 1. 在 main.js 中注册：app.directive('lazy', lazyDirective)
 * 2. 在模板中使用：<img v-lazy="imageUrl" />
 */

const DEFAULT_PLACEHOLDER = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjFmNWY5Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJzYW5zLXNlcmlmIiBmb250LXNpemU9IjE0IiBmaWxsPSIjOTRhM2I4IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+加载中...</text></svg>'

// 创建 IntersectionObserver 实例（单例模式，避免重复创建）
let observer = null

const getObserver = () => {
  if (!observer) {
    observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const img = entry.target
            const src = img.dataset.lazySrc
            if (src) {
              // 预加载图片
              const tempImg = new Image()
              tempImg.onload = () => {
                img.src = src
                img.classList.add('lazy-loaded')
                img.removeAttribute('data-lazy-src')
              }
              tempImg.onerror = () => {
                img.classList.add('lazy-error')
              }
              tempImg.src = src
            }
            observer.unobserve(img)
          }
        })
      },
      {
        rootMargin: '50px 0px', // 提前 50px 开始加载
        threshold: 0.01,
      }
    )
  }
  return observer
}

export const lazyDirective = {
  mounted(el, binding) {
    if (!binding.value) return
    
    // 设置占位图
    el.src = DEFAULT_PLACEHOLDER
    el.dataset.lazySrc = binding.value
    el.classList.add('lazy-img')
    
    // 使用 IntersectionObserver 监听
    if ('IntersectionObserver' in window) {
      getObserver().observe(el)
    } else {
      // 降级处理：直接加载
      el.src = binding.value
    }
  },
  
  updated(el, binding) {
    if (binding.value !== binding.oldValue) {
      el.dataset.lazySrc = binding.value
      el.classList.remove('lazy-loaded', 'lazy-error')
      
      if ('IntersectionObserver' in window) {
        getObserver().observe(el)
      } else {
        el.src = binding.value
      }
    }
  },
  
  unmounted(el) {
    if (observer) {
      observer.unobserve(el)
    }
  },
}

export default lazyDirective
