import { useAsyncData } from '#imports'
import { computed } from 'vue'
import { loadExtrasLocaleExport } from '~/content/extras-export'
import { loadHomeLocaleExport } from '~/content/home-export'
import { resolveOfferPresentation } from '~/content/offerPresentation'
import { resolveOfferPricingSummary, resolveOfferPricingTiers } from '~/content/offer-pricing'
import { resolveOfferMediaUrl } from '~/content/offer-media'
import { loadVehicleListingSnapshot } from '~/content/vehicles'
import { formatContentDate, toPublicIntlLocale } from '~/content/utils'
import { usePublicLocale } from '~/composables/usePublicLocale'
import { resolvePublicUiValue } from '~/i18n/public-ui'
import { normalizePublicLocale, toPublicLocaleCode } from '~/utils/public-locales'
import { normalizePublicInternalPath } from '~/utils/public-routes'

const HOME_HERO_RIGHT_IMAGE = '/content/home/home-hero-range-rover.webp'

function pickHomeBlock(homeBlocks = [], identifier) {
  const normalizedIdentifier = String(identifier || '').trim()

  const matches = [...homeBlocks].reverse().filter((block) => {
    const contentKey = String(block?.contentKey || '').trim()
    const slug = String(block?.slug || '').trim()
    const publicSlug = String(block?.publicSlug || '').trim()

    return contentKey === normalizedIdentifier || slug === normalizedIdentifier || publicSlug === normalizedIdentifier
  })
  return matches.find((block) => Object.keys(block.structuredContent || {}).length > 0) || matches[0] || null
}

function formatArticleDate(value, locale = 'en-US') {
  if (!value) {
    return null
  }

  return formatContentDate(value, locale)
}

function formatUsdPrice(value, locale = 'en-US') {
  const amount = Number(value)

  if (!Number.isFinite(amount)) {
    return null
  }

  const hasFraction = Math.abs(amount % 1) > 0.001

  return `$${new Intl.NumberFormat(locale, {
    minimumFractionDigits: hasFraction ? 2 : 0,
    maximumFractionDigits: 2,
  }).format(amount)}`
}

function toIntlLocale(locale) {
  const normalized = String(locale || 'en').toLowerCase()

  return {
    en: 'en-US',
    fr: 'fr-FR',
    es: 'es-ES',
    ru: 'ru-RU',
    de: 'de-DE',
    ka: 'ka-GE',
    it: 'it-IT',
    ar: 'ar',
    he: 'he-IL',
    pl: 'pl-PL',
    tr: 'tr-TR',
  }[normalized] || 'en-US'
}

function localizeArticleCategory(value, locale = 'en') {
  const resolvedValue = String(value || '').trim()
  const path = {
    article: 'news.categoryArticles',
    articles: 'news.categoryArticles',
    news: 'news.categoryNews',
  }[resolvedValue.toLowerCase()]

  if (!path) {
    return resolvedValue
  }

  return resolvePublicUiValue(locale, path, resolvedValue)
}

function formatArticleReadTime(article = {}, locale = 'en') {
  const numericMinutes = Number(article?.readTimeMinutes || parseInt(String(article?.readTime || ''), 10))

  if (!Number.isFinite(numericMinutes) || numericMinutes <= 0) {
    return String(article?.readTime || '').trim() || null
  }

  return resolvePublicUiValue(locale, 'news.readTimeMinutesTemplate', '{count} min read')
    .replace('{count}', String(numericMinutes))
}

function groupItemsByKey(items = [], resolveKey = (item) => item?.contentKey || item?.slug || item?.id) {
  const groups = new Map()

  for (const item of items) {
    const key = String(resolveKey(item) || '').trim()

    if (!key) {
      continue
    }

    if (!groups.has(key)) {
      groups.set(key, [])
    }

    groups.get(key).push(item)
  }

  return groups
}

function pickLocaleArticle(group = [], locale = 'en') {
  return group.find((item) => item?.locale === locale)
    || group.find((item) => item?.locale === 'en')
    || group[0]
    || null
}

function normalizeNewsArticleImage(article = {}) {
  return article?.image || article?.cardImage || article?.heroImage || article?.featuredImage || ''
}

function resolveNewsArticleHref(article = {}, locale = 'en') {
  const sourceLocale = normalizePublicLocale(article?.locale || locale)
  const fallbackPath = article?.path || ''

  return fallbackPath ? normalizePublicInternalPath(fallbackPath, sourceLocale) : ''
}

function normalizeHomeArticleCard(article = {}, locale = 'en') {
  const sourceLocale = normalizePublicLocale(article?.locale || locale)
  const requestedLocale = normalizePublicLocale(locale)

  return {
    id: article.slug || article.id,
    title: article.title,
    excerpt: article.excerpt,
    category: localizeArticleCategory(article.category, locale),
    date: formatArticleDate(article.publishedAt, toIntlLocale(locale)),
    readTime: formatArticleReadTime(article, locale),
    image: normalizeNewsArticleImage(article),
    href: resolveNewsArticleHref(article, locale),
    sourceLocale,
    sourceLocaleCode: toPublicLocaleCode(sourceLocale),
    isFallback: sourceLocale !== requestedLocale,
  }
}

function normalizePreferredArticleKeys(keys = []) {
  return Array.isArray(keys)
    ? keys.map((value) => String(value || '').trim()).filter(Boolean)
    : []
}

