import { computed } from 'vue'
import { vehicleRoutes as rawVehicleRoutes } from '~/generated/site/vehicles/routes'
import { loadExtrasLocaleExport } from '~/content/extras-export'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { useResolvedPage } from '~/content/pages'
import { resolvePublicUiValue } from '~/i18n/public-ui'
import { DEFAULT_PUBLIC_LOCALE, normalizePublicLocale } from '~/utils/public-locales'

const vehicleListingModules = import.meta.glob('../generated/site/vehicles/index/*.js')
const vehicleDetailModules = import.meta.glob('../generated/site/vehicles/detail/*/*.js')

const EMPTY_VEHICLE_LISTING = Object.freeze({
  locale: DEFAULT_PUBLIC_LOCALE,
  fleetCategories: [],
  fleetGalleryImages: [],
  fleetUseCases: [],
  fleetVehicles: [],
  vehicleItems: [],
  vehiclesIndex: [],
})

const EMPTY_VEHICLE_PAGE = Object.freeze({})
const EMPTY_VEHICLE_DETAIL_CONTENT = Object.freeze({})
const EMPTY_VEHICLE_LISTING_CONTENT = Object.freeze({})

const vehicleCategoryKeyMap = {
  All: 'all',
  Economy: 'economy',
  Sedan: 'sedan',
  SUV: 'suv',
  Vans: 'vans',
  Premium: 'premium',
}

