function firstNonEmpty(...values) {
  for (const value of values) {
    if (typeof value === 'string' && value.trim()) {
      return value.trim()
    }
  }

  return ''
}

function normalizeMediaCandidate(candidate) {
  if (!candidate) {
    return ''
  }

  if (typeof candidate === 'string') {
    return candidate.trim()
  }

  if (typeof candidate === 'object') {
    return firstNonEmpty(candidate.url, candidate.src, candidate.href, candidate.path)
  }

  return ''
}

export function resolveOfferMediaUrl(item = {}, variant = 'card', fallbackItem = null) {
  const source = item || {}
  const fallback = fallbackItem || {}
  const isHeroVariant = String(variant || '').toLowerCase() === 'hero'
  const galleryItems = isHeroVariant
    ? [
        source.galleryMedia?.[0],
        source.galleryMedia?.[1],
        source.galleryUrls?.[0],
        source.galleryUrls?.[1],
        source.gallery?.[0],
        source.gallery?.[1],
      ]
    : [
        source.galleryMedia?.[0],
        source.galleryUrls?.[0],
        source.gallery?.[0],
      ]

  const candidates = isHeroVariant
    ? [
        source.heroImage,
        source.featuredImage,
        source.cardImage,
        source.featuredMedia,
        ...galleryItems,
        fallback.heroImage,
        fallback.featuredImage,
        fallback.cardImage,
        fallback.featuredMedia,
      ]
    : [
        source.cardImage,
        source.featuredImage,
        source.heroImage,
        source.featuredMedia,
        ...galleryItems,
        fallback.cardImage,
        fallback.featuredImage,
        fallback.heroImage,
        fallback.featuredMedia,
      ]

  return candidates.map((candidate) => normalizeMediaCandidate(candidate)).find(Boolean) || ''
}

export function resolveOfferMediaAlt(item = {}, fallback = '') {
  return firstNonEmpty(
    item?.cardImageAlt,
    item?.heroImageAlt,
    item?.featuredMedia?.altText,
    item?.featuredMedia?.alt,
    item?.title,
    fallback,
  )
}
