import { useState, useEffect, useRef, useCallback } from 'react'
import { queueThumbnail } from '../lib/thumbnailQueue'

// Base64 placeholder - gray background, avoids network request
const PLACEHOLDER_BASE64 = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iIzM0NDI1NSIvPjx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzY0NzQ4YiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPk5vIFByZXZpZXc8L3RleHQ+PC9zdmc+'

// LazyThumbnail component - only loads when visible via IntersectionObserver
// Uses a global request queue to limit concurrent fetches
export default function LazyThumbnail({
  src,
  alt,
  className,
  onError
}: {
  src: string
  alt: string
  className: string
  onError?: () => void
}) {
  const imgRef = useRef<HTMLImageElement>(null)
  const [isVisible, setIsVisible] = useState(false)
  const [hasError, setHasError] = useState(false)
  const [isLoaded, setIsLoaded] = useState(false)
  const [readySrc, setReadySrc] = useState<string | null>(null)

  // IntersectionObserver: detect when thumbnail scrolls into view
  useEffect(() => {
    const img = imgRef.current
    if (!img) return

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsVisible(true)
            observer.disconnect()
          }
        })
      },
      {
        rootMargin: '200px',
        threshold: 0
      }
    )

    observer.observe(img)
    return () => observer.disconnect()
  }, [])

  // When visible, queue the fetch instead of setting src directly
  useEffect(() => {
    if (!isVisible || hasError || !src) return

    let cancelled = false
    queueThumbnail(src).then(
      (loadedSrc) => {
        if (!cancelled) setReadySrc(loadedSrc)
      },
      () => {
        if (!cancelled) {
          setHasError(true)
          onError?.()
        }
      }
    )

    return () => { cancelled = true }
  }, [isVisible, src, hasError, onError])

  const handleError = useCallback(() => {
    setHasError(true)
    onError?.()
  }, [onError])

  const handleLoad = useCallback(() => {
    setIsLoaded(true)
  }, [])

  return (
    <img
      ref={imgRef}
      src={hasError ? PLACEHOLDER_BASE64 : (readySrc || PLACEHOLDER_BASE64)}
      alt={alt}
      className={`${className} ${!isLoaded && isVisible && !hasError ? 'animate-pulse' : ''}`}
      loading="lazy"
      decoding="async"
      onError={handleError}
      onLoad={handleLoad}
    />
  )
}

export { PLACEHOLDER_BASE64 }