function normalizeRouteLookupValue(value = '') {
  const [pathname = ''] = String(value || '').trim().split(/[?#]/, 1)

  if (!pathname) {
    return ''
  }

  return pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname
}

function pathSlugSegment(path = '') {
  return normalizeRouteLookupValue(path).split('/').filter(Boolean).at(-1) || ''
}

function uniqueValues(values = []) {
  return [...new Set(values.map((value) => String(value || '').trim()).filter(Boolean))]
}

function normalizeLocalizedRouteEntry(entry = {}) {
  const locale = normalizePublicLocale(entry?.locale || DEFAULT_PUBLIC_LOCALE)
  const path = normalizeRouteLookupValue(entry?.path || '')
  const href = String(entry?.href || entry?.canonical || '').trim()
  const canonical = String(entry?.canonical || href).trim()
  const redirectFrom = uniqueValues([
    ...(Array.isArray(entry?.redirectFrom) ? entry.redirectFrom : []),
    ...(Array.isArray(entry?.redirect_from) ? entry.redirect_from : []),
  ]).map((value) => normalizeRouteLookupValue(value)).filter(Boolean)

  return {
    locale,
    path,
    href,
    canonical,
    title: String(entry?.title || '').trim(),
    redirectFrom,
    redirect_from: redirectFrom,
    lastModified: entry?.lastModified || entry?.last_modified || null,
    last_modified: entry?.lastModified || entry?.last_modified || null,
    indexable: entry?.indexable !== false,
    status: String(entry?.status || '').trim(),
  }
}

function normalizeVehicleRouteEntry(entry = {}) {
  const localized = (Array.isArray(entry?.localized) ? entry.localized : [])
    .map((item) => normalizeLocalizedRouteEntry(item))
    .filter((item) => item.path || item.href)
  const availableLocales = uniqueValues([
    ...(Array.isArray(entry?.availableLocales) ? entry.availableLocales : []),
    ...(Array.isArray(entry?.available_locales) ? entry.available_locales : []),
    ...localized.map((item) => item.locale),
  ])
  const defaultLocalized = localized.find((item) => item.locale === DEFAULT_PUBLIC_LOCALE) || localized[0] || null
  const redirectFrom = uniqueValues([
    ...(Array.isArray(entry?.redirectFrom) ? entry.redirectFrom : []),
    ...(Array.isArray(entry?.redirect_from) ? entry.redirect_from : []),
  ]).map((value) => normalizeRouteLookupValue(value)).filter(Boolean)
  const contentKey = String(entry?.contentKey || entry?.content_key || entry?.entityId || entry?.entity_id || '').trim()
  const entityId = String(entry?.entityId || entry?.entity_id || contentKey).trim()

  return {
    contentKey,
    content_key: contentKey,
    entityId,
    entity_id: entityId,
    path: normalizeRouteLookupValue(entry?.path || defaultLocalized?.path || ''),
    canonical: String(entry?.canonical || defaultLocalized?.canonical || defaultLocalized?.href || '').trim(),
    availableLocales,
    available_locales: availableLocales,
    localized,
    redirectFrom,
    redirect_from: redirectFrom,
    xDefault: String(entry?.xDefault || entry?.x_default || '').trim(),
    x_default: String(entry?.xDefault || entry?.x_default || '').trim(),
  }
}

const vehicleRouteEntries = (Array.isArray(rawVehicleRoutes) ? rawVehicleRoutes : [])
  .map((entry) => normalizeVehicleRouteEntry(entry))
  .filter((entry) => entry.contentKey || entry.entityId || entry.path)

const vehicleRouteLookupByPath = new Map()
const vehicleRouteLookupByKey = new Map()

for (const entry of vehicleRouteEntries) {
  for (const candidate of [
    entry.path,
    ...entry.redirectFrom,
    ...entry.localized.flatMap((item) => [item.path, ...(item.redirectFrom || [])]),
  ]) {
    const normalizedCandidate = normalizeRouteLookupValue(candidate)

    if (normalizedCandidate) {
      vehicleRouteLookupByPath.set(normalizedCandidate, entry)
    }
  }

  for (const candidate of uniqueValues([
    entry.contentKey,
    entry.entityId,
    pathSlugSegment(entry.path),
    ...entry.localized.flatMap((item) => [item.path, item.href, pathSlugSegment(item.path)]),
  ])) {
    vehicleRouteLookupByKey.set(candidate, entry)
  }
}

const vehicleListingPromiseCache = new Map()
const vehicleDetailPromiseCache = new Map()

function vehicleListingModuleKey(locale = DEFAULT_PUBLIC_LOCALE) {
  return `../generated/site/vehicles/index/${normalizePublicLocale(locale)}.js`
}

function vehicleDetailModuleKey(contentKey, locale = DEFAULT_PUBLIC_LOCALE) {
  return `../generated/site/vehicles/detail/${String(contentKey || '').trim()}/${normalizePublicLocale(locale)}.js`
}

function emptyVehicleListing() {
  return {
    locale: DEFAULT_PUBLIC_LOCALE,
    fleetCategories: [],
    fleetGalleryImages: [],
    fleetUseCases: [],
    fleetVehicles: [],
    vehicleItems: [],
    vehiclesIndex: [],
  }
}

function splitHeroTitle(title) {
  const parts = String(title || '').trim().split(/\s+/).filter(Boolean)

  if (parts.length < 2) {
    return {
      lead: '',
      accent: parts[0] || '',
    }
  }

  return {
    lead: parts.slice(0, -1).join(' '),
    accent: parts.at(-1),
  }
}

function normalizeVehicleTag(tag) {
  const value = String(tag || '').trim()

  if (!value) {
    return null
  }

  return value === 'Luxury' ? 'Premium' : value
}

function normalizeVehicleTags(tags = []) {
  return [...new Set((tags || [])
    .map(normalizeVehicleTag)
    .filter(Boolean))]
}

function absoluteOrigin(origin = '') {
  return String(origin || '').replace(/\/+$/, '')
}

function resolveLocalizedRouteEntry(routeEntry, locale = DEFAULT_PUBLIC_LOCALE) {
  if (!routeEntry) {
    return null
  }

  const normalizedLocale = normalizePublicLocale(locale)

  return routeEntry.localized.find((item) => item.locale === normalizedLocale)
    || routeEntry.localized.find((item) => item.locale === DEFAULT_PUBLIC_LOCALE)
    || routeEntry.localized[0]
    || null
}

function resolveVehiclePathFromRoute(routeEntry, locale = DEFAULT_PUBLIC_LOCALE, sectionPath = '') {
  const localizedEntry = resolveLocalizedRouteEntry(routeEntry, locale)

  if (localizedEntry?.path) {
    return localizedEntry.path
  }

  const fallbackLocalizedEntry = routeEntry?.localized.find((item) => item.locale === DEFAULT_PUBLIC_LOCALE)

  if (fallbackLocalizedEntry?.path) {
    return fallbackLocalizedEntry.path
  }

  return normalizeRouteLookupValue(sectionPath || '')
}

function resolveVehicleLookupCandidates(identifier) {
  if (typeof identifier === 'string') {
    const normalizedPath = normalizeRouteLookupValue(identifier)

    return uniqueValues([
      identifier,
      normalizedPath,
      pathSlugSegment(normalizedPath),
    ])
  }

  return uniqueValues([
    identifier?.contentKey,
    identifier?.content_key,
    identifier?.entityId,
    identifier?.entity_id,
    identifier?.slug,
    identifier?.publicSlug,
    identifier?.id,
    identifier?.path,
    normalizeRouteLookupValue(identifier?.path),
    pathSlugSegment(identifier?.path),
  ])
}

export function resolveVehicleRoute(identifier) {
  if (!identifier) {
    return null
  }

  const lookupPath = normalizeRouteLookupValue(typeof identifier === 'object' ? identifier?.path : identifier)

  if (lookupPath && vehicleRouteLookupByPath.has(lookupPath)) {
    return vehicleRouteLookupByPath.get(lookupPath) || null
  }

  for (const candidate of resolveVehicleLookupCandidates(identifier)) {
    if (vehicleRouteLookupByPath.has(candidate)) {
      return vehicleRouteLookupByPath.get(candidate) || null
    }

    if (vehicleRouteLookupByKey.has(candidate)) {
      return vehicleRouteLookupByKey.get(candidate) || null
    }
  }

  return null
}

function buildVehicleHreflang(routeEntry, existing = [], origin = '') {
  if (Array.isArray(existing) && existing.length) {
    return existing
  }

  const siteOrigin = absoluteOrigin(origin)

  return (routeEntry?.localized || [])
    .filter((item) => item.locale && (item.href || item.path))
    .map((item) => ({
      locale: item.locale,
      href: item.href || `${siteOrigin}${item.path}`,
    }))
}

function mergeVehicleRouteData(item, locale = DEFAULT_PUBLIC_LOCALE, sectionPath = '') {
  const routeEntry = resolveVehicleRoute(item)

  if (!routeEntry) {
    return {
      ...item,
      path: normalizeRouteLookupValue(item?.path || sectionPath || ''),
    }
  }

  const localizedEntry = resolveLocalizedRouteEntry(routeEntry, locale)
  const path = resolveVehiclePathFromRoute(routeEntry, locale, sectionPath)

  return {
    ...item,
    contentKey: routeEntry.contentKey || item?.contentKey || item?.content_key || item?.id || '',
    content_key: routeEntry.contentKey || item?.contentKey || item?.content_key || item?.id || '',
    entityId: routeEntry.entityId || item?.entityId || item?.entity_id || item?.id || '',
    entity_id: routeEntry.entityId || item?.entityId || item?.entity_id || item?.id || '',
    availableLocales: routeEntry.availableLocales,
    available_locales: routeEntry.availableLocales,
    localized: routeEntry.localized,
    path,
    seo: {
      ...(item?.seo || {}),
      canonical: localizedEntry?.canonical || localizedEntry?.href || item?.seo?.canonical || routeEntry.canonical || '',
      hreflang: buildVehicleHreflang(routeEntry, item?.seo?.hreflang),
      xDefault: routeEntry.xDefault || routeEntry.x_default || item?.seo?.xDefault || '',
      lastModified: localizedEntry?.lastModified || localizedEntry?.last_modified || item?.seo?.lastModified || null,
    },
  }
}

function normalizeVehicleRecord(item, locale = DEFAULT_PUBLIC_LOCALE, sectionPath = '') {
  if (!item) {
    return null
  }

  const mergedItem = mergeVehicleRouteData(item, locale, sectionPath)
  const resolvedPath = resolveVehiclePathFromRoute(resolveVehicleRoute(mergedItem), locale, sectionPath) || normalizeRouteLookupValue(mergedItem?.path || sectionPath || '')
  const slug = String(mergedItem?.slug || mergedItem?.publicSlug || pathSlugSegment(resolvedPath) || mergedItem?.id || '').trim()
  const contentKey = String(mergedItem?.contentKey || mergedItem?.content_key || mergedItem?.entityId || mergedItem?.entity_id || mergedItem?.id || slug).trim()
  const entityId = String(mergedItem?.entityId || mergedItem?.entity_id || contentKey).trim()
  const tags = normalizeVehicleTags(
    (Array.isArray(mergedItem?.badges) ? mergedItem.badges.map((badge) => badge?.label) : [])
      .filter(Boolean),
  )
  const gallery = mergedItem?.mediaPack?.gallery?.length
    ? mergedItem.mediaPack.gallery
    : (Array.isArray(mergedItem?.gallery) ? mergedItem.gallery : []).filter(Boolean)
  const image = mergedItem?.heroImage
    || mergedItem?.image
    || mergedItem?.mediaPack?.heroImage
    || gallery[0]
    || null
  const includedInPrice = Array.isArray(mergedItem?.includedInPrice)
    ? mergedItem.includedInPrice
    : Array.isArray(mergedItem?.filterMeta?.includedInPrice)
      ? mergedItem.filterMeta.includedInPrice
      : []

  return {
    id: mergedItem?.id || `${contentKey}__${normalizePublicLocale(mergedItem?.locale || locale)}`,
    contentKey,
    content_key: contentKey,
    entityId,
    entity_id: entityId,
    locale: normalizePublicLocale(mergedItem?.locale || locale),
    availableLocales: mergedItem?.availableLocales || mergedItem?.available_locales || [],
    available_locales: mergedItem?.availableLocales || mergedItem?.available_locales || [],
    localized: Array.isArray(mergedItem?.localized) ? mergedItem.localized : [],
    slug,
    publicSlug: String(mergedItem?.publicSlug || slug).trim(),
    name: mergedItem?.name || [mergedItem?.brand, mergedItem?.model].filter(Boolean).join(' ').trim(),
    title: mergedItem?.title || mergedItem?.name || [mergedItem?.brand, mergedItem?.model].filter(Boolean).join(' ').trim(),
    brand: mergedItem?.brand || '',
    model: mergedItem?.model || '',
    vehicleGroupId: Number(mergedItem?.vehicleGroupId || 0) || null,
    year: mergedItem?.year || null,
    category: mergedItem?.category || '',
    path: resolvedPath,
    image,
    heroImage: image,
    gallery: gallery.length ? gallery : [image].filter(Boolean),
    price: Number(mergedItem?.priceFrom ?? mergedItem?.price ?? 0),
    prices: mergedItem?.prices || mergedItem?.pricing?.prices || null,
    currency: mergedItem?.currency || 'USD',
    rating: mergedItem?.reviewAggregate?.rating ?? mergedItem?.rating ?? null,
    reviewAggregate: mergedItem?.reviewAggregate || null,
    description: mergedItem?.longDescription || mergedItem?.description || '',
    videoUrl: mergedItem?.videoUrl || mergedItem?.mediaPack?.videoUrl || mergedItem?.video || '',
    tags: tags.length ? tags : normalizeVehicleTags(mergedItem?.tags || mergedItem?.salesTags || []),
    useCases: Array.isArray(mergedItem?.useCases) ? mergedItem.useCases : [],
    features: mergedItem?.features || mergedItem?.featureNames || mergedItem?.shortFeatures || [],
    featureKeys: Array.isArray(mergedItem?.featureKeys)
      ? mergedItem.featureKeys
      : Array.isArray(mergedItem?.filterMeta?.featureKeys)
        ? mergedItem.filterMeta.featureKeys
        : [],
    paymentMethods: Array.isArray(mergedItem?.paymentMethods)
      ? mergedItem.paymentMethods
      : Array.isArray(mergedItem?.filterMeta?.paymentMethods)
        ? mergedItem.filterMeta.paymentMethods
        : [],
    filterMeta: mergedItem?.filterMeta || null,
    filterFlags: mergedItem?.filterFlags || null,
    includedInPrice: [...includedInPrice]
      .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)),
    conditionReport: mergedItem?.conditionReport || null,
    suitabilityTags: mergedItem?.suitabilityTags || [],
    seo: mergedItem?.seo || null,
    specs: {
      seats: mergedItem?.seats || mergedItem?.specs?.seats || null,
      doors: mergedItem?.doors || mergedItem?.specs?.doors || null,
      transmission: mergedItem?.transmission || mergedItem?.specs?.transmission || null,
      fuel: mergedItem?.fuelType || mergedItem?.powertrain || mergedItem?.specs?.fuel || mergedItem?.specs?.engine || null,
      power: mergedItem?.driveType || mergedItem?.specs?.power || null,
      engine: mergedItem?.powertrain || mergedItem?.fuelType || mergedItem?.specs?.engine || null,
      luggage: mergedItem?.bags || mergedItem?.specs?.luggage || null,
    },
  }
}

