import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { PageRenderer } from "@/sections/PageRenderer";
import { getPageBySlug, listPublishedSlugs } from "@/lib/wp/pages";
import { yoastToMetadata, yoastJsonLdGraph } from "@/lib/wp/yoast";
import { safeJsonLd } from "@/lib/wp/seo-defaults";
import {
  DEFAULT_LOCALE,
  LOCALES,
  isLocale,
  splitLocaleFromSegments,
  type Locale,
} from "@/lib/i18n/config";

interface RouteProps {
  params: Promise<{ path?: string[] }>;
}

const HOME_SLUG = "home";

function resolveSlug(segments: string[]): string {
  return segments.length === 0 ? HOME_SLUG : segments.join("/");
}

/**
 * Pre-render every (locale, slug) pair WordPress knows about. The default
 * locale's pages render at `/<slug>`; non-default locales render at
 * `/<locale>/<slug>`.
 */
export async function generateStaticParams(): Promise<Array<{ path: string[] }>> {
  const lists = await Promise.all(
    LOCALES.map(async (locale) => ({ locale, slugs: await listPublishedSlugs(locale) })),
  );

  const params: Array<{ path: string[] }> = [];
  for (const { locale, slugs } of lists) {
    for (const slug of slugs) {
      const slugSegments = slug === HOME_SLUG ? [] : slug.split("/");
      const segments = locale === DEFAULT_LOCALE ? slugSegments : [locale, ...slugSegments];
      params.push({ path: segments });
    }
  }
  return params;
}

export async function generateMetadata({ params }: RouteProps): Promise<Metadata> {
  const { path = [] } = await params;
  const { locale, slug } = splitLocaleFromSegments(path);
  const wpSlug = resolveSlug(slug);
  const page = await getPageBySlug(wpSlug, locale);
  if (!page) return {};

  const alternates: Record<string, string> = {};
  for (const altLocale of LOCALES) {
    alternates[altLocale] = hrefFor(altLocale, slug);
  }

  const fromYoast = yoastToMetadata(page.yoast, {
    title: page.title,
    description: page.meta_description,
  });

  return {
    ...fromYoast,
    title: fromYoast.title ?? page.title,
    description: fromYoast.description ?? page.meta_description,
    alternates: {
      canonical: fromYoast.alternates?.canonical ?? hrefFor(locale, slug),
      languages: alternates,
    },
  };
}

export default async function CatchAllPage({ params }: RouteProps) {
  const { path = [] } = await params;

  // Reject unknown locale prefixes early so they don't poison cache keys.
  if (path.length > 0) {
    const first = path[0];
    if (first.length === 2 && !isLocale(first)) {
      // Not a locale, treat as content slug.
    }
  }

  const { locale, slug } = splitLocaleFromSegments(path);
  const wpSlug = resolveSlug(slug);
  const page = await getPageBySlug(wpSlug, locale);
  if (!page) {
    notFound();
  }

  const pageJsonLd = yoastJsonLdGraph(page.yoast);

  return (
    <main
      data-page={page.slug}
      data-transparent-header={page.transparent_header ? "true" : "false"}
    >
      {pageJsonLd ? (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: safeJsonLd(pageJsonLd) }}
        />
      ) : null}
      <PageRenderer
        sections={page.sections.filter(
          (s): s is { layout: string; data: unknown } => s.data !== null,
        )}
      />
    </main>
  );
}

function hrefFor(locale: Locale, slug: string[]): string {
  const slugPath = slug.join("/");
  const base = locale === DEFAULT_LOCALE ? "" : `/${locale}`;
  if (slugPath === "" || slugPath === HOME_SLUG) {
    return base === "" ? "/" : base;
  }
  return `${base}/${slugPath}`;
}