function resolveHomeArticleKey(item = {}) {
  return item?.contentKey || item?.slug || item?.id
}

function resolveHomeFeaturedArticles(featuredArticles = [], locale = 'en', limit = 6, preferredKeys = []) {
  const normalizedLocale = String(locale || 'en').trim().toLowerCase()
  const picked = []
  const seenKeys = new Set()
  const groupedFeaturedArticles = groupItemsByKey(featuredArticles, resolveHomeArticleKey)

  const appendFrom = (items) => {
    for (const [key, group] of groupItemsByKey(items, resolveHomeArticleKey)) {
      if (seenKeys.has(key)) {
        continue
      }

      const article = pickLocaleArticle(group, normalizedLocale)

      if (!article) {
        continue
      }

      picked.push(article)
      seenKeys.add(key)

      if (picked.length >= limit) {
        break
      }
    }
  }

  for (const key of normalizePreferredArticleKeys(preferredKeys)) {
    if (seenKeys.has(key)) {
      continue
    }

    const article = pickLocaleArticle(groupedFeaturedArticles.get(key) || [], normalizedLocale)

    if (!article) {
      continue
    }

    picked.push(article)
    seenKeys.add(key)

    if (picked.length >= limit) {
      return picked.slice(0, limit)
    }
  }

  appendFrom(featuredArticles)

  return picked.slice(0, limit)
}

const heroCarTypeIcons = {
  SEDAN: 'sedan',
  PREMIUM: 'premium',
  SUV: 'suv',
  MINIVAN: 'minivan',
}

const budgetTierByOptionId = {
  any: 'budget_any',
  under_50: 'budget_low',
  '50_100': 'budget_mid',
  over_100: 'budget_high',
}

const homeFleetPerformanceBySlug = {
  'range-rover-3g-range-rover-3g': {
    power: '335 HP',
    acceleration: '6.9s',
    topSpeed: '209 km/h',
  },
  'range-rover-range-rover-range-rover': {
    power: '395 HP',
    acceleration: '5.9s',
    topSpeed: '225 km/h',
  },
  'range-rover-sport-range-rover-sport': {
    power: '355 HP',
    acceleration: '6.0s',
    topSpeed: '225 km/h',
  },
}

function normalizeHomeOfferCard(item, section = {}, locale = 'en') {
  const presentation = resolveOfferPresentation(item.slug, {
    discount: section.defaultBadgeLabel || '',
    validUntil: section.defaultValidityLabel || '',
  })
  const localeKey = toIntlLocale(locale)
  const structuredPresentation = item?.structuredContent?.presentation || {}
  const structuredHomeCard = structuredPresentation.homeCard || {}
  const structuredSocialProof = item?.structuredContent?.socialProof || {}
  const structuredPricingPresentation = item?.structuredContent?.pricingPresentation || {}
  const pricingSummary = resolveOfferPricingSummary(item)
  const pricingTiers = resolveOfferPricingTiers(item)

  return {
    id: item.slug || item.id,
    slug: item.slug || item.id,
    name: item.title,
    subtitle: item.subtitle || '',
    relatedVehicle: item.relatedVehicle || item.recommendedVehicle || item?.structuredContent?.relatedVehicle || item?.structuredContent?.recommendedVehicle || null,
    category: item.category || section.defaultBadgeLabel || '',
    image: resolveOfferMediaUrl(item, 'card'),
    badge: item.badge || presentation.discount || section.defaultBadgeLabel || '',
    discountLabel: structuredPresentation.discountLabel || item?.structuredContent?.badge || item.badge || presentation.discount || '',
    oldPriceValue: pricingSummary.oldPriceValue || Number(item.oldPrice || structuredHomeCard.oldPrice || 0) || null,
    newPriceValue: pricingSummary.newPriceValue || Number(item.currentPrice || structuredHomeCard.newPrice || 0) || null,
    oldPrice: pricingSummary.oldPriceValue ? formatUsdPrice(pricingSummary.oldPriceValue, localeKey) : (structuredHomeCard.oldPrice ? formatUsdPrice(structuredHomeCard.oldPrice, localeKey) : presentation.oldPrice),
    newPrice: pricingSummary.newPriceValue ? formatUsdPrice(pricingSummary.newPriceValue, localeKey) : (structuredHomeCard.newPrice ? formatUsdPrice(structuredHomeCard.newPrice, localeKey) : presentation.newPrice),
    pricingLabel: structuredPricingPresentation.label || '',
    socialProofLabel: structuredSocialProof.label || '',
    validUntil: item.validity || presentation.validUntil || section.defaultValidityLabel,
    rating: item.rating ?? null,
    reviews: item.socialProof?.reviews ?? null,
    tags: structuredPresentation.tags || presentation.tags || [],
    description: item.excerpt || item.body || section.pricingDetailsLabel || '',
    ctaLabel: item.cta?.label || section.offerDetailsLabel || '',
    ctaUrl: normalizePublicInternalPath(item.cta?.url || item.path || '/offers', locale),
    pricingTiers,
  }
}