function normalizeVehicleUseCases(useCases = []) {
  return [...(useCases || [])]
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
    .map((item) => ({
      ...item,
      desc: item.description || item.desc || '',
    }))
}

function buildVehicleCategoryOptions(categories = [], locale = DEFAULT_PUBLIC_LOCALE) {
  return (categories || []).map((value) => {
    const key = vehicleCategoryKeyMap[value]

    return {
      value,
      label: key ? resolvePublicUiValue(locale, `vehicles.categories.${key}`, value) : value,
    }
  })
}

async function importVehicleListingModule(locale = DEFAULT_PUBLIC_LOCALE) {
  const normalizedLocale = normalizePublicLocale(locale)

  if (!vehicleListingPromiseCache.has(normalizedLocale)) {
    const promise = (async () => {
      for (const candidateLocale of uniqueValues([normalizedLocale, DEFAULT_PUBLIC_LOCALE])) {
        const loader = vehicleListingModules[vehicleListingModuleKey(candidateLocale)]

        if (!loader) {
          continue
        }

        const module = await loader()
        const listing = module.vehicleListing || EMPTY_VEHICLE_LISTING

        return {
          locale: normalizePublicLocale(listing?.locale || candidateLocale),
          fleetCategories: module.fleetCategories || listing?.fleetCategories || [],
          fleetGalleryImages: module.fleetGalleryImages || listing?.fleetGalleryImages || [],
          fleetUseCases: module.fleetUseCases || listing?.fleetUseCases || [],
          fleetVehicles: module.fleetVehicles || listing?.fleetVehicles || [],
          vehicleItems: module.vehicleItems || listing?.vehicleItems || [],
          vehiclesIndex: module.vehiclesIndex || listing?.vehiclesIndex || [],
        }
      }

      return emptyVehicleListing()
    })()

    vehicleListingPromiseCache.set(normalizedLocale, promise)
  }

  return vehicleListingPromiseCache.get(normalizedLocale)
}

