import type { Metadata, Viewport } from 'next';
import { notFound } from 'next/navigation';
import { LOCALES, isLocale, localeMeta, type Locale } from '@ai-radar/shared';
import { SITE, absoluteUrl, baseUrl, localeAlternates } from '@/lib/site';
import { getDictionary } from '@/lib/dictionary';
import { SiteHeader } from '@/components/layout/SiteHeader';
import { SiteFooter } from '@/components/layout/SiteFooter';
import '../globals.css';
import '../token.css';

/**
 * The real root layout, nested under [lang] so it can set <html lang>
 * and dir from the route.
 *
 * Both locales are pre-rendered: there are only two, and they are known
 * at build time.
 */
export function generateStaticParams() {
  return LOCALES.map((lang) => ({ lang }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ lang: string }>;
}): Promise<Metadata> {
  // Next.js 16 removed synchronous params access.
  const { lang } = await params;
  if (!isLocale(lang)) return {};

  const meta = localeMeta(lang);
  const site = SITE[lang];

  return {
    metadataBase: new URL(baseUrl()),
    title: {
      default: `${site.name} — ${site.tagline}`,
      template: `%s · ${site.name}`,
    },
    description: site.description,
    applicationName: site.name,
    alternates: {
      canonical: absoluteUrl(`/${lang}`),
      // hreflang for both locales plus x-default, so Google serves the
      // right language and neither version competes with the other.
      languages: localeAlternates('/'),
      types: { 'application/rss+xml': absoluteUrl(`/${lang}/rss.xml`) },
    },
    openGraph: {
      type: 'website',
      siteName: site.name,
      title: `${site.name} — ${site.tagline}`,
      description: site.description,
      url: absoluteUrl(`/${lang}`),
      locale: meta.ogLocale,
    },
    twitter: {
      card: 'summary_large_image',
      title: `${site.name} — ${site.tagline}`,
      description: site.description,
    },
    robots: {
      index: true,
      follow: true,
      googleBot: { index: true, follow: true, 'max-image-preview': 'large' },
    },
  };
}

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  themeColor: [
    { media: '(prefers-color-scheme: light)', color: '#ffffff' },
    { media: '(prefers-color-scheme: dark)', color: '#0b0d11' },
  ],
};

/**
 * Applies the saved theme before first paint, so a dark-mode reader
 * never sees a white flash. Inline by necessity.
 */
const THEME_SCRIPT = `
(function(){
  try {
    var t = localStorage.getItem('theme');
    if (t === 'dark' || t === 'light') {
      document.documentElement.setAttribute('data-theme', t);
    }
  } catch (e) {}
})();
`;

/**
 * Latin faces for English, Arabic faces for Arabic. Loaded per locale.
 *
 * Geist rather than Inter Tight for body text: Inter is the default of
 * every dashboard and SaaS page on the web, which made a publication read
 * like an admin panel. Geist keeps the same clean grotesque skeleton but
 * has more warmth in the curves and a taller x-height, so it holds up at
 * the small sizes the meta lines use.
 *
 * Newsreader stays on headlines — the serif is what makes this look like
 * something edited rather than something generated.
 */
const FONT_HREF: Record<Locale, string> = {
  en: 'https://fonts.googleapis.com/css2?family=Newsreader:ital,opsz,wght@0,6..72,400..600;1,6..72,400&family=Geist:wght@400..600&family=JetBrains+Mono:wght@400..600&display=swap',
  ar: 'https://fonts.googleapis.com/css2?family=Noto+Kufi+Arabic:wght@400..700&family=IBM+Plex+Sans+Arabic:wght@400;500;600&family=Geist:wght@400..600&display=swap',
};

export default async function LangLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();

  const meta = localeMeta(lang);
  const dict = getDictionary(lang);

  return (
    <html lang={meta.htmlLang} dir={meta.dir} suppressHydrationWarning>
      <head>
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
        <link rel="stylesheet" href={FONT_HREF[lang]} />
        <script dangerouslySetInnerHTML={{ __html: THEME_SCRIPT }} />

        {/* AdSense loads only when a publisher id is configured, and
            always async so it cannot block first paint. Absent that,
            no ad script ships at all — which is also what keeps the
            site fast before there is anything to monetise. */}
        {process.env.NEXT_PUBLIC_ADSENSE_CLIENT && (
          <script
            async
            src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_ADSENSE_CLIENT}`}
            crossOrigin="anonymous"
          />
        )}
      </head>
      <body>
        <a href="#main" className="sr-only">
          {lang === 'ar' ? 'انتقل إلى المحتوى' : 'Skip to content'}
        </a>
        <SiteHeader locale={lang} dict={dict} />
        {children}
        <SiteFooter locale={lang} dict={dict} />
      </body>
    </html>
  );
}
