/**
 * Regional landing page URLs.
 *
 *   /            Global, default language (English)
 *   /fr          Global, French (any other Global language)
 *   /we          Western Europe, its default language
 *   /we/fr       Western Europe, French
 *
 * A region's default language never gets a suffix (/we/en → /we when English is
 * the default), so each page has exactly one URL. Inner pages (/about …) are global.
 */
import type { Metadata } from "next";
import type { PublicLanguage, PublicRegion } from "./content";

export const GLOBAL = "global";

export type Landing = { region: PublicRegion; language: PublicLanguage };
export type Resolved = { landing: Landing } | { redirect: string } | null;

export function landingPath(region: PublicRegion, lang: string): string {
  const base = region.code === GLOBAL ? "" : `/${region.code}`;
  if (lang === region.defaultLanguage) return base || "/";
  return `${base}/${lang}`;
}

const langOf = (region: PublicRegion, code: string) => region.languages.find((l) => l.code === code);

/** URL segments → the landing page to render, a redirect to its one canonical URL, or null (404). */
export function resolveLanding(regions: PublicRegion[], first?: string, second?: string): Resolved {
  const global = regions.find((r) => r.code === GLOBAL);
  if (!global) return null;
  const pick = (region: PublicRegion, code: string): Resolved => {
    const language = langOf(region, code);
    if (!language) return null;
    const canonical = landingPath(region, code);
    const asked = `/${[first, second].filter(Boolean).join("/")}`;
    return canonical === asked ? { landing: { region, language } } : { redirect: canonical };
  };

  if (!first) return pick(global, global.defaultLanguage);
  if (first === GLOBAL) return pick(global, second ?? global.defaultLanguage);

  const region = regions.find((r) => r.code === first);
  if (region) return pick(region, second ?? region.defaultLanguage);

  // Not a region: a Global language (/fr). Two segments here is never valid.
  if (second || !langOf(global, first)) return null;
  return pick(global, first);
}

/** Every landing URL's params, for generateStaticParams. */
export function landingParams(regions: PublicRegion[]) {
  const one: { region: string }[] = [];
  const two: { region: string; lang: string }[] = [];
  for (const region of regions) {
    for (const l of region.languages) {
      const segs = landingPath(region, l.code).split("/").filter(Boolean);
      if (segs.length === 1) one.push({ region: segs[0] });
      if (segs.length === 2) two.push({ region: segs[0], lang: segs[1] });
    }
  }
  // Cache Components fails the build when generateStaticParams returns nothing (e.g. no
  // region offers a second language). A placeholder that resolves to 404 keeps it valid.
  if (!one.length) one.push({ region: "_none" });
  if (!two.length) two.push({ region: GLOBAL, lang: "_none" });
  return { one, two };
}

/** Origin for canonical / hreflang / sitemap URLs. Set NEXT_PUBLIC_SITE_URL in production. */
export const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000").replace(/\/+$/, "");

const BASE_TITLE = "Unionists Group | Global Leader in Agriculture & Food Supply";

/**
 * Canonical + hreflang for a landing page. The alternates are the same region's other
 * languages (translations of this page); other regions are different pages.
 */
export function landingMetadata({ region, language }: Landing, description?: string): Metadata {
  const languages: Record<string, string> = {};
  for (const l of region.languages) languages[l.bcp47] = landingPath(region, l.code);
  languages["x-default"] = landingPath(region, region.defaultLanguage);
  return {
    metadataBase: new URL(SITE_URL),
    title: region.code === GLOBAL ? BASE_TITLE : `Unionists Group ${region.name} | Global Leader in Agriculture & Food Supply`,
    description,
    alternates: { canonical: landingPath(region, language.code), languages },
    openGraph: { locale: language.bcp47.replace("-", "_"), url: landingPath(region, language.code), siteName: "Unionists Group" },
  };
}