async function importVehicleDetailModule(contentKey, locale = DEFAULT_PUBLIC_LOCALE, routeEntry = null) {
  const normalizedContentKey = String(contentKey || '').trim()

  if (!normalizedContentKey) {
    return null
  }

  const cacheKey = `${normalizedContentKey}:${normalizePublicLocale(locale)}`

  if (!vehicleDetailPromiseCache.has(cacheKey)) {
    const promise = (async () => {
      const fallbackLocale = resolveLocalizedRouteEntry(routeEntry, locale)?.locale
        || resolveLocalizedRouteEntry(routeEntry, DEFAULT_PUBLIC_LOCALE)?.locale
        || DEFAULT_PUBLIC_LOCALE

      for (const candidateLocale of uniqueValues([
        normalizePublicLocale(locale),
        fallbackLocale,
        DEFAULT_PUBLIC_LOCALE,
      ])) {
        const loader = vehicleDetailModules[vehicleDetailModuleKey(normalizedContentKey, candidateLocale)]

        if (!loader) {
          continue
        }

        const module = await loader()

        if (module?.vehicleDetail) {
          return module.vehicleDetail
        }
      }

      return null
    })()

    vehicleDetailPromiseCache.set(cacheKey, promise)
  }

  return vehicleDetailPromiseCache.get(cacheKey)
}

function vehiclePageContent(page) {
  return page || EMPTY_VEHICLE_PAGE
}

function vehicleListingContent(page) {
  return vehiclePageContent(page)?.structuredContent?.ui || EMPTY_VEHICLE_LISTING_CONTENT
}

function vehicleDetailContent(page) {
  return vehiclePageContent(page)?.structuredContent?.detail || EMPTY_VEHICLE_DETAIL_CONTENT
}

export async function loadVehicleListingSnapshot(locale = DEFAULT_PUBLIC_LOCALE) {
  return importVehicleListingModule(locale)
}

export async function loadVehicleDetailSnapshot(contentKey, locale = DEFAULT_PUBLIC_LOCALE, routeEntry = null) {
  return importVehicleDetailModule(contentKey, locale, routeEntry)
}

export async function loadResolvedVehicleDetail(identifier, locale = DEFAULT_PUBLIC_LOCALE, sectionPath = '') {
  const routeEntry = resolveVehicleRoute(identifier)

  if (!routeEntry) {
    return null
  }

  const detail = await loadVehicleDetailSnapshot(routeEntry.contentKey || routeEntry.entityId, locale, routeEntry)

  if (!detail) {
    return resolveFleetVehicle(routeEntry.contentKey || routeEntry.entityId, locale, sectionPath)
  }

  return normalizeVehicleRecord(detail, locale, sectionPath)
}

