import type { Metadata } from 'next'
import Script from 'next/script'
import { NextIntlClientProvider } from 'next-intl'
import { getMessages, getTranslations, setRequestLocale } from 'next-intl/server'
import { notFound } from 'next/navigation'
import { routing } from '@/i18n/routing'
import Nav from '@/components/layout/Nav'
import Footer from '@/components/layout/Footer'
import GoogleAnalytics from '@/components/analytics/GoogleAnalytics'
import CookieConsent from '@/components/analytics/CookieConsent'
import '@/styles/globals.css'

const BASE_URL = 'https://letsbe.biz'

type Props = {
  children: React.ReactNode
  params: Promise<{ locale: string }>
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params
  const t = await getTranslations({ locale, namespace: 'meta' })

  const ogLocaleMap: Record<string, string> = { en: 'en_US', fr: 'fr_FR', it: 'it_IT', es: 'es_ES' }
  const currentOgLocale = ogLocaleMap[locale] ?? 'en_US'
  const otherOgLocales = Object.values(ogLocaleMap).filter((l) => l !== currentOgLocale)

  return {
    metadataBase: new URL(BASE_URL),
    title: {
      default: t('home.title'),
      template: '%s',
    },
    description: t('home.description'),
    openGraph: {
      type: 'website',
      siteName: t('siteName'),
      locale: currentOgLocale,
      images: [{ url: '/images/og-default.png', width: 1200, height: 630 }],
    },
    other: {
      'og:locale:alternate': otherOgLocales,
    },
    twitter: {
      card: 'summary_large_image',
    },
    robots: {
      index: true,
      follow: true,
    },
  }
}

export function generateStaticParams() {
  return routing.locales.map((locale) => ({ locale }))
}

// ─── JSON-LD: Organization ───────────────────────────────────────────────────

const organizationJsonLd = {
  '@context': 'https://schema.org',
  '@type': 'Organization',
  name: 'LetsBe.',
  url: BASE_URL,
  logo: `${BASE_URL}/images/letsbe-logo-short.png`,
  sameAs: [
    'https://www.linkedin.com/company/letsbe-digital',
    'https://x.com/letsbe_digital',
  ],
  contactPoint: {
    '@type': 'ContactPoint',
    email: 'hello@letsbe.biz',
    contactType: 'customer service',
  },
  availableLanguage: [
    { '@type': 'Language', name: 'English', alternateName: 'en' },
    { '@type': 'Language', name: 'French', alternateName: 'fr' },
    { '@type': 'Language', name: 'Italian', alternateName: 'it' },
    { '@type': 'Language', name: 'Spanish', alternateName: 'es' },
  ],
}

export default async function LocaleLayout({ children, params }: Props) {
  const { locale } = await params

  if (!routing.locales.includes(locale as any)) {
    notFound()
  }

  setRequestLocale(locale)
  const messages = await getMessages()

  return (
    <html lang={locale} className="scroll-smooth">
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationJsonLd) }}
        />
        {process.env.NODE_ENV === 'development' && (
          <Script
            src="//unpkg.com/react-grab/dist/index.global.js"
            crossOrigin="anonymous"
            strategy="beforeInteractive"
          />
        )}
      </head>
      <body className="font-sans text-on-surface bg-surface antialiased">
        <GoogleAnalytics />
        <NextIntlClientProvider messages={messages}>
          <Nav />
          {children}
          <Footer />
          <CookieConsent />
        </NextIntlClientProvider>
      </body>
    </html>
  )
}
