import type { Metadata } from "next";

import { getCompany, getModule, getProduct, getSector, getT } from "@/lib/content";
import { DEFAULT_LOCALE, isLocale, type Locale } from "@/lib/locales";
import { buildMetadata } from "@/lib/metadata";
import { allTargets, moduleById, resolveRoute, segmentsFor, type RouteTarget } from "@/lib/routes";

import { ClientsView } from "../_views/Clients";
import { CompanyView } from "../_views/Company";
import { ContactView } from "../_views/Contact";
import { HomeView } from "../_views/Home";
import { ModuleView } from "../_views/Module";
import { NexysView } from "../_views/Nexys";
import { NotFoundView } from "../_views/NotFound";
import { PrivacyView } from "../_views/Privacy";
import { SectorsView, SectorView } from "../_views/Sectors";
import { SupportView } from "../_views/Support";

/**
 * RRYM / 002 — SULSYS — the page resolver.
 *
 * Every URL on the site is declared once in `lib/routes.ts`, including both
 * locales' spellings of each segment. This page resolves the incoming segments
 * against that registry and dispatches to a view. Two consequences matter:
 *
 *  · The language switch can always find the exact counterpart URL, because
 *    the registry knows both spellings of the same page (Blueprint 03).
 *  · A page cannot exist in one language only — `generateStaticParams` walks
 *    the same list for every locale, so a missing counterpart is impossible
 *    rather than merely linted (Blueprint 17 rule 2).
 *
 * `dynamicParams = false` means anything outside the registry is a 404 at the
 * framework level, with no server work at all.
 */

export const dynamicParams = false;

export function generateStaticParams({ params }: { params: { locale: string } }) {
  const locale = isLocale(params.locale) ? params.locale : DEFAULT_LOCALE;
  return allTargets().map((target) => ({ slug: segmentsFor(target, locale) }));
}

type PageParams = { locale: string; slug?: string[] };

function resolve(params: PageParams): { locale: Locale; target: RouteTarget } | null {
  if (!isLocale(params.locale)) return null;
  const target = resolveRoute(params.locale, params.slug);
  return target ? { locale: params.locale, target } : null;
}

/* -------------------------------------------------------------------------- */
/* Metadata                                                                   */
/* -------------------------------------------------------------------------- */

export async function generateMetadata({
  params,
}: {
  params: Promise<PageParams>;
}): Promise<Metadata> {
  const resolved = resolve(await params);
  if (!resolved) return { title: "404" };

  const { locale, target } = resolved;
  const t = getT(locale);

  switch (target.key) {
    case "home":
      return buildMetadata({
        locale,
        target,
        title: t("meta.home.title"),
        description: t("meta.home.description"),
      });

    case "nexys": {
      const product = getProduct(locale);
      return buildMetadata({
        locale,
        target,
        title: product.name,
        description: t("meta.nexys.description"),
      });
    }

    case "module": {
      const meta = moduleById(target.module);
      const content = getModule(locale, target.module);
      return buildMetadata({
        locale,
        target,
        title: `${content.brandName} — ${content.name}`,
        description: t("meta.moduleDescription", {
          brand: meta?.brandName ?? content.brandName,
          name: content.name,
        }),
      });
    }

    case "sectors":
      return buildMetadata({
        locale,
        target,
        title: t("sectors.title"),
        description: t("meta.sectors.description"),
      });

    case "sector": {
      const sector = getSector(locale, target.sector);
      return buildMetadata({
        locale,
        target,
        title: sector.name,
        description: t("meta.sectorDescription", { name: sector.name }),
      });
    }

    case "clients":
      return buildMetadata({
        locale,
        target,
        title: t("clients.title"),
        description: t("meta.clients.description"),
      });

    case "support":
      return buildMetadata({
        locale,
        target,
        title: t("support.title"),
        description: t("meta.support.description"),
      });

    case "company": {
      const company = getCompany(locale);
      return buildMetadata({
        locale,
        target,
        title: company.name,
        description: t("meta.company.description"),
      });
    }

    case "contact":
      return buildMetadata({
        locale,
        target,
        title: t("contact.title"),
        description: t("meta.contact.description"),
      });

    case "privacy":
      return buildMetadata({
        locale,
        target,
        title: t("form.privacyLink"),
        description: t("meta.privacy.description"),
      });

    case "notFound":
      return buildMetadata({
        locale,
        target,
        title: t("notFound.title"),
        description: t("meta.notFound.description"),
        noindex: true,
      });
  }
}

/* -------------------------------------------------------------------------- */
/* Page                                                                       */
/* -------------------------------------------------------------------------- */

export default async function Page({ params }: { params: Promise<PageParams> }) {
  const resolved = resolve(await params);

  // Unreachable with `dynamicParams = false`, but the view is the right
  // fallback rather than a framework error page.
  if (!resolved) return <NotFoundView locale={DEFAULT_LOCALE} />;

  const { locale, target } = resolved;

  switch (target.key) {
    case "home":
      return <HomeView locale={locale} />;
    case "nexys":
      return <NexysView locale={locale} />;
    case "module":
      return <ModuleView locale={locale} moduleId={target.module} />;
    case "sectors":
      return <SectorsView locale={locale} />;
    case "sector":
      return <SectorView locale={locale} sectorId={target.sector} />;
    case "clients":
      return <ClientsView locale={locale} />;
    case "support":
      return <SupportView locale={locale} />;
    case "company":
      return <CompanyView locale={locale} />;
    case "contact":
      return <ContactView locale={locale} />;
    case "privacy":
      return <PrivacyView locale={locale} />;
    case "notFound":
      return <NotFoundView locale={locale} />;
  }
}