export const vehicleDetailUi = {
  backLabel: '',
  showAllLabel: '',
  view360ButtonLabel: '',
  playVideoButtonLabel: '',
  mediaEmptyLabel: '',
  dailyRateLabel: '',
  pricePerDaySuffix: '',
  rentalPeriodLabel: '',
  pickupLabel: '',
  dropoffLabel: '',
  daySingularLabel: resolvePublicUiValue('en', 'common.day'),
  dayPluralLabel: resolvePublicUiValue('en', 'common.days'),
  totalDaysLabel: '',
  confirmDatesLabel: '',
  weeklyDiscountAppliedLabel: '',
  weeklyDiscountProgressPrefix: '',
  weeklyDiscountProgressSuffix: '',
  weeklyDiscountLineLabel: '',
  totalLabel: resolvePublicUiValue('en', 'vehicles.total'),
  bookingCtaLabel: '',
  bookingFootnote: '',
  capacityLabel: '',
  adultsLabel: '',
  gearboxLabel: '',
  fuelTypeLabel: '',
  driveLabel: '',
  powertrainLabel: '',
  luggageSpaceLabel: '',
  totalBagsLabel: '',
  includedInPriceTitle: '',
  conditionReportTitle: '',
  conditionReportVerifiedLabel: '',
  featuresTitle: '',
  perfectForTitle: '',
  availableExtrasTitle: '',
  availableExtrasHint: '',
  availableExtrasEmptyTitle: '',
  availableExtrasEmptyDescription: '',
  reviewsTitle: '',
  reviewsHint: '',
  reviewsEmptyTitle: '',
  reviewsEmptyDescription: '',
  reviewSingularLabel: '',
  reviewPluralLabel: '',
  mobileTotalPrefix: '',
  mobileDiscountLabel: '',
  mobileBookingCtaLabel: '',
  view360Title: '',
  view360Description: '',
  view360DragHint: '',
}

export const vehicleBookingBuilderUi = {
  pickupLocationLabel: resolvePublicUiValue('en', 'vehicles.pickupLocation'),
  dropoffLocationLabel: resolvePublicUiValue('en', 'vehicles.dropoffLocation'),
  pickupTimeLabel: resolvePublicUiValue('en', 'vehicles.pickupTime'),
  dropoffTimeLabel: resolvePublicUiValue('en', 'vehicles.dropoffTime'),
  sameLocationLabel: resolvePublicUiValue('en', 'vehicles.sameLocation'),
  livePricingLabel: resolvePublicUiValue('en', 'vehicles.livePricing'),
  livePricingLoadingLabel: resolvePublicUiValue('en', 'vehicles.livePricingLoading'),
  livePricingUpdatingLabel: resolvePublicUiValue('en', 'vehicles.livePricingUpdating'),
  livePricingUnavailableLabel: resolvePublicUiValue('en', 'vehicles.livePricingUnavailable'),
  livePricingFootnoteLabel: resolvePublicUiValue('en', 'vehicles.livePricingFootnote'),
  rateBandLabel: resolvePublicUiValue('en', 'vehicles.rateBand'),
  depositLabel: resolvePublicUiValue('en', 'vehicles.securityDeposit'),
  dueAfterApprovalLabel: resolvePublicUiValue('en', 'vehicles.dueAfterApproval'),
  selectLocationLabel: resolvePublicUiValue('en', 'vehicles.selectLocation'),
}

export const vehicleCatalogUi = {
  heroBadge: '',
  heroTitle: '',
  heroTitleLead: '',
  heroTitleAccent: '',
  heroDescription: '',
  headerTitle: '',
  searchPlaceholder: '',
  journeyTitle: '',
  maxPriceLabel: '',
  sortByLabel: '',
  sortRecommendedLabel: '',
  sortPriceLowLabel: '',
  sortPriceHighLabel: '',
  sortRatingLabel: '',
  resultsSingularLabel: resolvePublicUiValue('en', 'vehicles.compareVehicleSingular'),
  resultsPluralLabel: resolvePublicUiValue('en', 'vehicles.compareVehiclePlural'),
  defaultLocationLabel: '',
  dailyRateLabel: '',
  pricePerDaySuffix: '',
  imageComingSoonLabel: resolvePublicUiValue('en', 'vehicles.imageComingSoon'),
  daySingularLabel: resolvePublicUiValue('en', 'common.day'),
  dayPluralLabel: resolvePublicUiValue('en', 'common.days'),
  totalLabel: resolvePublicUiValue('en', 'vehicles.total'),
  bookLabel: '',
  unavailableLabel: '',
  continueLabel: '',
  trustBannerRateLabel: '',
  trustBannerQuoteLabel: '',
  trustBannerSupportLabel: '',
  compareLimitMessage: '',
  compareTitle: '',
  compareSelectedTemplate: resolvePublicUiValue('en', 'vehicles.compareSelectedTemplate'),
  compareClearAllLabel: '',
  compareNowLabel: '',
  compareAddVehicleLabel: '',
  compareActionAddLabel: '',
  compareActionRemoveLabel: '',
  newArrivalBadgeLabel: '',
  hotDealBadgeLabel: '',
  emptyTitle: '',
  emptyDescription: '',
  clearFiltersLabel: '',
  locationLabel: resolvePublicUiValue('en', 'vehicles.location'),
  datesLabel: resolvePublicUiValue('en', 'vehicles.dates'),
  applyDatesLabel: resolvePublicUiValue('en', 'vehicles.applyDates'),
  pickupPlaceholderLabel: resolvePublicUiValue('en', 'vehicles.pickup'),
  dropoffPlaceholderLabel: resolvePublicUiValue('en', 'vehicles.dropoff'),
  brandLabel: resolvePublicUiValue('en', 'vehicles.brand'),
  seatsLabel: resolvePublicUiValue('en', 'vehicles.seats'),
  transmissionLabel: resolvePublicUiValue('en', 'vehicles.transmission'),
  engineLabel: resolvePublicUiValue('en', 'vehicles.engine'),
  featuresLabel: resolvePublicUiValue('en', 'vehicles.features'),
  conditionsLabel: resolvePublicUiValue('en', 'vehicles.rentalConditions'),
  resultsFoundLabel: resolvePublicUiValue('en', 'vehicles.resultsFound'),
  compareYearLabel: resolvePublicUiValue('en', 'vehicles.year'),
  compareTypeLabel: resolvePublicUiValue('en', 'vehicles.type'),
  compareSeatsLabel: resolvePublicUiValue('en', 'vehicles.seats'),
  compareTransmissionLabel: resolvePublicUiValue('en', 'vehicles.transmission'),
  compareEngineLabel: resolvePublicUiValue('en', 'vehicles.engine'),
  compareFeaturesLabel: resolvePublicUiValue('en', 'vehicles.keyFeatures'),
  compareOptionsLabel: resolvePublicUiValue('en', 'vehicles.options'),
  compareBrowseLabel: resolvePublicUiValue('en', 'vehicles.browseCars'),
  compareAddDescription: resolvePublicUiValue('en', 'vehicles.compareAddDescription'),
}