function normalizeHomeFleetVehicle(item, locale = 'en') {
  const slug = item.slug || item.id
  const performance = homeFleetPerformanceBySlug[slug] || {}
  const tags = []
  const homeTypes = Array.from(new Set(
    (Array.isArray(item.homeTypes) && item.homeTypes.length ? item.homeTypes : [item.homeCategory || item.category || ''])
      .map((value) => String(value || '').trim())
      .filter(Boolean),
  ))
  const category = item.homeCategory || homeTypes[0] || item.category || ''
  const homeSortOrder = Number.isFinite(Number(item.homeSortOrder)) ? Number(item.homeSortOrder) : null
  const includedInPrice = Array.isArray(item.includedInPrice)
    ? item.includedInPrice
    : Array.isArray(item.filterMeta?.includedInPrice)
      ? item.filterMeta.includedInPrice
      : []
  const isPremium = category === 'Premium' || homeTypes.includes('Premium')

  if (isPremium) {
    tags.push('PREMIUM')
  }

  return {
    id: slug,
    slug,
    vehicleGroupId: Number(item.vehicleGroupId || 0) || null,
    contentKey: item.contentKey || item.content_key || item.entityId || item.entity_id || slug,
    entityId: item.entityId || item.entity_id || item.contentKey || item.content_key || slug,
    name: item.name || [item.brand, item.model].filter(Boolean).join(' '),
    category,
    homeTypes,
    homeSortOrder,
    price: Number(item.priceFrom ?? item.price ?? 0),
    priceFrom: Number(item.priceFrom ?? item.baseDailyRate ?? item.price ?? 0),
    baseDailyRate: Number(item.baseDailyRate ?? item.priceFrom ?? item.price ?? 0),
    displayPriceFrom: Number(item.displayPriceFrom ?? item.price ?? item.priceFrom ?? 0),
    fuelConsumptionPer100Km: item.fuelConsumptionPer100Km ?? item.filterMeta?.specs?.fuelConsumptionPer100Km ?? null,
    currency: item.currency || 'USD',
    image: item.heroImage || item.image || item.cardImage,
    description: item.longDescription || item.description || '',
    tags,
    paymentMethods: Array.isArray(item.paymentMethods) ? item.paymentMethods : [],
    featureKeys: Array.isArray(item.featureKeys) ? item.featureKeys : [],
    includedInPrice: [...includedInPrice]
      .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)),
    filterMeta: item.filterMeta || null,
    filterFlags: item.filterFlags || null,
    prices: item.prices || null,
    ctaUrl: item.path ? normalizePublicInternalPath(item.path, locale) : normalizePublicInternalPath('/vehicles', locale),
    specs: {
      seats: item.seats || item.specs?.seats || null,
      doors: item.doors || item.specs?.doors || null,
      transmission: item.transmission || item.specs?.transmission || null,
      fuel: item.fuelType || item.powertrain || item.specs?.fuel || item.specs?.engine || null,
      fuelConsumptionPer100Km: item.fuelConsumptionPer100Km ?? item.filterMeta?.specs?.fuelConsumptionPer100Km ?? item.specs?.fuelConsumptionPer100Km ?? null,
      driveType: item.driveType || item.specs?.driveType || null,
      power: performance.power || null,
      acceleration: performance.acceleration || null,
      topSpeed: performance.topSpeed || null,
    },
  }
}

const homeFleetCategoryPriority = {
  Economy: 10,
  Sedan: 20,
  SUV: 30,
  Vans: 40,
  Premium: 50,
  Standard: 60,
  Manual: 70,
  Automatic: 80,
}

function orderHomeFleetCategories(categories = []) {
  return [...categories].sort((left, right) => {
    const leftPriority = homeFleetCategoryPriority[left] ?? 100
    const rightPriority = homeFleetCategoryPriority[right] ?? 100

    if (leftPriority !== rightPriority) {
      return leftPriority - rightPriority
    }

    return left.localeCompare(right)
  })
}

function resolveHomeFleetFilters(fleetSection = {}, locale = 'en', fallbackCategories = []) {
  const allLabel = resolvePublicUiValue(locale, 'home.fleet.allCategoryLabel')
  const rawFilters = Array.isArray(fleetSection?.filters) ? fleetSection.filters : []
  const normalizedFilters = rawFilters
    .map((item) => {
      if (typeof item === 'string') {
        const value = String(item || '').trim()

        return value ? { id: value, label: value } : null
      }

      if (!item || typeof item !== 'object') {
        return null
      }

      const id = String(item.id || item.label || '').trim()
      const label = String(item.label || item.id || '').trim()

      if (!id || !label || id === 'All') {
        return null
      }

      return { id, label }
    })
    .filter(Boolean)

  if (normalizedFilters.length) {
    return [{ id: 'All', label: allLabel }, ...normalizedFilters]
  }

  return [
    { id: 'All', label: allLabel },
    ...orderHomeFleetCategories(fallbackCategories).map((category) => ({ id: category, label: category })),
  ]
}

function orderHomeFleetVehicles(vehicles = []) {
  return [...vehicles].sort((left, right) => {
    const leftOrder = Number.isFinite(left.homeSortOrder) ? left.homeSortOrder : Number.MAX_SAFE_INTEGER
    const rightOrder = Number.isFinite(right.homeSortOrder) ? right.homeSortOrder : Number.MAX_SAFE_INTEGER

    if (leftOrder !== rightOrder) {
      return leftOrder - rightOrder
    }

    const leftCategory = homeFleetCategoryPriority[left.category] ?? 100
    const rightCategory = homeFleetCategoryPriority[right.category] ?? 100

    if (leftCategory !== rightCategory) {
      return leftCategory - rightCategory
    }

    return String(left.name || '').localeCompare(String(right.name || ''))
  })
}

