function toNumber(value) {
  const numericValue = Number(value)
  return Number.isFinite(numericValue) ? numericValue : null
}

function firstNonEmpty(...values) {
  for (const value of values) {
    if (value === undefined || value === null) {
      continue
    }

    const text = String(value).trim()

    if (text) {
      return text
    }
  }

  return ''
}

function defaultTierLabel(index) {
  return ['1-3 days', '4-7 days', '8+ days'][index] || ''
}

function normalizeTierSource(source = {}, index = 0) {
  const oldPriceValue = toNumber(
    source.oldPrice
      ?? source.oldPriceValue
      ?? source.old_price
      ?? source.old_price_value
      ?? source.basePrice
      ?? source.base_price
      ?? source.base_price_value
      ?? source.currentPrice
      ?? source.current_price,
  )
  const newPriceValue = toNumber(
    source.newPrice
      ?? source.newPriceValue
      ?? source.new_price
      ?? source.new_price_value
      ?? source.currentPrice
      ?? source.current_price,
  )
  const saveAmountValue = toNumber(
    source.saveAmount
      ?? source.saveAmountValue
      ?? source.save_amount
      ?? source.save_amount_value
  )
  const currency = firstNonEmpty(source.currency, source.priceCurrency, source.price_currency, 'USD') || 'USD'

  return {
    key: firstNonEmpty(source.key, source.slug, source.id, `tier-${index + 1}`),
    label: firstNonEmpty(source.label, source.title, source.name, source.daysLabel, source.days_label, defaultTierLabel(index)),
    daysFrom: toNumber(source.daysFrom ?? source.days_from),
    daysTo: toNumber(source.daysTo ?? source.days_to),
    oldPriceValue,
    newPriceValue,
    saveAmount: Number.isFinite(saveAmountValue)
      ? saveAmountValue
      : (Number.isFinite(oldPriceValue) && Number.isFinite(newPriceValue) ? oldPriceValue - newPriceValue : null),
    currency,
    isDefault: source.isDefault === true || source.default === true,
    oldPrice: Number.isFinite(oldPriceValue) ? oldPriceValue : null,
    newPrice: Number.isFinite(newPriceValue) ? newPriceValue : null,
    raw: source,
  }
}

function buildLegacyPricingTiers(source = {}) {
  const summary = normalizeTierSource(source)

  if (!Number.isFinite(summary.oldPriceValue) && !Number.isFinite(summary.newPriceValue)) {
    return []
  }

  return [0, 1, 2].map((index) => ({
    key: ['1_3', '4_7', '8_plus'][index],
    label: defaultTierLabel(index),
    daysFrom: [1, 4, 8][index],
    daysTo: [3, 7, null][index],
    oldPriceValue: summary.oldPriceValue,
    newPriceValue: summary.newPriceValue,
    saveAmount: summary.saveAmount,
    currency: summary.currency,
    isDefault: index === 1,
    raw: summary.raw,
  }))
}

function collectPricingTiers(item = {}) {
  const structuredContent = item?.structuredContent && typeof item.structuredContent === 'object'
    ? item.structuredContent
    : {}
  const pricingPresentation = item?.pricingPresentation && typeof item.pricingPresentation === 'object'
    ? item.pricingPresentation
    : structuredContent?.pricingPresentation && typeof structuredContent.pricingPresentation === 'object'
    ? structuredContent.pricingPresentation
    : {}
  const homeCard = pricingPresentation.homeCard && typeof pricingPresentation.homeCard === 'object'
    ? pricingPresentation.homeCard
    : {}
  const sourceTiers = item?.pricingTiers
    || item?.pricing_tiers
    || structuredContent?.pricingTiers
    || structuredContent?.pricing_tiers
    || pricingPresentation?.pricingTiers
    || pricingPresentation?.pricing_tiers
    || homeCard?.pricingTiers
    || homeCard?.pricing_tiers
    || []

  if (Array.isArray(sourceTiers) && sourceTiers.length) {
    return sourceTiers.map((tier, index) => normalizeTierSource({
      ...tier,
      oldPrice: tier?.oldPrice ?? tier?.old_price ?? homeCard.oldPrice ?? item?.oldPrice ?? item?.currentPrice,
      newPrice: tier?.newPrice ?? tier?.new_price ?? tier?.currentPrice ?? tier?.current_price ?? homeCard.newPrice ?? item?.currentPrice,
      currency: tier?.currency ?? homeCard.currency ?? item?.currency,
    }, index))
      .sort((left, right) => {
        const leftDays = Number.isFinite(left.daysFrom) ? left.daysFrom : Number.MAX_SAFE_INTEGER
        const rightDays = Number.isFinite(right.daysFrom) ? right.daysFrom : Number.MAX_SAFE_INTEGER

        return leftDays - rightDays
      })
  }

  return buildLegacyPricingTiers({
    oldPrice: homeCard.oldPrice ?? item?.oldPrice ?? item?.currentPrice,
    newPrice: homeCard.newPrice ?? item?.currentPrice,
    currency: homeCard.currency ?? item?.currency,
  })
}

export function resolveOfferPricingTiers(item = {}) {
  return collectPricingTiers(item)
}

export function resolveOfferPricingTierForDays(item = {}, days = 0) {
  const tiers = collectPricingTiers(item)
  const normalizedDays = Number(days || 0)

  if (!tiers.length) {
    return null
  }

  const matchedTier = tiers.find((tier) => {
    const daysFrom = Number(tier.daysFrom || 0)
    const daysTo = tier.daysTo === null || tier.daysTo === undefined
      ? Number.POSITIVE_INFINITY
      : Number(tier.daysTo || 0)

    return normalizedDays >= daysFrom && normalizedDays <= daysTo
  })

  return matchedTier || tiers[0] || null
}

export function resolveOfferPricingSummary(item = {}) {
  const tiers = collectPricingTiers(item)
  const firstTier = tiers[0] || normalizeTierSource(item)
  const structuredContent = item?.structuredContent && typeof item.structuredContent === 'object'
    ? item.structuredContent
    : {}
  const pricingPresentation = item?.pricingPresentation && typeof item.pricingPresentation === 'object'
    ? item.pricingPresentation
    : structuredContent?.pricingPresentation && typeof structuredContent.pricingPresentation === 'object'
    ? structuredContent.pricingPresentation
    : {}
  const homeCard = pricingPresentation.homeCard && typeof pricingPresentation.homeCard === 'object'
    ? pricingPresentation.homeCard
    : {}

  return {
    tiers,
    oldPriceValue: firstTier.oldPriceValue ?? toNumber(item?.oldPrice ?? homeCard.oldPrice ?? item?.currentPrice),
    newPriceValue: firstTier.newPriceValue ?? toNumber(item?.currentPrice ?? homeCard.newPrice),
    currency: firstTier.currency || homeCard.currency || item?.currency || 'USD',
  }
}