export const vehicleSortOptions = []

export const vehicleTrustCards = []

function normalizeVehicleRentalExtras(extrasCatalog = []) {
  return (Array.isArray(extrasCatalog) ? extrasCatalog : [])
    .filter((item) => item.group !== 'included')
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
    .map((item) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      description: item.description,
      price: item.price,
      pricingType: item.pricingType,
      iconKey: item.iconKey,
      kind: item.kind,
      kindLabel: item.kindLabel,
      group: item.group,
      sortOrder: item.sortOrder || 0,
    }))
}

export function resolveFleetVehicle(id, locale = DEFAULT_PUBLIC_LOCALE, sectionPath = '') {
  const routeEntry = resolveVehicleRoute(id)

  if (!routeEntry) {
    return null
  }

  return normalizeVehicleRecord({
    id: routeEntry.contentKey || routeEntry.entityId,
    contentKey: routeEntry.contentKey,
    content_key: routeEntry.contentKey,
    entityId: routeEntry.entityId,
    entity_id: routeEntry.entityId,
    availableLocales: routeEntry.availableLocales,
    available_locales: routeEntry.available_locales,
    localized: routeEntry.localized,
    seo: {
      canonical: resolveLocalizedRouteEntry(routeEntry, locale)?.canonical || routeEntry.canonical || '',
      hreflang: buildVehicleHreflang(routeEntry),
      xDefault: routeEntry.xDefault || routeEntry.x_default || '',
    },
    path: resolveVehiclePathFromRoute(routeEntry, locale, sectionPath),
  }, locale, sectionPath)
}

export function buildVehicleDetailSeo(vehicle, locale = DEFAULT_PUBLIC_LOCALE, origin = '') {
  const car = normalizeVehicleRecord(vehicle, locale)
  const siteOrigin = absoluteOrigin(origin)
  const localized = Array.isArray(car?.localized) ? car.localized : []
  const activeLocalized = localized.find((entry) => normalizePublicLocale(entry?.locale) === normalizePublicLocale(locale))
    || localized.find((entry) => normalizePublicLocale(entry?.locale) === DEFAULT_PUBLIC_LOCALE)
    || localized[0]
  const canonicalPath = activeLocalized?.path || car?.path || ''
  const hreflang = Array.isArray(car?.seo?.hreflang) && car.seo.hreflang.length
    ? car.seo.hreflang
    : localized
      .filter((entry) => entry?.locale && (entry?.href || entry?.path))
      .map((entry) => ({
        locale: entry.locale,
        href: entry.href || `${siteOrigin}${entry.path}`,
      }))
  const defaultHref = car?.seo?.xDefault
    || localized.find((entry) => normalizePublicLocale(entry?.locale) === DEFAULT_PUBLIC_LOCALE)?.href
    || (canonicalPath ? `${siteOrigin}${canonicalPath}` : '')

  return {
    title: car?.seo?.title || `${car?.name || 'Vehicle'} Rental in Georgia | bent.ge`,
    description: car?.seo?.description || car?.description || '',
    ogTitle: car?.seo?.ogTitle || car?.seo?.title || `${car?.name || 'Vehicle'} Rental in Georgia | bent.ge`,
    ogDescription: car?.seo?.ogDescription || car?.seo?.description || car?.description || '',
    ogImage: car?.seo?.ogImage || car?.heroImage || car?.image || '',
    canonical: activeLocalized?.href || car?.seo?.canonical || (canonicalPath ? `${siteOrigin}${canonicalPath}` : ''),
    hreflang,
    xDefault: defaultHref,
    robots: car?.seo?.robots || 'index,follow',
  }
}

export function formatVehicleResultsLabel(count) {
  const singular = vehicleCatalogUi.resultsSingularLabel || resolvePublicUiValue('en', 'vehicles.compareVehicleSingular')
  const plural = vehicleCatalogUi.resultsPluralLabel || resolvePublicUiValue('en', 'vehicles.compareVehiclePlural')
  return `${count} ${count === 1 ? singular : plural}`
}

export function formatVehicleCompareSelectedLabel(count, max = 3) {
  return String(vehicleCatalogUi.compareSelectedTemplate || resolvePublicUiValue('en', 'vehicles.compareSelectedTemplate'))
    .replace('{count}', String(count))
    .replace('{max}', String(max))
}

export function normalizeVehicleDetailUi(detailContent = EMPTY_VEHICLE_DETAIL_CONTENT, locale = DEFAULT_PUBLIC_LOCALE) {
  return {
    ...vehicleDetailUi,
    ...detailContent,
    daySingularLabel: detailContent.daySingularLabel || resolvePublicUiValue(locale, 'common.day'),
    dayPluralLabel: detailContent.dayPluralLabel || resolvePublicUiValue(locale, 'common.days'),
    totalLabel: detailContent.totalLabel || resolvePublicUiValue(locale, 'vehicles.total'),
  }
}

