import tailwindcss from '@tailwindcss/vite'
import { routePages } from './app/generated/site/route-pages'
import { siteRoutes } from './app/generated/site/site-routes'
import { luxuryCars as legacyLuxuryCars } from './app/generated/site/luxury/index'
import {
  DEFAULT_PUBLIC_LOCALE,
  localizedExactPublicPath,
  localizedSectionPublicPath,
  NON_DEFAULT_PUBLIC_LOCALES,
  stripPublicLocalePrefix,
  supportedPublicLocalesForPath,
  withPublicLocalePrefix,
} from './app/utils/public-locales'

function firstBarePathSegment(path: string) {
  const barePath = stripPublicLocalePrefix(path)
  const match = barePath.match(/^\/[^/]+/)
  return match?.[0] || null
}

function toRoutePath(value: unknown) {
  const rawValue = String(value || '').trim()

  if (!rawValue) {
    return ''
  }

  if (rawValue.startsWith('http://') || rawValue.startsWith('https://')) {
    try {
      return new URL(rawValue).pathname || ''
    } catch {
      return ''
    }
  }

  return rawValue
}

function hasDynamicDetailShape(path: string) {
  const barePath = stripPublicLocalePrefix(path)
  return barePath.split('/').filter(Boolean).length > 1
}

function extractLegacyLuxuryId(value: unknown) {
  const match = String(value || '').match(/-(\d+)$/)
  return match?.[1] || ''
}

function buildDynamicPrefixPathMap() {
  const registry = new Map<string, Record<string, string>>()
  const routes = Array.isArray(siteRoutes?.routes) ? siteRoutes.routes : []

  for (const route of routes) {
    const locale = String(route?.locale || '').trim().toLowerCase()
    const localizedPath = toRoutePath(route?.path)

    if (!locale || !localizedPath || !hasDynamicDetailShape(localizedPath)) {
      continue
    }

    const canonicalSourcePath = toRoutePath(route?.x_default || route?.canonical || localizedPath)
    const canonicalPrefix = firstBarePathSegment(canonicalSourcePath)
    const localizedPrefix = firstBarePathSegment(localizedPath)

    if (!canonicalPrefix || !localizedPrefix || canonicalPrefix === '/' || localizedPrefix === '/') {
      continue
    }

    if (!registry.has(canonicalPrefix)) {
      registry.set(canonicalPrefix, {})
    }

    registry.get(canonicalPrefix)![locale] = localizedPrefix
  }

  return Object.fromEntries(registry.entries())
}

const DYNAMIC_PREFIX_PATHS = buildDynamicPrefixPathMap()
function collectPageRoutePaths() {
  const registry = routePages && typeof routePages === 'object' ? routePages : {}
  const paths = new Set<string>()

  for (const entry of Object.values(registry)) {
    const page = entry && typeof entry === 'object' ? (entry as any).page : null

    if (!page) {
      continue
    }

    const primaryPath = toRoutePath(page.path)

    if (primaryPath.startsWith('/')) {
      paths.add(primaryPath)
    }

    for (const localizedEntry of Array.isArray(page.localized) ? page.localized : []) {
      const localizedPath = toRoutePath(localizedEntry?.path)

      if (localizedPath.startsWith('/')) {
        paths.add(localizedPath)
      }
    }
  }

  return Array.from(paths)
}

const LEGACY_LUXURY_LOCALE_PREFIXES = ['', '/fr', '/es', '/ru', '/de', '/ka']
const LEGACY_LUXURY_IDS = Array.from(new Set(
  (Array.isArray(legacyLuxuryCars) ? legacyLuxuryCars : [])
    .map((car: any) => extractLegacyLuxuryId(car?.publicSlug || car?.slug || car?.id))
    .filter(Boolean),
)).sort((left, right) => Number(left) - Number(right))
const LEGACY_LUXURY_DETAIL_PATHS = [
  '/luxury/:legacyLuxuryId(\\d+)',
  '/fr/luxury/:legacyLuxuryId(\\d+)',
  '/es/luxury/:legacyLuxuryId(\\d+)',
  '/ru/luxury/:legacyLuxuryId(\\d+)',
  '/de/luxury/:legacyLuxuryId(\\d+)',
  '/ka/luxury/:legacyLuxuryId(\\d+)',
]
const LEGACY_LUXURY_PRERENDER_PATHS = LEGACY_LUXURY_LOCALE_PREFIXES.flatMap((prefix) =>
  LEGACY_LUXURY_IDS.map((id) => `${prefix}/luxury/${id}`),
)
const PRERENDER_ROUTE_PATHS = [
  ...collectPageRoutePaths(),
  ...LEGACY_LUXURY_PRERENDER_PATHS,
]

function buildLegacyLuxuryDetailPages(sourcePages: any[]) {
  const luxuryPage = sourcePages.find((page: any) => page?.path === '/luxury')

  if (!luxuryPage) {
    return []
  }

  return LEGACY_LUXURY_DETAIL_PATHS.map((path, index) => ({
    ...luxuryPage,
    name: luxuryPage.name ? `${luxuryPage.name}___legacy_luxury_${index}` : `legacy_luxury_${index}`,
    path,
  }))
}

