'use client'

import { useEffect, useRef } from 'react';

import type { GalleryMediaItem } from '../types'

/**
 * Preload adjacent images for smoother navigation
 * Preloads prev and next images when current index changes
 */
export function usePreloadImages(
  images: GalleryMediaItem[],
  currentIndex: number,
  preloadCount: number = 1
): void {
  const preloadedRef = useRef<Set<string>>(new Set())

  useEffect(() => {
    if (images.length === 0) return

    const toPreload: string[] = []

    // Collect indices to preload (current + adjacent)
    for (let offset = -preloadCount; offset <= preloadCount; offset++) {
      if (offset === 0) continue // Skip current, it's already loading

      const index = (currentIndex + offset + images.length) % images.length
      const image = images[index]

      if (image && !preloadedRef.current.has(image.src)) {
        toPreload.push(image.src)
      }
    }

    // Preload images
    toPreload.forEach((src) => {
      const img = new Image()
      img.src = src
      preloadedRef.current.add(src)
    })
  }, [images, currentIndex, preloadCount])
}

/**
 * Preload specific image URLs
 */
export function preloadImage(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve()
    img.onerror = reject
    img.src = src
  })
}

/**
 * Preload multiple images with optional concurrency limit
 */
export async function preloadImages(
  urls: string[],
  concurrency: number = 3
): Promise<void> {
  const chunks: string[][] = []

  for (let i = 0; i < urls.length; i += concurrency) {
    chunks.push(urls.slice(i, i + concurrency))
  }

  for (const chunk of chunks) {
    await Promise.allSettled(chunk.map(preloadImage))
  }
}
