/**
 * Thumbnail request queue - limits concurrent fetches to avoid
 * overwhelming the browser connection pool and nginx.
 *
 * With HTTP/1.1, browsers open 6-8 connections per domain.
 * Without a queue, 100+ thumbnail requests fire simultaneously,
 * causing most to wait in the browser's internal queue.
 * This queue ensures orderly loading with priority for visible items.
 */

type QueueItem = {
  resolve: (value: string) => void
  reject: (reason: unknown) => void
  src: string
}

const MAX_CONCURRENT = 20
let activeCount = 0
const queue: QueueItem[] = []

function processQueue() {
  while (activeCount < MAX_CONCURRENT && queue.length > 0) {
    const item = queue.shift()!
    activeCount++

    const img = new Image()
    img.onload = () => {
      activeCount--
      item.resolve(item.src)
      processQueue()
    }
    img.onerror = () => {
      activeCount--
      item.reject(new Error('Failed to load'))
      processQueue()
    }
    img.src = item.src
  }
}

/**
 * Queue a thumbnail URL for loading. Returns a promise that resolves
 * when the image has been fetched (and is in the browser cache).
 */
export function queueThumbnail(src: string): Promise<string> {
  return new Promise((resolve, reject) => {
    queue.push({ resolve, reject, src })
    processQueue()
  })
}

/**
 * Clear all pending items from the queue (e.g., on page navigation).
 */
export function clearThumbnailQueue() {
  queue.length = 0
}