function localizeDynamicPagePath(path: string, locale: string) {
  const barePath = stripPublicLocalePrefix(path)
  const canonicalPrefix = firstBarePathSegment(barePath)

  if (!canonicalPrefix) {
    return null
  }

  const localizedPrefix = DYNAMIC_PREFIX_PATHS[canonicalPrefix]?.[locale]

  if (!localizedPrefix) {
    return null
  }

  return withPublicLocalePrefix(`${localizedPrefix}${barePath.slice(canonicalPrefix.length)}`, locale)
}

function localizePagePath(path: string, locale: string) {
  if (typeof path !== 'string' || !path.startsWith('/')) {
    return path
  }

  const barePath = stripPublicLocalePrefix(path)

  if (barePath === '/') {
    return withPublicLocalePrefix('/', locale)
  }

  const localizedDynamicPath = localizeDynamicPagePath(barePath, locale)

  if (localizedDynamicPath) {
    return localizedDynamicPath
  }

  const localizedSectionPath = localizedSectionPublicPath(barePath, locale)

  if (localizedSectionPath) {
    return localizedSectionPath
  }

  const localizedExactPath = localizedExactPublicPath(barePath, locale)

  if (localizedExactPath) {
    return localizedExactPath
  }

  return withPublicLocalePrefix(barePath, locale)
}

function cloneLocalizedPage(page: any, locale: string) {
  return {
    ...page,
    name: page.name ? `${page.name}___${locale}` : page.name,
    path: localizePagePath(page.path, locale),
    children: Array.isArray(page.children)
      ? page.children.map((child: any) => cloneLocalizedPage(child, locale))
      : page.children,
  }
}

function supportedLocalesForPage(page: any) {
  if (typeof page?.path !== 'string' || !page.path.startsWith('/')) {
    return NON_DEFAULT_PUBLIC_LOCALES
  }

  if (page.path.includes('/:slug') && stripPublicLocalePrefix(page.path) === '/:slug(.*)*') {
    return NON_DEFAULT_PUBLIC_LOCALES
  }

  if (typeof page.path === 'string' && page.path.includes('/:')) {
    const dynamicPrefix = DYNAMIC_PREFIX_PATHS[firstBarePathSegment(page.path) || '']

    if (dynamicPrefix) {
      return Object.keys(dynamicPrefix)
        .filter((locale) => locale !== DEFAULT_PUBLIC_LOCALE)
    }
  }

  return supportedPublicLocalesForPath(page.path)
    .filter((locale) => locale !== DEFAULT_PUBLIC_LOCALE)
}

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: '2025-07-15',
  devtools: { enabled: false },
  nitro: {
    prerender: {
      routes: PRERENDER_ROUTE_PATHS,
    },
  },
  experimental: {
    defaults: {
      nuxtLink: {
        prefetch: true,
        prefetchOn: {
          interaction: true,
          visibility: false,
        },
      },
    },
  },
  modules: ['motion-v/nuxt'],
  css: [
    '@fontsource/inter/300.css',
    '@fontsource/inter/400.css',
    '@fontsource/inter/500.css',
    '@fontsource/inter/600.css',
    '@fontsource/inter/700.css',
    '@fontsource/montserrat/200.css',
    '@fontsource/montserrat/300.css',
    '@fontsource/montserrat/400.css',
    '@fontsource/montserrat/500.css',
    '@fontsource/montserrat/600.css',
    '@fontsource/outfit/400.css',
    '@fontsource/outfit/500.css',
    '@fontsource/outfit/600.css',
    '@fontsource/outfit/700.css',
    '@fontsource/outfit/800.css',
    '~/assets/css/main.css',
  ],
  vite: {
    plugins: [tailwindcss()],
    build: {
      manifest: 'manifest.json',
      modulePreload: false,
    },
  },
  runtimeConfig: {
    public: {
      apiBaseUrl: process.env.NUXT_PUBLIC_API_BASE_URL || 'https://api.hub.bent.ge/api',
      gtmId: process.env.NUXT_PUBLIC_GTM_ID || 'GTM-N7XKF6C',
      siteBaseUrl: process.env.NUXT_PUBLIC_SITE_BASE_URL || 'http://127.0.0.1:3000',
    },
  },
  app: {
    head: {
      title: 'bent.ge',
      htmlAttrs: {
        lang: 'en',
      },
      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { name: 'theme-color', content: '#101935' },
      ],
      link: [
        { rel: 'icon', type: 'image/svg+xml', href: '/favicon.svg' },
        { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' },
        { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/favicon-16x16.png' },
        { rel: 'apple-touch-icon', sizes: '180x180', href: '/apple-touch-icon.png' },
        { rel: 'manifest', href: '/site.webmanifest' },
      ],
    },
  },
  hooks: {
    'pages:extend'(pages) {
      const sourcePages = pages.filter((page: any) => !String(page.name || '').includes('___'))
      pages.push(
        ...sourcePages.flatMap((page: any) =>
          supportedLocalesForPage(page).map((locale) => cloneLocalizedPage(page, locale)),
        ),
      )
      pages.push(...buildLegacyLuxuryDetailPages(sourcePages))
    },
  },
})