export function normalizeVehicleBookingBuilderUi(locale = DEFAULT_PUBLIC_LOCALE) {
  return {
    pickupLocationLabel: resolvePublicUiValue(locale, 'vehicles.pickupLocation'),
    dropoffLocationLabel: resolvePublicUiValue(locale, 'vehicles.dropoffLocation'),
    pickupTimeLabel: resolvePublicUiValue(locale, 'vehicles.pickupTime'),
    dropoffTimeLabel: resolvePublicUiValue(locale, 'vehicles.dropoffTime'),
    sameLocationLabel: resolvePublicUiValue(locale, 'vehicles.sameLocation'),
    livePricingLabel: resolvePublicUiValue(locale, 'vehicles.livePricing'),
    livePricingLoadingLabel: resolvePublicUiValue(locale, 'vehicles.livePricingLoading'),
    livePricingUpdatingLabel: resolvePublicUiValue(locale, 'vehicles.livePricingUpdating'),
    livePricingUnavailableLabel: resolvePublicUiValue(locale, 'vehicles.livePricingUnavailable'),
    livePricingFootnoteLabel: resolvePublicUiValue(locale, 'vehicles.livePricingFootnote'),
    rateBandLabel: resolvePublicUiValue(locale, 'vehicles.rateBand'),
    depositLabel: resolvePublicUiValue(locale, 'vehicles.securityDeposit'),
    dueAfterApprovalLabel: resolvePublicUiValue(locale, 'vehicles.dueAfterApproval'),
    selectLocationLabel: resolvePublicUiValue(locale, 'vehicles.selectLocation'),
  }
}

export function normalizeVehicleCatalogUi(page = EMPTY_VEHICLE_PAGE, locale = DEFAULT_PUBLIC_LOCALE) {
  const localizedPage = vehiclePageContent(page)
  const listingContent = vehicleListingContent(localizedPage)
  const detailContent = vehicleDetailContent(localizedPage)
  const titleParts = splitHeroTitle(localizedPage?.title)

  return {
    ...vehicleCatalogUi,
    heroBadge: listingContent.heroBadge || localizedPage?.subtitle || '',
    heroTitle: localizedPage?.title || '',
    heroTitleLead: titleParts.lead,
    heroTitleAccent: titleParts.accent,
    heroDescription: localizedPage?.excerpt || '',
    headerTitle: listingContent.headerTitle,
    searchPlaceholder: listingContent.searchPlaceholder,
    journeyTitle: listingContent.journeyTitle,
    maxPriceLabel: listingContent.maxPriceLabel,
    sortByLabel: listingContent.sortByLabel,
    sortRecommendedLabel: listingContent.sortRecommendedLabel,
    sortPriceLowLabel: listingContent.sortPriceLowLabel,
    sortPriceHighLabel: listingContent.sortPriceHighLabel,
    sortRatingLabel: listingContent.sortRatingLabel,
    resultsSingularLabel: listingContent.resultsSingularLabel || resolvePublicUiValue(locale, 'vehicles.compareVehicleSingular'),
    resultsPluralLabel: listingContent.resultsPluralLabel || resolvePublicUiValue(locale, 'vehicles.compareVehiclePlural'),
    defaultLocationLabel: listingContent.defaultLocationLabel,
    dailyRateLabel: listingContent.dailyRateLabel,
    pricePerDaySuffix: listingContent.pricePerDaySuffix,
    imageComingSoonLabel: listingContent.imageComingSoonLabel || detailContent.imageComingSoonLabel || resolvePublicUiValue(locale, 'vehicles.imageComingSoon'),
    daySingularLabel: detailContent.daySingularLabel || resolvePublicUiValue(locale, 'common.day'),
    dayPluralLabel: detailContent.dayPluralLabel || resolvePublicUiValue(locale, 'common.days'),
    totalLabel: detailContent.totalLabel || resolvePublicUiValue(locale, 'vehicles.total'),
    bookLabel: listingContent.bookLabel,
    unavailableLabel: listingContent.unavailableLabel,
    continueLabel: listingContent.continueLabel,
    trustBannerRateLabel: listingContent.trustBannerRateLabel,
    trustBannerQuoteLabel: listingContent.trustBannerQuoteLabel,
    trustBannerSupportLabel: listingContent.trustBannerSupportLabel,
    compareLimitMessage: listingContent.compareLimitMessage,
    compareTitle: listingContent.compareTitle,
    compareSelectedTemplate: listingContent.compareSelectedTemplate || resolvePublicUiValue(locale, 'vehicles.compareSelectedTemplate'),
    compareClearAllLabel: listingContent.compareClearAllLabel,
    compareNowLabel: listingContent.compareNowLabel,
    compareAddVehicleLabel: listingContent.compareAddVehicleLabel,
    compareActionAddLabel: listingContent.compareActionAddLabel,
    compareActionRemoveLabel: listingContent.compareActionRemoveLabel,
    newArrivalBadgeLabel: listingContent.newArrivalBadgeLabel,
    hotDealBadgeLabel: listingContent.hotDealBadgeLabel,
    emptyTitle: listingContent.emptyTitle,
    emptyDescription: listingContent.emptyDescription,
    clearFiltersLabel: listingContent.clearFiltersLabel,
    locationLabel: resolvePublicUiValue(locale, 'vehicles.location'),
    datesLabel: resolvePublicUiValue(locale, 'vehicles.dates'),
    applyDatesLabel: resolvePublicUiValue(locale, 'vehicles.applyDates'),
    pickupPlaceholderLabel: resolvePublicUiValue(locale, 'vehicles.pickup'),
    dropoffPlaceholderLabel: resolvePublicUiValue(locale, 'vehicles.dropoff'),
    brandLabel: resolvePublicUiValue(locale, 'vehicles.brand'),
    seatsLabel: resolvePublicUiValue(locale, 'vehicles.seats'),
    transmissionLabel: resolvePublicUiValue(locale, 'vehicles.transmission'),
    engineLabel: resolvePublicUiValue(locale, 'vehicles.engine'),
    featuresLabel: resolvePublicUiValue(locale, 'vehicles.features'),
    conditionsLabel: resolvePublicUiValue(locale, 'vehicles.rentalConditions'),
    resultsFoundLabel: resolvePublicUiValue(locale, 'vehicles.resultsFound'),
    compareYearLabel: resolvePublicUiValue(locale, 'vehicles.year'),
    compareTypeLabel: resolvePublicUiValue(locale, 'vehicles.type'),
    compareSeatsLabel: resolvePublicUiValue(locale, 'vehicles.seats'),
    compareTransmissionLabel: resolvePublicUiValue(locale, 'vehicles.transmission'),
    compareEngineLabel: resolvePublicUiValue(locale, 'vehicles.engine'),
    compareFeaturesLabel: resolvePublicUiValue(locale, 'vehicles.keyFeatures'),
    compareOptionsLabel: resolvePublicUiValue(locale, 'vehicles.options'),
    compareBrowseLabel: resolvePublicUiValue(locale, 'vehicles.browseCars'),
    compareAddDescription: resolvePublicUiValue(locale, 'vehicles.compareAddDescription'),
  }
}

