// Cœur de rendu des routes localisées EN/ES (app/en|es/[[...slug]]).
//
// Stratégie additive : on résout l'URI localisée vers son identité FR + type de
// contenu, on récupère la traduction Polylang via les mêmes fetchers que le FR,
// et on rend avec les MÊMES composants (BlockRenderer, Navbar, Footer) — parité
// pixel garantie. Aucune route FR existante n'est modifiée.

import type { Metadata } from "next";
import { notFound } from "next/navigation";

import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import StickyMobileCTA from "@/components/StickyMobileCTA";
import JsonLd from "@/components/seo/JsonLd";
import { BlockRenderer } from "@/components/blocks/BlockRenderer";
import {
  type Locale,
  I18N_ROUTES,
  SELECT_LANGUAGE_PATH,
  SITE_URL,
  localizedUrl,
} from "@/config/i18nRoutes";
import { resolveLocalizedUri } from "./resolve";
import { localizeAltDeep } from "@/lib/wp/localizeAlt";
import { getWpPage } from "@/lib/wp/queries/page";
import { getProduit } from "@/lib/wp/queries/produit";
import { getToiture } from "@/lib/wp/queries/toiture";
import { getIndustrie } from "@/lib/wp/queries/industrie";
import { wpSeoToMetadata, breadcrumbJsonLd } from "@/lib/wp/seoToMetadata";
import type { WpSectionsField, WpSeo } from "@/lib/wp/types";

interface LocalizedContent {
  title?: string | null;
  seo?: WpSeo | null;
  sections?: WpSectionsField | null;
}

/** Construit l'URI localisée à partir du segment de route et de la locale. */
function toLocalizedUri(locale: Locale, slug?: string[]): string {
  const rest = slug && slug.length ? `/${slug.join("/")}` : "";
  return `/${locale}${rest}`;
}

async function fetchLocalized(localizedUri: string, locale: Locale): Promise<LocalizedContent | null> {
  const r = resolveLocalizedUri(localizedUri, locale);
  if (!r) return null;
  try {
    let content: LocalizedContent | null;
    switch (r.kind) {
      case "home":
      case "page":
        content = await getWpPage(r.pageUri, locale);
        break;
      case "produit":
        content = r.cptSlug ? await getProduit(r.cptSlug, locale) : null;
        break;
      case "toiture":
        content = r.cptSlug ? await getToiture(r.cptSlug, locale) : null;
        break;
      case "industrie":
        content = r.cptSlug ? await getIndustrie(r.cptSlug, locale) : null;
        break;
      case "blog":
        content = null; // index blog localisé = front-only, hors périmètre seed
        break;
      default:
        content = null;
    }
    // EN/ES : replie les alt traduits (postmeta) sur `altText` avant le rendu.
    return content ? localizeAltDeep(content, locale) : content;
  } catch (error) {
    console.error("[i18n] contenu indisponible pour", localizedUri, error);
    return null;
  }
}

/** Alternates hreflang FR/EN/ES + x-default, à partir du triple de la page. */
function hreflangAlternates(frUri: string, locale: Locale): Metadata["alternates"] {
  const triple = I18N_ROUTES.find((t) => t.fr === frUri);
  if (!triple) return { canonical: localizedUrl(locale, frUri) };
  return {
    canonical: `${SITE_URL}${triple[locale]}`,
    languages: {
      fr: `${SITE_URL}${triple.fr}`,
      en: `${SITE_URL}${triple.en}`,
      es: `${SITE_URL}${triple.es}`,
      "x-default": `${SITE_URL}${SELECT_LANGUAGE_PATH}`,
    },
  };
}

export async function localizedMetadata(locale: Locale, slug?: string[]): Promise<Metadata> {
  const localizedUri = toLocalizedUri(locale, slug);
  const r = resolveLocalizedUri(localizedUri, locale);
  if (!r) return {};
  const content = await fetchLocalized(localizedUri, locale);

  const base = wpSeoToMetadata(
    content?.seo,
    {
      ...(content?.title ? { title: content.title } : {}),
      canonical: localizedUrl(locale, r.frUri),
    },
    locale
  );

  return { ...base, alternates: hreflangAlternates(r.frUri, locale) };
}

export async function renderLocalizedRoute(locale: Locale, slug?: string[]) {
  const localizedUri = toLocalizedUri(locale, slug);
  const r = resolveLocalizedUri(localizedUri, locale);
  if (!r) notFound();
  const content = await fetchLocalized(localizedUri, locale);
  if (!content || !content.sections) notFound();

  const pageUrl = localizedUrl(locale, r.frUri);
  return (
    <div className="min-h-screen bg-background">
      <JsonLd
        id="wp-page-breadcrumb-jsonld"
        data={breadcrumbJsonLd([{ name: content.title ?? "Covalba", url: pageUrl }])}
      />
      <Navbar locale={locale} />
      <main>
        <BlockRenderer sections={content.sections?.sections} locale={locale} />
      </main>
      <Footer locale={locale} />
      <StickyMobileCTA locale={locale} />
    </div>
  );
}

/** Les routes connues d'une locale (sans le préfixe /xx), hors blog (front-only). */
export function localizedStaticParams(locale: Locale): { slug: string[] }[] {
  return I18N_ROUTES.filter((t) => t.fr !== "/blog")
    .map((t) => t[locale])
    .map((uri) => uri.replace(new RegExp(`^/${locale}`), "").replace(/^\//, ""))
    .map((rest) => ({ slug: rest ? rest.split("/") : [] }));
}
