const CITY_RENTAL_TAG_STYLES = {
  economy: { iconKey: 'fuel', color: 'bg-emerald-50 text-emerald-700 border-emerald-200' },
  sedan: { iconKey: 'settings', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  suv: { iconKey: 'navigation', color: 'bg-amber-50 text-amber-700 border-amber-200' },
  van: { iconKey: 'users', color: 'bg-sky-50 text-sky-700 border-sky-200' },
  vans: { iconKey: 'users', color: 'bg-sky-50 text-sky-700 border-sky-200' },
  minivan: { iconKey: 'users', color: 'bg-sky-50 text-sky-700 border-sky-200' },
  caravan: { iconKey: 'users', color: 'bg-sky-50 text-sky-700 border-sky-200' },
  premium: { iconKey: 'star', color: 'bg-violet-50 text-violet-700 border-violet-200' },
  luxury: { iconKey: 'star', color: 'bg-violet-50 text-violet-700 border-violet-200' },
  featured: { iconKey: 'star', color: 'bg-violet-50 text-violet-700 border-violet-200' },
  family: { iconKey: 'users', color: 'bg-sky-50 text-sky-700 border-sky-200' },
  business: { iconKey: 'briefcase', color: 'bg-slate-50 text-slate-700 border-slate-200' },
  intercity: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  city: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  comfort: { iconKey: 'shieldCheck', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  space: { iconKey: 'briefcase', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  auto: { iconKey: 'settings', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  automatic: { iconKey: 'settings', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  manual: { iconKey: 'settings', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  agile: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  mountain: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  kazbegi: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
  gudauri: { iconKey: 'navigation', color: 'bg-slate-50 text-slate-600 border-slate-200' },
}

function normalizeText(value) {
  return String(value || '').trim()
}

function normalizeLowerText(value) {
  return normalizeText(value).toLowerCase()
}

function uniqueStrings(values = []) {
  return [...new Set((Array.isArray(values) ? values : [])
    .map((value) => normalizeText(value))
    .filter(Boolean))]
}

function toNumber(value) {
  if (value == null) {
    return null
  }

  const text = String(value).trim()

  if (!text) {
    return null
  }

  const numeric = Number(text.replace(/[^\d.-]/g, ''))

  return Number.isFinite(numeric) ? numeric : null
}

function parseLuggageValue(value) {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value
  }

  const numeric = String(value || '').match(/\d+/)?.[0]

  return numeric ? Number(numeric) : null
}

function normalizeVehicleTokens(vehicle = {}) {
  return uniqueStrings([
    vehicle?.homeCategory,
    vehicle?.category,
    ...(Array.isArray(vehicle?.homeTypes) ? vehicle.homeTypes : []),
    ...(Array.isArray(vehicle?.suitabilityTags) ? vehicle.suitabilityTags : []),
    ...(Array.isArray(vehicle?.salesTags) ? vehicle.salesTags : []),
    ...(Array.isArray(vehicle?.tags)
      ? vehicle.tags.map((tag) => (typeof tag === 'string' ? tag : tag?.label))
      : []),
    ...(Array.isArray(vehicle?.badges)
      ? vehicle.badges.map((badge) => badge?.label)
      : []),
  ]).map((value) => normalizeLowerText(value))
}

function hasToken(vehicle, expectedValues = []) {
  const tokens = normalizeVehicleTokens(vehicle)

  return expectedValues.some((expected) => tokens.some((token) => token.includes(normalizeLowerText(expected))))
}

function isVehicleEconomy(vehicle) {
  return hasToken(vehicle, ['economy'])
}

function isVehicleSedan(vehicle) {
  return hasToken(vehicle, ['sedan'])
}

function isVehicleSuv(vehicle) {
  return hasToken(vehicle, ['suv'])
}

function isVehicleVan(vehicle) {
  return hasToken(vehicle, ['van', 'vans', 'minivan', 'caravan']) || Number(vehicle?.specs?.seats || 0) >= 7
}

function isVehiclePremium(vehicle) {
  return hasToken(vehicle, ['premium', 'luxury', 'featured'])
}

function isMountainReady(vehicle) {
  return hasToken(vehicle, ['kazbegi', 'gudauri', 'mountain', 'mountains', 'winter'])
}

function priceScore(vehicle) {
  const price = Number(vehicle?.price || 0)

  if (!price) {
    return 1
  }

  if (price <= 30) {
    return 5
  }

  if (price <= 45) {
    return 4
  }

  if (price <= 65) {
    return 3
  }

  if (price <= 100) {
    return 2
  }

  return 1
}

function scoreRoute(vehicle, route) {
  if (!route) {
    return 0
  }

  if (route === 'Tbilisi only') {
    if (isVehicleEconomy(vehicle)) return 5
    if (isVehicleSedan(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 3
    if (isVehicleSuv(vehicle)) return 2
    if (isVehicleVan(vehicle)) return 1
    return 0
  }

  if (route === 'Kazbegi / Mountains') {
    if (isVehicleSuv(vehicle)) return 5
    if (isVehicleVan(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 3
    if (isVehicleSedan(vehicle)) return 1
    if (isVehicleEconomy(vehicle)) return 0
    return 1
  }

  if (route === 'Kakheti / smooth roads') {
    if (isVehicleSedan(vehicle)) return 5
    if (isVehicleEconomy(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 4
    if (isVehicleSuv(vehicle)) return 3
    if (isVehicleVan(vehicle)) return 2
    return 0
  }

  if (route === 'Long Georgia trip') {
    if (isVehicleVan(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 4
    if (isVehicleSedan(vehicle)) return 3
    if (isVehicleEconomy(vehicle)) return 2
    return 1
  }

  return 0
}

function scorePassengers(vehicle, passengers) {
  const seats = Number(vehicle?.specs?.seats || 0)
  const luggage = Number(vehicle?.specs?.luggage || 0)

  if (passengers === '1-2 adults') {
    if (isVehicleEconomy(vehicle)) return 5
    if (isVehicleSedan(vehicle)) return 5
    if (isVehiclePremium(vehicle)) return 4
    if (isVehicleSuv(vehicle)) return 3
    if (isVehicleVan(vehicle)) return 1
    return 0
  }

  if (passengers === '3-4 adults') {
    if (isVehicleSedan(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 5
    if (isVehiclePremium(vehicle)) return 4
    if (seats >= 4) return 3
    if (isVehicleVan(vehicle)) return 3
    if (isVehicleEconomy(vehicle)) return 2
    return 0
  }

  if (passengers === 'Family + Luggage') {
    if (isVehicleVan(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 5
    if (isVehiclePremium(vehicle)) return 4
    if (seats >= 5 || luggage >= 4) return 4
    if (isVehicleSedan(vehicle)) return 3
    if (isVehicleEconomy(vehicle)) return 1
    return 0
  }

  if (passengers === '4+ adults') {
    if (isVehicleVan(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 3
    if (seats >= 5) return 3
    if (isVehicleSedan(vehicle)) return 1
    if (isVehicleEconomy(vehicle)) return 0
    return 0
  }

  return 0
}

function scorePriority(vehicle, priority) {
  const seats = Number(vehicle?.specs?.seats || 0)
  const luggage = Number(vehicle?.specs?.luggage || 0)
  const price = Number(vehicle?.price || 0)

  if (priority === 'Lowest Price') {
    return priceScore(vehicle)
  }

  if (priority === 'Mountain Confidence') {
    if (isVehicleSuv(vehicle)) return 5
    if (isVehicleVan(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 3
    if (isVehicleSedan(vehicle)) return 1
    if (isVehicleEconomy(vehicle)) return 0
    return 0
  }

  if (priority === 'Luggage / Comfort') {
    if (isVehicleVan(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 4
    if (isVehiclePremium(vehicle)) return 4
    if (seats >= 5 || luggage >= 3) return 4
    if (isVehicleSedan(vehicle)) return 3
    if (isVehicleEconomy(vehicle)) return 1
    return 0
  }

  if (priority === 'Premium Look') {
    if (isVehiclePremium(vehicle)) return 5
    if (isVehicleSuv(vehicle)) return 4
    if (isVehicleSedan(vehicle)) return 3
    if (isVehicleVan(vehicle)) return 2
    if (isVehicleEconomy(vehicle)) return 1
    return 0
  }

  return price > 0 ? priceScore(vehicle) : 0
}

function normalizedPriceBands(item = {}) {
  const fallbackPrice = toNumber(item?.price ?? item?.displayPriceFrom ?? item?.priceFrom ?? 0)
  const bandPrice = (keys = []) => {
    for (const key of keys) {
      const value = toNumber(item?.prices?.[key])

      if (value != null) {
        return value
      }
    }

    return fallbackPrice
  }

  return {
    '1-3d': bandPrice(['1-3d', '1-2d', '1-4d']),
    '4-7d': bandPrice(['4-7d', '4-6d', '7-14d']),
    '8-14d': bandPrice(['8-14d', '7-14d', '15-29d']),
    '15+d': bandPrice(['15+d', '15-29d']),
  }
}

function normalizedTagStyle(label) {
  const key = normalizeLowerText(label)

  return CITY_RENTAL_TAG_STYLES[key] || { iconKey: 'shieldCheck', color: 'bg-slate-50 text-slate-600 border-slate-200' }
}

function normalizeCityRentalTag(label) {
  const text = normalizeText(label)

  if (!text) {
    return null
  }

  const style = normalizedTagStyle(text)

  return {
    label: text,
    iconKey: style.iconKey,
    color: style.color,
  }
}

function buildCityRentalTags(item = {}) {
  const labels = uniqueStrings([
    item?.homeCategory,
    item?.category,
    ...(Array.isArray(item?.homeTypes) ? item.homeTypes : []),
    ...(Array.isArray(item?.suitabilityTags) ? item.suitabilityTags : []),
    ...(Array.isArray(item?.salesTags) ? item.salesTags : []),
    ...(Array.isArray(item?.badges) ? item.badges.map((badge) => badge?.label) : []),
  ])

  return labels
    .map((label) => normalizeCityRentalTag(label))
    .filter(Boolean)
    .slice(0, 4)
}

export function normalizeCityRentalVehicleRecord(item = {}) {
  const contentKey = normalizeText(item?.contentKey || item?.content_key || item?.entityId || item?.entity_id || item?.id)
  const locale = normalizeText(item?.locale || 'en')
  const gallery = Array.isArray(item?.gallery) && item.gallery.length
    ? item.gallery.filter(Boolean)
    : Array.isArray(item?.mediaPack?.gallery) ? item.mediaPack.gallery.filter(Boolean) : []
  const image = item?.heroImage
    || item?.image
    || item?.mediaPack?.heroImage
    || gallery[0]
    || null
  const resolvedGallery = gallery.length ? gallery : [image].filter(Boolean)
  const price = toNumber(item?.price) || 0
  const category = normalizeText(item?.category || item?.homeCategory || '')
  const seats = toNumber(item?.seats || item?.specs?.seats)
  const luggage = parseLuggageValue(item?.bags || item?.specs?.luggage)

  return {
    id: normalizeText(item?.id || (contentKey ? `${contentKey}__${locale}` : '')),
    contentKey,
    content_key: contentKey,
    entityId: normalizeText(item?.entityId || item?.entity_id || contentKey),
    entity_id: normalizeText(item?.entityId || item?.entity_id || contentKey),
    locale,
    slug: normalizeText(item?.slug || item?.publicSlug || ''),
    publicSlug: normalizeText(item?.publicSlug || item?.slug || ''),
    name: normalizeText(item?.name || [item?.brand, item?.model].filter(Boolean).join(' ')),
    title: normalizeText(item?.title || item?.name || [item?.brand, item?.model].filter(Boolean).join(' ')),
    brand: normalizeText(item?.brand || ''),
    model: normalizeText(item?.model || ''),
    vehicleGroupId: toNumber(item?.vehicleGroupId) || null,
    year: normalizeText(item?.year || ''),
    category,
    homeCategory: normalizeText(item?.homeCategory || ''),
    homeTypes: uniqueStrings(item?.homeTypes || []),
    homeSortOrder: toNumber(item?.homeSortOrder) || null,
    path: normalizeText(item?.path || item?.ctaUrl || ''),
    image,
    heroImage: image,
    gallery: resolvedGallery,
    price,
    currency: normalizeText(item?.currency || 'USD') || 'USD',
    rating: toNumber(item?.rating ?? item?.reviewAggregate?.rating),
    reviewAggregate: item?.reviewAggregate || null,
    description: normalizeText(item?.longDescription || item?.description || ''),
    longDescription: normalizeText(item?.longDescription || item?.description || ''),
    videoUrl: normalizeText(item?.videoUrl || item?.mediaPack?.videoUrl || item?.video || ''),
    baseDailyRate: toNumber(item?.baseDailyRate) || null,
    priceFrom: toNumber(item?.priceFrom) || null,
    displayPriceFrom: toNumber(item?.displayPriceFrom) || null,
    priceNote: normalizeText(item?.priceNote || ''),
    tags: buildCityRentalTags(item),
    salesTags: uniqueStrings(item?.salesTags || []),
    suitabilityTags: uniqueStrings(item?.suitabilityTags || []),
    badges: Array.isArray(item?.badges) ? item.badges.filter(Boolean) : [],
    features: Array.isArray(item?.features) ? item.features : Array.isArray(item?.featureNames) ? item.featureNames : Array.isArray(item?.shortFeatures) ? item.shortFeatures : [],
    includedInPrice: Array.isArray(item?.includedInPrice) ? item.includedInPrice : [],
    conditionReport: item?.conditionReport || null,
    prices: normalizedPriceBands(item),
    deposit: item?.deposit == null ? null : toNumber(item?.deposit),
    photosCount: toNumber(item?.photosCount || resolvedGallery.length || 0) || 0,
    ctaUrl: normalizeText(item?.ctaUrl || item?.path || ''),
    compareUrl: normalizeText(item?.ctaUrl || item?.path || ''),
    specs: {
      seats: seats == null ? null : seats,
      transmission: normalizeText(item?.transmission || item?.specs?.transmission || ''),
      fuel: normalizeText(item?.fuelType || item?.powertrain || item?.specs?.fuel || item?.specs?.engine || ''),
      luggage: luggage == null ? null : luggage,
    },
  }
}

export function dedupeCityRentalVehicles(records = []) {
  const seen = new Set()
  const uniqueRecords = []

  for (const record of Array.isArray(records) ? records : []) {
    const key = normalizeText(record?.contentKey || record?.entityId || record?.id)

    if (!key || seen.has(key)) {
      continue
    }

    seen.add(key)
    uniqueRecords.push(record)
  }

  return uniqueRecords
}

export function matchesCityRentalFilter(vehicle = {}, filter = '') {
  const normalizedFilter = normalizeText(filter)

  if (!normalizedFilter || normalizedFilter === 'All') {
    return true
  }

  if (normalizedFilter === 'Economy') {
    return isVehicleEconomy(vehicle)
  }

  if (normalizedFilter === 'SUV') {
    return isVehicleSuv(vehicle)
  }

  if (normalizedFilter === 'Sedan') {
    return isVehicleSedan(vehicle)
  }

  if (normalizedFilter === 'Vans') {
    return isVehicleVan(vehicle)
  }

  if (normalizedFilter === 'Premium') {
    return isVehiclePremium(vehicle)
  }

  if (normalizedFilter === 'Family') {
    return Number(vehicle?.specs?.seats || 0) >= 5 && Number(vehicle?.specs?.luggage || 0) >= 4
  }

  if (normalizedFilter === 'Kazbegi / Gudauri') {
    return isVehicleSuv(vehicle) || isMountainReady(vehicle)
  }

  return true
}

export function scoreCityRentalVehicle(vehicle = {}, answers = {}) {
  const routeScore = scoreRoute(vehicle, answers.route)
  const passengersScore = scorePassengers(vehicle, answers.passengers)
  const priorityScore = scorePriority(vehicle, answers.priority)

  return routeScore + passengersScore + priorityScore
}