function pickLocalizedArray(overrideValue, fallbackValue = []) {
  return Array.isArray(overrideValue) && overrideValue.length
    ? overrideValue
    : (Array.isArray(fallbackValue) ? fallbackValue : [])
}

function emptyHomeSnapshot() {
  return {
    homePageContent: null,
    homeHeroContent: {},
    homeFollowUsSection: {
      socialProfiles: [],
      storeButtons: [],
    },
    homeHeroTabs: [],
    homeHeroRequestForm: {
      carTypes: [],
      budgetOptions: [],
    },
    homeHeroSearchForm: {},
    homeHeroRequestStatus: {},
    homeAboutSection: {
      paragraphs: [],
      highlights: [],
    },
    homeDiscoverSection: {
      galleryItems: [],
    },
    homeFeaturesSection: {
      highlights: [],
    },
    homeOffersSection: {},
    homeOfferCards: [],
    homeFleetSection: {},
    homeFleetCategories: [],
    homeFleetVehicles: [],
    homeExtrasSection: {},
    homeIncludedPerks: [],
    homeRentalExtras: [],
    homeArticlesSection: {},
    homeFeaturedArticle: null,
    homeSecondaryArticles: [],
    homeSidebarArticles: [],
  }
}

function createHomeContentSnapshot(locale = 'en', payload = {}, extrasCatalog = [], vehicleListing = null) {
  const currentHomePage = payload?.homePage || null

  if (!currentHomePage) {
    return emptyHomeSnapshot()
  }

  const currentHomeBlocks = Array.isArray(payload?.homeBlocks) ? payload.homeBlocks : []
  const currentFeaturedOffers = Array.isArray(payload?.featuredOffers) ? payload.featuredOffers : []
  const currentFeaturedArticlesSource = Array.isArray(payload?.featuredArticles) ? payload.featuredArticles : []
  const currentFeaturedVehicles = Array.isArray(payload?.featuredVehicles) ? payload.featuredVehicles : []
  const fullFleetVehicles = Array.isArray(vehicleListing?.fleetVehicles) ? vehicleListing.fleetVehicles : []
  const currentFleetVehicles = fullFleetVehicles.length ? fullFleetVehicles : currentFeaturedVehicles
  const currentAboutBlock = pickHomeBlock(currentHomeBlocks, 'home_about_service')
  const currentDiscoverBlock = pickHomeBlock(currentHomeBlocks, 'home_discover_georgia')
  const currentFeaturesBlock = pickHomeBlock(currentHomeBlocks, 'home_why_choose_us')
  const currentHeroContent = currentHomePage?.structuredContent?.hero || {}
  const currentRequestFormContent = currentHeroContent.requestForm || {}
  const currentSearchFormContent = currentHeroContent.searchForm || {}
  const currentRequestStatusContent = currentHeroContent.requestStatus || {}
  const currentHeroUi = resolvePublicUiValue(locale, 'home.hero', {}) || {}
  const currentHeroRequestFormUi = currentHeroUi.requestForm || {}
  const currentHeroSearchFormUi = currentHeroUi.searchForm || {}
  const currentHeroRequestStatusUi = currentHeroUi.requestStatus || {}
  const currentOffersSection = currentHomePage?.structuredContent?.sections?.offers || {}
  const currentFleetSection = currentHomePage?.structuredContent?.sections?.fleet || {}
  const currentExtrasSection = currentHomePage?.structuredContent?.sections?.extras || {}
  const currentArticlesSection = currentHomePage?.structuredContent?.sections?.articles || {}
  const includedExtras = (Array.isArray(extrasCatalog) ? extrasCatalog : [])
    .filter((item) => item.group === 'included')
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
  const rentalExtras = (Array.isArray(extrasCatalog) ? extrasCatalog : [])
    .filter((item) => item.group !== 'included')
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
  const insuranceExtras = [...includedExtras, ...rentalExtras]
    .filter((item) => String(item?.kind || item?.kindLabel || '').trim().toLowerCase() === 'insurance')
    .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
  const currentFeaturedArticles = resolveHomeFeaturedArticles(
    currentFeaturedArticlesSource,
    locale,
    6,
    currentArticlesSection.featuredKeys,
  )
  const normalizedArticlesForLocale = currentFeaturedArticles.map((article) => normalizeHomeArticleCard(article, locale))
  const normalizedHomeFleetVehicles = currentFleetVehicles.map((item) => normalizeHomeFleetVehicle(item, locale))
  const orderedHomeFleetVehicles = orderHomeFleetVehicles(normalizedHomeFleetVehicles)
  const derivedCategories = [...new Set(orderedHomeFleetVehicles.flatMap((item) => item.homeTypes || []).filter(Boolean))]

  return {
    homePageContent: currentHomePage,
    homeHeroContent: {
      formTitle: currentHeroUi.formTitle || currentHeroContent.formTitle,
      rightEyebrow: currentHomePage?.structuredContent?.hero?.editorial?.eyebrow,
      rightTitle: currentHomePage?.subtitle,
      rightDescription: currentHomePage?.excerpt,
      rightImage: HOME_HERO_RIGHT_IMAGE,
    },
    homeFollowUsSection: {
      title: resolvePublicUiValue(locale, 'home.followUsTitle'),
      socialProfiles: [
        { id: 'facebook', label: resolvePublicUiValue(locale, 'home.socialProfiles.facebook'), iconKey: 'facebook', href: null },
        { id: 'messenger', label: resolvePublicUiValue(locale, 'home.socialProfiles.messenger'), iconKey: 'messenger', href: null },
        { id: 'instagram', label: resolvePublicUiValue(locale, 'home.socialProfiles.instagram'), iconKey: 'instagram', href: null },
        { id: 'linkedin', label: resolvePublicUiValue(locale, 'home.socialProfiles.linkedin'), iconKey: 'linkedin', href: null },
        { id: 'about-me', label: resolvePublicUiValue(locale, 'home.socialProfiles.aboutMe'), iconKey: 'monogram', href: null, monogram: 'ME' },
      ],
      storeButtons: [
        { id: 'google-play', label: resolvePublicUiValue(locale, 'home.storeButtons.googlePlay.label'), eyebrow: resolvePublicUiValue(locale, 'home.storeButtons.googlePlay.eyebrow'), iconKey: 'play', href: null },
        { id: 'app-store', label: resolvePublicUiValue(locale, 'home.storeButtons.appStore.label'), eyebrow: resolvePublicUiValue(locale, 'home.storeButtons.appStore.eyebrow'), iconKey: 'apple', href: null },
      ],
    },
    homeHeroTabs: [...pickLocalizedArray(currentHeroUi.tabs, currentHeroContent.tabs || [])]
      .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)),
    homeHeroRequestForm: {
      pickupLabel: currentHeroRequestFormUi.pickupLabel || currentRequestFormContent.pickupLabel,
      pickupDateLabel: currentHeroRequestFormUi.pickupDateLabel || currentRequestFormContent.pickupDateLabel,
      returnDateLabel: currentHeroRequestFormUi.returnDateLabel || currentRequestFormContent.returnDateLabel,
      vehicleClassLabel: currentHeroRequestFormUi.vehicleClassLabel || currentRequestFormContent.vehicleClassLabel,
      phoneLabel: currentHeroRequestFormUi.phoneLabel || currentRequestFormContent.phoneLabel,
      phonePlaceholder: currentHeroRequestFormUi.phonePlaceholder || currentRequestFormContent.phonePlaceholder,
      phoneValidationMessage: currentHeroRequestFormUi.phoneValidationMessage || currentRequestFormContent.phoneValidationMessage,
      budgetLabel: currentHeroRequestFormUi.budgetLabel || currentRequestFormContent.budgetLabel,
      calendarDoneLabel: currentHeroRequestFormUi.calendarDoneLabel || currentRequestFormContent.calendarDoneLabel,
      submitLabel: currentHeroRequestFormUi.submitLabel || currentRequestFormContent.submitLabel,
      submittingLabel: currentHeroRequestFormUi.submittingLabel || currentRequestFormContent.submittingLabel,
      carTypes: [...pickLocalizedArray(currentHeroRequestFormUi.carTypes, currentRequestFormContent.carTypes || [])]
        .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
        .map((item) => ({
          id: item.id,
          label: item.label,
          icon: heroCarTypeIcons[item.id] || 'sedan',
        })),
      budgetOptions: [...pickLocalizedArray(currentHeroRequestFormUi.budgetOptions, currentRequestFormContent.budgetOptions || [])]
        .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
        .map((item) => ({
          id: item.id,
          label: item.label,
          amount: item.amount,
          tier: budgetTierByOptionId[item.id] || 'budget_any',
        })),
    },
    homeHeroSearchForm: {
      tripDetailsLabel: currentHeroSearchFormUi.tripDetailsLabel || currentSearchFormContent.tripDetailsLabel,
      returnToSamePlaceLabel: currentHeroSearchFormUi.returnToSamePlaceLabel || currentSearchFormContent.returnToSamePlaceLabel,
      pickupLabel: currentHeroSearchFormUi.pickupLabel || currentSearchFormContent.pickupLabel,
      returnLabel: currentHeroSearchFormUi.returnLabel || currentSearchFormContent.returnLabel,
      pickupDateLabel: currentHeroSearchFormUi.pickupDateLabel || currentSearchFormContent.pickupDateLabel,
      returnDateLabel: currentHeroSearchFormUi.returnDateLabel || currentSearchFormContent.returnDateLabel,
      timeLabel: currentHeroSearchFormUi.timeLabel || currentSearchFormContent.timeLabel,
      selectDateLabel: currentHeroSearchFormUi.selectDateLabel || currentSearchFormContent.selectDateLabel,
      driverAgeLabel: currentHeroSearchFormUi.driverAgeLabel || currentSearchFormContent.driverAgeLabel,
      driverAgeValue: currentHeroSearchFormUi.driverAgeValue || currentSearchFormContent.driverAgeValue,
      driverAgeFallbackLabel: currentHeroSearchFormUi.driverAgeFallbackLabel || currentSearchFormContent.driverAgeFallbackLabel,
      promoCodeLabel: currentHeroSearchFormUi.promoCodeLabel || currentSearchFormContent.promoCodeLabel,
      promoCodePlaceholder: currentHeroSearchFormUi.promoCodePlaceholder || currentSearchFormContent.promoCodePlaceholder,
      promoApplyLabel: currentHeroSearchFormUi.promoApplyLabel || currentSearchFormContent.promoApplyLabel,
      promoAppliedLabel: currentHeroSearchFormUi.promoAppliedLabel || currentSearchFormContent.promoAppliedLabel,
      calendarDoneLabel: currentHeroSearchFormUi.calendarDoneLabel || currentSearchFormContent.calendarDoneLabel,
      searchSubmitLabel: currentHeroSearchFormUi.searchSubmitLabel || currentSearchFormContent.searchSubmitLabel,
      liveSummaryLabel: currentHeroSearchFormUi.liveSummaryLabel || currentSearchFormContent.liveSummaryLabel,
      liveSummaryUpdatingLabel: currentHeroSearchFormUi.liveSummaryUpdatingLabel || currentSearchFormContent.liveSummaryUpdatingLabel,
      pickupSummaryLabel: currentHeroSearchFormUi.pickupSummaryLabel || currentSearchFormContent.pickupSummaryLabel,
      dropoffSummaryLabel: currentHeroSearchFormUi.dropoffSummaryLabel || currentSearchFormContent.dropoffSummaryLabel,
      fleetVehiclesLabel: currentHeroSearchFormUi.fleetVehiclesLabel || currentSearchFormContent.fleetVehiclesLabel,
      fleetVehiclesUnitLabel: currentHeroSearchFormUi.fleetVehiclesUnitLabel || currentSearchFormContent.fleetVehiclesUnitLabel,
      fleetSyncLabel: currentHeroSearchFormUi.fleetSyncLabel || currentSearchFormContent.fleetSyncLabel,
      startingFromLabel: currentHeroSearchFormUi.startingFromLabel || currentSearchFormContent.startingFromLabel,
      onRequestLabel: currentHeroSearchFormUi.onRequestLabel || currentSearchFormContent.onRequestLabel,
      perDayLabel: currentHeroSearchFormUi.perDayLabel || currentSearchFormContent.perDayLabel,
      detailsLabel: currentHeroSearchFormUi.detailsLabel || currentSearchFormContent.detailsLabel,
      airportGroupLabel: currentHeroSearchFormUi.airportGroupLabel || currentSearchFormContent.airportGroupLabel,
      cityGroupLabel: currentHeroSearchFormUi.cityGroupLabel || currentSearchFormContent.cityGroupLabel,
      operatingHoursLabel: currentHeroSearchFormUi.operatingHoursLabel || currentSearchFormContent.operatingHoursLabel,
      operatingHoursValue: currentHeroSearchFormUi.operatingHoursValue || currentSearchFormContent.operatingHoursValue,
      morningLabel: currentHeroSearchFormUi.morningLabel || currentSearchFormContent.morningLabel,
      afternoonLabel: currentHeroSearchFormUi.afternoonLabel || currentSearchFormContent.afternoonLabel,
      eveningLabel: currentHeroSearchFormUi.eveningLabel || currentSearchFormContent.eveningLabel,
    },
    homeHeroRequestStatus: {
      sentTitle: currentHeroRequestStatusUi.sentTitle || currentRequestStatusContent.sentTitle,
      sentDescriptionTemplate: currentHeroRequestStatusUi.sentDescriptionTemplate || currentRequestStatusContent.sentDescriptionTemplate,
      activeTitle: currentHeroRequestStatusUi.activeTitle || currentRequestStatusContent.activeTitle,
      liveUpdatesLabel: currentHeroRequestStatusUi.liveUpdatesLabel || currentRequestStatusContent.liveUpdatesLabel,
      detailsTitle: currentHeroRequestStatusUi.detailsTitle || currentRequestStatusContent.detailsTitle,
      locationLabel: currentHeroRequestStatusUi.locationLabel || currentRequestStatusContent.locationLabel,
      vehicleTypeLabel: currentHeroRequestStatusUi.vehicleTypeLabel || currentRequestStatusContent.vehicleTypeLabel,
      datesLabel: currentHeroRequestStatusUi.datesLabel || currentRequestStatusContent.datesLabel,
      budgetLabel: currentHeroRequestStatusUi.budgetLabel || currentRequestStatusContent.budgetLabel,
      openTrackingLabel: currentHeroRequestStatusUi.openTrackingLabel || currentRequestStatusContent.openTrackingLabel,
      closeLabel: currentHeroRequestStatusUi.closeLabel || currentRequestStatusContent.closeLabel,
      statTypeLabel: currentHeroRequestStatusUi.statTypeLabel || currentRequestStatusContent.statTypeLabel,
      statLocationLabel: currentHeroRequestStatusUi.statLocationLabel || currentRequestStatusContent.statLocationLabel,
      statStatusLabel: currentHeroRequestStatusUi.statStatusLabel || currentRequestStatusContent.statStatusLabel,
      trackStatusLabel: currentHeroRequestStatusUi.trackStatusLabel || currentRequestStatusContent.trackStatusLabel,
      trackPendingLabel: currentHeroRequestStatusUi.trackPendingLabel || currentRequestStatusContent.trackPendingLabel,
      progressSteps: [...pickLocalizedArray(currentHeroRequestStatusUi.progressSteps, currentRequestStatusContent.progressSteps || [])]
        .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
        .map((item) => item.label)
        .filter(Boolean),
      waitTitle: currentHeroRequestStatusUi.waitTitle || currentRequestStatusContent.waitTitle,
      waitDescription: currentHeroRequestStatusUi.waitDescription || currentRequestStatusContent.waitDescription,
      previewTitle: currentHeroRequestStatusUi.previewTitle || currentRequestStatusContent.previewTitle,
      previewDescription: currentHeroRequestStatusUi.previewDescription || currentRequestStatusContent.previewDescription,
      bannerTitle: currentHeroRequestStatusUi.bannerTitle || currentRequestStatusContent.bannerTitle,
      bannerDescription: currentHeroRequestStatusUi.bannerDescription || currentRequestStatusContent.bannerDescription,
      fleetTitle: currentHeroRequestStatusUi.fleetTitle || currentRequestStatusContent.fleetTitle,
      publicFleetLabel: currentHeroRequestStatusUi.publicFleetLabel || currentRequestStatusContent.publicFleetLabel,
      fleetCtaLabel: currentHeroRequestStatusUi.fleetCtaLabel || currentRequestStatusContent.fleetCtaLabel,
    },
    homeAboutSection: {
      eyebrow: currentAboutBlock?.title,
      title: currentAboutBlock?.subtitle,
      description: currentAboutBlock?.excerpt,
      paragraphs: currentAboutBlock?.structuredContent?.paragraphs || [],
      highlights: currentAboutBlock?.structuredContent?.highlights || [],
      image: currentAboutBlock?.featuredImage || currentAboutBlock?.cardImage || currentAboutBlock?.heroImage,
      badge: currentAboutBlock?.structuredContent?.brandBadge,
      mediaAction: currentAboutBlock?.structuredContent?.mediaAction
        ? {
            type: currentAboutBlock.structuredContent.mediaAction.type,
            label: currentAboutBlock.structuredContent.mediaAction.label,
            videoUrl: currentAboutBlock.structuredContent.mediaAction.videoUrl,
            posterImage: currentAboutBlock.structuredContent.mediaAction.posterImage,
          }
        : null,
      ctaLabel: currentAboutBlock?.cta?.label,
      ctaUrl: normalizePublicInternalPath(currentAboutBlock?.cta?.url, locale),
    },
    homeDiscoverSection: {
      title: currentDiscoverBlock?.title,
      galleryItems: [...(currentDiscoverBlock?.structuredContent?.galleryItems || [])]
        .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)),
    },
    homeFeaturesSection: {
      eyebrow: currentFeaturesBlock?.structuredContent?.eyebrow,
      title: currentFeaturesBlock?.subtitle,
      description: currentFeaturesBlock?.excerpt,
      highlights: [...(currentFeaturesBlock?.structuredContent?.highlights || [])]
        .sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0)),
    },
    homeOffersSection: {
      eyebrow: currentOffersSection.eyebrow,
      title: currentOffersSection.title,
      accent: currentOffersSection.accent,
      viewAllLabel: currentOffersSection.viewAllLabel,
      offerPriceLabel: currentOffersSection.offerPriceLabel,
      perDayLabel: currentOffersSection.perDayLabel,
      emptyTitle: currentOffersSection.emptyTitle,
      emptyDescription: currentOffersSection.emptyDescription,
    },
    homeOfferCards: currentFeaturedOffers.slice(0, 3).map((item) => normalizeHomeOfferCard(item, currentOffersSection, locale)),
    homeFleetSection: {
      eyebrow: currentFleetSection.eyebrow,
      title: currentFleetSection.title,
      accent: currentFleetSection.accent,
      description: currentFleetSection.description,
      premiumBadgeLabel: currentFleetSection.premiumBadgeLabel || resolvePublicUiValue(locale, 'home.fleet.premiumBadgeLabel'),
      detailPanelTitle: currentFleetSection.detailPanelTitle || resolvePublicUiValue(locale, 'home.fleet.detailPanelTitle'),
      transmissionLabel: currentFleetSection.transmissionLabel || resolvePublicUiValue(locale, 'home.fleet.transmissionLabel'),
      fuelLabel: currentFleetSection.fuelLabel || resolvePublicUiValue(locale, 'home.fleet.fuelLabel'),
      classLabel: currentFleetSection.classLabel || resolvePublicUiValue(locale, 'home.fleet.classLabel'),
      dailyRateLabel: currentFleetSection.dailyRateLabel,
      perDayLabel: currentFleetSection.perDayLabel,
      ctaLabel: currentFleetSection.ctaLabel,
      seatsLabel: currentFleetSection.seatsLabel || resolvePublicUiValue(locale, 'home.fleet.seatsLabel'),
      doorsLabel: currentFleetSection.doorsLabel || resolvePublicUiValue(locale, 'home.fleet.doorsLabel'),
      showcaseLabel: currentFleetSection.showcaseLabel,
      gridLabel: currentFleetSection.gridLabel,
      performanceTitle: resolvePublicUiValue(locale, 'home.fleet.performanceTitle'),
      powerLabel: resolvePublicUiValue(locale, 'home.fleet.powerLabel'),
      accelerationLabel: resolvePublicUiValue(locale, 'home.fleet.accelerationLabel'),
      topSpeedLabel: resolvePublicUiValue(locale, 'home.fleet.topSpeedLabel'),
      emptyTitle: currentFleetSection.emptyTitle,
      emptyDescription: currentFleetSection.emptyDescription,
    },
    homeFleetCategories: resolveHomeFleetFilters(currentFleetSection, locale, derivedCategories),
    homeFleetVehicles: orderedHomeFleetVehicles,
    homeExtrasSection: {
      includedEyebrow: currentExtrasSection.includedEyebrow,
      includedTitle: currentExtrasSection.includedTitle,
      includedAccent: currentExtrasSection.includedAccent,
      extrasTitle: currentExtrasSection.extrasTitle,
      extrasDescription: currentExtrasSection.extrasDescription,
    },
    homeIncludedPerks: includedExtras.map((item) => ({
      id: item.id,
      code: item.code,
      title: item.name,
      description: currentHomePage?.structuredContent?.extras?.includedDescriptions?.[item.code] || item.description,
      iconKey: item.iconKey,
      kind: item.kind,
      kindLabel: item.kindLabel,
      group: item.group,
      pricingType: item.pricingType,
    })),
    homeRentalExtras: rentalExtras.map((item) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      description: currentHomePage?.structuredContent?.extras?.extraDescriptions?.[item.code] || item.description,
      price: `$${Number(item.price || 0)}`,
      period: item.pricingType === 'per_day' ? resolvePublicUiValue(locale, 'home.fleet.pricingDailyLabel') : resolvePublicUiValue(locale, 'home.fleet.pricingTripLabel'),
      iconKey: item.iconKey,
      actionLabel: item.homeAction?.label || null,
      actionUrl: normalizePublicInternalPath(item.homeAction?.href, locale),
      kind: item.kind,
      kindLabel: item.kindLabel,
      group: item.group,
      pricingType: item.pricingType,
      sortOrder: item.sortOrder || 0,
    })),
    homeInsuranceOptions: insuranceExtras.map((item) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      description: currentHomePage?.structuredContent?.extras?.extraDescriptions?.[item.code]
        || currentHomePage?.structuredContent?.extras?.includedDescriptions?.[item.code]
        || item.description,
      price: Number(item.price || 0),
      pricingType: item.pricingType,
      iconKey: item.iconKey,
      group: item.group,
      kind: item.kind,
      kindLabel: item.kindLabel,
      sortOrder: item.sortOrder || 0,
    })),
    homeArticlesSection: {
      eyebrow: currentArticlesSection.eyebrow,
      title: currentArticlesSection.title,
      accent: currentArticlesSection.accent,
      description: currentArticlesSection.description,
      quickReadsTitle: currentArticlesSection.quickReadsTitle,
      viewAllLabel: currentArticlesSection.viewAllLabel,
    },
    homeFeaturedArticle: normalizedArticlesForLocale[0] || null,
    homeSecondaryArticles: normalizedArticlesForLocale.slice(1, 3),
    homeSidebarArticles: normalizedArticlesForLocale.slice(3),
  }
}

