import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import { headers } from 'next/headers'
import Script from 'next/script'
import '../globals.css'
import { GoogleOAuthWrapper } from '../GoogleOAuthWrapper'
import { PaddleProvider } from '../PaddleProvider'
import { NextIntlClientProvider } from 'next-intl'
import { getMessages } from 'next-intl/server'
import { routing } from '@/i18n/routing'
import CookieConsentBanner from '@/components/CookieConsentBanner'
import GoogleAnalyticsConsent from '@/components/GoogleAnalyticsConsent'

const inter = Inter({ subsets: ['latin'], variable: '--font-sans' })

const BASE_URL = process.env.NEXT_PUBLIC_APP_URL ?? 'https://www.cahootravel.com'

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string }>
}): Promise<Metadata> {
  const { locale } = await params

  // x-pathname is injected by middleware so we can build a self-referencing
  // canonical URL and per-page hreflang tags server-side. Fall back to the
  // locale root for any edge case where the header is absent (e.g. static
  // pre-rendering at build time).
  const requestHeaders = headers()
  const pathname =
    requestHeaders.get('x-pathname') ??
    (locale === routing.defaultLocale ? '/' : `/${locale}`)

  // Strip the locale prefix to get the bare page path.
  // '/pl-PL/security' with locale 'pl-PL' → '/security'
  // '/pricing'        with locale 'en-GB' → '/pricing'
  const localePrefix = locale === routing.defaultLocale ? '' : `/${locale}`
  const pagePath = (
    pathname.startsWith(localePrefix)
      ? pathname.slice(localePrefix.length)
      : pathname
  ) || '/'

  // Build per-page hreflang pointing to the same page in every locale.
  // e.g. for '/security':  en-GB → /security,  de-DE → /de-DE/security
  const languages: Record<string, string> = {}
  for (const loc of routing.locales) {
    const prefix = loc === routing.defaultLocale ? '' : `/${loc}`
    languages[loc] = pagePath === '/' ? (prefix || '/') : `${prefix}${pagePath}`
  }
  // x-default signals the preferred fallback for unmatched locales (English).
  languages['x-default'] = pagePath === '/' ? '/' : pagePath

  return {
    metadataBase: new URL(BASE_URL),
    title: {
      template: '%s | CahooTravel',
      default: 'CahooTravel — Find Hidden Hotel Price Gaps & Save',
    },
    description:
      'Compare hotel prices from 100+ countries. Reveal geo-pricing gaps on Booking.com, Airbnb, Expedia and more — and book at the cheapest rate. Free to start.',
    icons: { icon: '/favicon.svg' },
    openGraph: {
      type: 'website',
      siteName: 'CahooTravel',
      title: 'CahooTravel — Find Hidden Hotel Price Gaps & Save',
      description:
        'Compare hotel prices from 100+ countries. Reveal geo-pricing gaps on Booking.com, Airbnb, Expedia and more — and book at the cheapest rate.',
      images: [
        {
          url: `${BASE_URL}/api/og`,
          width: 1200,
          height: 630,
          alt: 'CahooTravel — The smartest way to book your next adventure.',
        },
      ],
      locale,
    },
    twitter: {
      card: 'summary_large_image',
      title: 'CahooTravel — Find Hidden Hotel Price Gaps & Save',
      description:
        'Compare hotel prices from 100+ countries. Reveal geo-pricing gaps on Booking.com, Airbnb, Expedia and more — and book at the cheapest rate.',
      images: [`${BASE_URL}/api/og`],
    },
    alternates: {
      canonical: pathname,
      languages,
    },
  }
}

const organizationSchema = {
  '@context': 'https://schema.org',
  '@type': 'Organization',
  name: 'CahooTravel',
  url: BASE_URL,
  logo: `${BASE_URL}/cahootravel-logo.svg`,
  sameAs: [
    'https://www.instagram.com/cahootravel.co',
    'https://www.tiktok.com/@cahootravel.co',
  ],
  contactPoint: {
    '@type': 'ContactPoint',
    contactType: 'customer support',
    email: 'support@cahootravel.com',
  },
}

export default async function LocaleLayout({
  children,
  params,
}: {
  children: React.ReactNode
  params: Promise<{ locale: string }>
}) {
  const { locale } = await params
  const messages = await getMessages()

  return (
    <html lang={locale}>
      <body className={`${inter.variable} font-sans antialiased`}>
        <NextIntlClientProvider messages={messages}>
          <GoogleOAuthWrapper>
            <PaddleProvider>{children}</PaddleProvider>
          </GoogleOAuthWrapper>
          <CookieConsentBanner />
          <GoogleAnalyticsConsent />
        </NextIntlClientProvider>
        <Script
          src="https://www.googletagmanager.com/gtag/js?id=G-5GNKKJ7HE2"
          strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('consent', 'default', {
              analytics_storage: 'denied',
              ad_storage: 'denied',
              wait_for_update: 500,
            });
            gtag('js', new Date());
            gtag('config', 'G-5GNKKJ7HE2');
          `}
        </Script>
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationSchema) }}
        />
      </body>
    </html>
  )
}
