import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import { getPageDetail, type PageDetail } from '@/lib/db/queries/getPageDetail'
import { getDefaultLanguage } from '@/lib/db/queries/getlanguages'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { buildLocalizedPath } from '@/lib/i18n/buildLocalizedPath'
import JsonLd from '@/components/frontend/seo/JsonLd'
import LegalLayout from '@/components/frontend/legal/LegalLayout'
import { faqifyHtml } from '@/lib/cms/faqify'

const APP_URL = (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000').replace(/\/$/, '')

interface CmsPageProps {
  params: Promise<{ locale: string; slug: string }>
}

// Same idempotent decode as product/[slug]/page.tsx and category/[slug]/page.tsx.
function decodeSlug(slug: string): string {
  try {
    return decodeURIComponent(slug)
  } catch {
    return slug
  }
}

function buildAlternatePaths(page: PageDetail, defaultLocale: string): Record<string, string> {
  const paths: Record<string, string> = {}
  for (const alt of page.alternateLocales) {
    paths[alt.locale] = buildLocalizedPath(alt.locale, defaultLocale, `/${alt.slug}`)
  }
  return paths
}

export async function generateMetadata({ params }: CmsPageProps): Promise<Metadata> {
  const { locale, slug } = await params
  const [page, defaultLanguage, siteInfo] = await Promise.all([
    getPageDetail(decodeSlug(slug), locale),
    getDefaultLanguage(),
    getSiteInfo(),
  ])
  if (!page) return {}

  const defaultLocale = defaultLanguage?.code ?? 'en'
  const alternatePaths = buildAlternatePaths(page, defaultLocale)
  const canonicalPath = buildLocalizedPath(locale, defaultLocale, `/${page.slug}`)

  const title = page.metaTitle || page.title
  const description =
    page.metaDescription ||
    (page.content ? page.content.replace(/<[^>]+>/g, '').slice(0, 160) : undefined)

  return {
    title: `${title} | ${siteInfo.siteName}`,
    description,
    alternates: {
      canonical: `${APP_URL}${canonicalPath}`,
      languages: {
        ...Object.fromEntries(
          Object.entries(alternatePaths).map(([loc, path]) => [loc, `${APP_URL}${path}`]),
        ),
        'x-default': `${APP_URL}${alternatePaths[defaultLocale] ?? canonicalPath}`,
      },
    },
    openGraph: {
      title,
      description,
      siteName: siteInfo.siteName,
      url: `${APP_URL}${canonicalPath}`,
      type: 'website',
    },
    twitter: { card: 'summary', title, description },
  }
}

// Generic CMS text page (FAQ, Privacy, Terms, Return/Shipping/Cancellation
// Policy, and any future admin-created page) — a single dynamic route for
// every `pages`/`page_translations` row instead of one hand-written static
// route per legal document. Only reached for a URL that doesn't match any
// more specific static route under (root)/[locale]/ (Next.js always
// prefers a literal segment — /cart, /products, /faq's old folder before it
// was deleted, etc. — over a same-level [slug] catch), so this is safe to
// add without touching any other route. See DATA_FETCHING_PATTERN.md /
// Till_Done.md for the full migration.
export default async function CmsPage({ params }: CmsPageProps) {
  const { locale, slug } = await params

  const page = await getPageDetail(decodeSlug(slug), locale)
  if (!page) notFound()

  const lastUpdated = new Date(page.updatedAt).toLocaleDateString(locale, {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  })

  return (
    <>
      <JsonLd data={Object.values(page.schemas) as Record<string, unknown>[]} />
      <LegalLayout title={page.title} lastUpdated={lastUpdated}>
        <div
          className="prose prose-lg max-w-none prose-headings:text-dark prose-p:text-gray-custom prose-strong:text-dark prose-li:text-gray-custom"
          dangerouslySetInnerHTML={{ __html: faqifyHtml(page.content ?? '') }}
        />
      </LegalLayout>
    </>
  )
}