export function useHomeContent() {
  const { locale } = usePublicLocale()
  const { data, pending, status } = useAsyncData(
    () => `public-home:${normalizePublicLocale(locale.value)}`,
    async () => {
      const [payload, extrasCatalog, vehicleListing] = await Promise.all([
        loadHomeLocaleExport(locale.value),
        loadExtrasLocaleExport(locale.value),
        loadVehicleListingSnapshot(locale.value),
      ])

      return createHomeContentSnapshot(locale.value, payload, extrasCatalog, vehicleListing)
    },
    {
      watch: [locale],
      default: () => emptyHomeSnapshot(),
    },
  )

  return {
    homePageContent: computed(() => data.value.homePageContent),
    homeHeroContent: computed(() => data.value.homeHeroContent),
    homeFollowUsSection: computed(() => data.value.homeFollowUsSection),
    homeHeroTabs: computed(() => data.value.homeHeroTabs),
    homeHeroRequestForm: computed(() => data.value.homeHeroRequestForm),
    homeHeroSearchForm: computed(() => data.value.homeHeroSearchForm),
    homeHeroRequestStatus: computed(() => data.value.homeHeroRequestStatus),
    homeContentPending: pending,
    homeContentStatus: status,
    homeAboutSection: computed(() => data.value.homeAboutSection),
    homeDiscoverSection: computed(() => data.value.homeDiscoverSection),
    homeFeaturesSection: computed(() => data.value.homeFeaturesSection),
    homeOffersSection: computed(() => data.value.homeOffersSection),
    homeOfferCards: computed(() => data.value.homeOfferCards),
    homeFleetSection: computed(() => data.value.homeFleetSection),
    homeFleetCategories: computed(() => data.value.homeFleetCategories),
    homeFleetVehicles: computed(() => data.value.homeFleetVehicles),
    homeExtrasSection: computed(() => data.value.homeExtrasSection),
    homeIncludedPerks: computed(() => data.value.homeIncludedPerks),
    homeRentalExtras: computed(() => data.value.homeRentalExtras),
    homeInsuranceOptions: computed(() => data.value.homeInsuranceOptions),
    homeArticlesSection: computed(() => data.value.homeArticlesSection),
    homeFeaturedArticle: computed(() => data.value.homeFeaturedArticle),
    homeSecondaryArticles: computed(() => data.value.homeSecondaryArticles),
    homeSidebarArticles: computed(() => data.value.homeSidebarArticles),
  }
}
