/**
 * 图片懒加载指令
 * 使用 Intersection Observer API 实现
 */

// 默认占位图（1x1透明像素）
const defaultPlaceholder = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'

// 加载中占位图（可选，灰色背景）
const loadingPlaceholder = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"%3E%3Crect fill="%23333" width="100" height="100"/%3E%3C/svg%3E'

// 创建 Intersection Observer
let observer = null

const getObserver = () => {
  if (observer) return observer
  
  observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const el = entry.target
        const src = el.dataset.src
        
        if (src) {
          // 创建新图片预加载
          const img = new Image()
          img.onload = () => {
            el.src = src
            el.classList.add('lazy-loaded')
            el.classList.remove('lazy-loading')
          }
          img.onerror = () => {
            el.classList.add('lazy-error')
            el.classList.remove('lazy-loading')
          }
          img.src = src
        }
        
        // 停止观察
        observer.unobserve(el)
      }
    })
  }, {
    rootMargin: '100px', // 提前100px开始加载
    threshold: 0.1
  })
  
  return observer
}

export const lazyLoad = {
  mounted(el, binding) {
    const src = binding.value
    
    if (!src) return
    
    // 保存真实src
    el.dataset.src = src
    
    // 设置占位图
    el.src = binding.arg === 'loading' ? loadingPlaceholder : defaultPlaceholder
    el.classList.add('lazy-loading')
    
    // 开始观察
    getObserver().observe(el)
  },
  
  updated(el, binding) {
    // 如果src变化，重新加载
    if (binding.value !== binding.oldValue && binding.value) {
      el.dataset.src = binding.value
      el.classList.remove('lazy-loaded', 'lazy-error')
      el.classList.add('lazy-loading')
      getObserver().observe(el)
    }
  },
  
  unmounted(el) {
    if (observer) {
      observer.unobserve(el)
    }
  }
}

// 视频懒加载指令
export const lazyVideo = {
  mounted(el, binding) {
    const src = binding.value
    
    if (!src) return
    
    el.dataset.src = src
    el.preload = 'none' // 不预加载
    el.classList.add('lazy-loading')
    
    const videoObserver = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          el.src = el.dataset.src
          el.preload = 'metadata' // 只加载元数据
          el.classList.add('lazy-loaded')
          el.classList.remove('lazy-loading')
          videoObserver.unobserve(el)
        }
      })
    }, {
      rootMargin: '50px',
      threshold: 0.1
    })
    
    videoObserver.observe(el)
  }
}

export default {
  install(app) {
    app.directive('lazy', lazyLoad)
    app.directive('lazy-video', lazyVideo)
  }
}
