import { computed } from 'vue'
import { luxuryCars as rawLuxuryCars, luxuryFeatures } from '~/generated/site/luxury/index'
import { useResolvedPage } from '~/content/pages'
import { buildResolvedPageSeo } from '~/content/utils'

function extractLegacyLuxuryId(car) {
  const candidates = [
    car?.legacyId,
    car?.publicSlug,
    car?.slug,
    car?.id,
    car?.name,
  ]

  for (const candidate of candidates) {
    const match = String(candidate || '').match(/-(\d+)$/)

    if (match?.[1]) {
      return match[1]
    }
  }

  return ''
}

function formatLuxuryAmount(value, currency = 'USD') {
  const amount = Number(value)

  if (!Number.isFinite(amount) || amount <= 0) {
    return ''
  }

  try {
    return new Intl.NumberFormat(undefined, {
      style: 'currency',
      currency,
      maximumFractionDigits: 0,
    }).format(amount)
  } catch {
    return `${currency} ${Math.round(amount)}`
  }
}

function formatLuxuryPrice(car, ui) {
  if (car?.priceMode === 'from' && Number(car?.priceFrom) > 0) {
    const template = String(ui?.priceFromTemplate || 'From :price:unit')
    const amount = formatLuxuryAmount(car.priceFrom, car.currency || 'USD')
    const unit = String(ui?.perDayLabel || '')

    return template.replace(':price', amount).replace(':unit', unit)
  }

  return String(ui?.quoteOnRequestLabel || '')
}

export function buildLuxuryPageSeo(page, origin = '') {
  return buildResolvedPageSeo(page, origin, {
    ogImage: page?.heroImage || page?.featuredImage || page?.structuredContent?.heroImage || '',
  })
}

export function useLuxuryContent() {
  const luxuryPage = useResolvedPage('luxury')
  const luxuryContent = computed(() => luxuryPage.value?.structuredContent || {})
  const luxuryUiContent = computed(() => luxuryContent.value.ui || {})
  const luxuryFormContent = computed(() => luxuryContent.value.form || {})

  const luxuryUi = computed(() => ({
    scrollLabel: luxuryUiContent.value.scrollLabel,
    fleetIntroTitle: luxuryUiContent.value.fleetIntroTitle,
    fleetIntroLive: luxuryUiContent.value.fleetIntroLive,
    fleetIntroEmpty: luxuryUiContent.value.fleetIntroEmpty,
    fleetEmptyTitle: luxuryUiContent.value.fleetEmptyTitle,
    fleetEmptyDescription: luxuryUiContent.value.fleetEmptyDescription,
    conciergeTitle: luxuryUiContent.value.conciergeTitle,
    conciergeDescription: luxuryUiContent.value.conciergeDescription,
    modalEyebrow: luxuryUiContent.value.modalEyebrow,
    modalTitle: luxuryUiContent.value.modalTitle,
    modalDescription: luxuryUiContent.value.modalDescription,
    collectionLabel: luxuryUiContent.value.luxuryCollectionLabel,
  }))

  const luxuryForm = computed(() => ({
    labels: luxuryFormContent.value.labels || {},
    placeholders: luxuryFormContent.value.placeholders || {},
    submitLabel: luxuryFormContent.value.submitLabel,
    submittingLabel: luxuryFormContent.value.submittingLabel,
    doneLabel: luxuryFormContent.value.doneLabel,
    phoneValidationMessage: luxuryFormContent.value.phoneValidationMessage,
  }))

  const luxuryCars = computed(() => rawLuxuryCars.map((car) => ({
    ...car,
    legacyLuxuryId: extractLegacyLuxuryId(car),
    category: luxuryUiContent.value.premiumVehicleLabel || 'Prestige car',
    specs: [
      car.isPopular
        ? luxuryUiContent.value.popularChoiceLabel
        : luxuryUiContent.value.collectionLabel,
      luxuryUiContent.value.reviewLabel,
    ].filter(Boolean),
    price: formatLuxuryPrice(car, luxuryUiContent.value),
    actionLabel: luxuryUiContent.value.requestLabel,
  })))

  return {
    luxuryPage,
    luxuryUi,
    luxuryForm,
    luxuryCars,
    luxuryFeatures,
    luxuryFleet: luxuryCars,
  }
}