function buildVehicleSortOptions(ui) {
  return [
    { value: 'recommended', label: ui.sortRecommendedLabel },
    { value: 'price-low', label: ui.sortPriceLowLabel },
    { value: 'price-high', label: ui.sortPriceHighLabel },
    { value: 'rating', label: ui.sortRatingLabel },
  ].filter((option) => option.label)
}

function formatVehicleResultsLabelWithUi(count, ui, locale = DEFAULT_PUBLIC_LOCALE) {
  const singular = ui.resultsSingularLabel || resolvePublicUiValue(locale, 'vehicles.compareVehicleSingular')
  const plural = ui.resultsPluralLabel || resolvePublicUiValue(locale, 'vehicles.compareVehiclePlural')
  return `${count} ${count === 1 ? singular : plural}`
}

function formatVehicleCompareSelectedLabelWithUi(count, max, ui, locale = DEFAULT_PUBLIC_LOCALE) {
  return String(ui.compareSelectedTemplate || resolvePublicUiValue(locale, 'vehicles.compareSelectedTemplate'))
    .replace('{count}', String(count))
    .replace('{max}', String(max))
}

export function useVehiclesContent() {
  const { locale } = usePublicLocale()
  const resolvedVehiclesPage = useResolvedPage('vehicles')
  const vehiclesPageRef = computed(() => resolvedVehiclesPage.value || EMPTY_VEHICLE_PAGE)

  const { data: listingData } = useAsyncData(
    'vehicles-listing',
    () => loadVehicleListingSnapshot(locale.value),
    {
      watch: [locale],
      default: () => emptyVehicleListing(),
    },
  )
  const { data: extrasData } = useAsyncData(
    () => `vehicles-extras:${normalizePublicLocale(locale.value)}`,
    () => loadExtrasLocaleExport(locale.value),
    {
      watch: [locale],
      default: () => [],
    },
  )

  const vehicleListingRef = computed(() => listingData.value || EMPTY_VEHICLE_LISTING)
  const vehicleRentalExtrasRef = computed(() => normalizeVehicleRentalExtras(extrasData.value))
  const fleetVehiclesRef = computed(() => (vehicleListingRef.value.fleetVehicles || [])
    .map((item) => normalizeVehicleRecord(item, locale.value, vehiclesPageRef.value?.path || '/vehicles'))
    .filter(Boolean))
  const fleetUseCasesRef = computed(() => {
    const useCases = vehicleListingRef.value.fleetUseCases?.length
      ? vehicleListingRef.value.fleetUseCases
      : (vehiclesPageRef.value?.structuredContent?.ui?.useCases || [])

    return normalizeVehicleUseCases(useCases)
  })
  const vehicleTrustCardsRef = computed(() => [...(vehiclesPageRef.value?.structuredContent?.trustCards || [])]
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)))

  const vehicleCatalogUiRef = computed(() => normalizeVehicleCatalogUi(vehiclesPageRef.value, locale.value))
  const vehicleDetailUiRef = computed(() => normalizeVehicleDetailUi(vehicleDetailContent(vehiclesPageRef.value), locale.value))
  const vehicleBookingBuilderUiRef = computed(() => normalizeVehicleBookingBuilderUi(locale.value))
  const vehicleSortOptionsRef = computed(() => buildVehicleSortOptions(vehicleCatalogUiRef.value))

  function formatResultsLabel(count) {
    return formatVehicleResultsLabelWithUi(count, vehicleCatalogUiRef.value, locale.value)
  }

  function formatCompareSelectedLabel(count, max = 3) {
    return formatVehicleCompareSelectedLabelWithUi(count, max, vehicleCatalogUiRef.value, locale.value)
  }

  return {
    vehiclesPage: vehiclesPageRef,
    vehiclesIndex: fleetVehiclesRef,
    fleetVehicles: fleetVehiclesRef,
    fleetCategories: computed(() => buildVehicleCategoryOptions(vehicleListingRef.value.fleetCategories || [], locale.value)),
    fleetUseCases: fleetUseCasesRef,
    vehicleCatalogUi: vehicleCatalogUiRef,
    vehicleDetailUi: vehicleDetailUiRef,
    vehicleBookingBuilderUi: vehicleBookingBuilderUiRef,
    vehicleSortOptions: vehicleSortOptionsRef,
    vehicleRentalExtras: vehicleRentalExtrasRef,
    vehicleTrustCards: vehicleTrustCardsRef,
    formatVehicleResultsLabel: formatResultsLabel,
    formatVehicleCompareSelectedLabel: formatCompareSelectedLabel,
  }
}
