/**
 * Website-side types and clean-up for CMS home page content
 * (GET /public/home-page, see the "Unionists CMS API Reference").
 */
import type { Background, Cta, Img, RichTitle } from "@/app/(admin)/_lib/cms";
import { MEDIA_ORIGIN } from "@/app/(admin)/_lib/media";

export type { Background, Cta, Img, RichTitle };

export type PublicLanguage = { code: string; name: string; nativeName: string; bcp47: string; dir: "ltr" | "rtl" };
export type PublicRegion = {
  code: string;
  name: string;
  /** "/" for Global, else "/<code>". */
  path: string;
  isDefault: boolean;
  defaultLanguage: string;
  languages: PublicLanguage[];
};

export type HeroContent = { title: RichTitle; subtitle?: string; background: Background; ctas: Cta[] };
export type StatsContent = { items: { value: string; label?: string; icon?: Img }[] };
export type FeatureCardsContent = { title?: RichTitle; items: { title: string; description?: string; icon?: Img }[]; ctas: Cta[] };
export type TextImageContent = { title: RichTitle; body: string; image: Img; imagePosition: "left" | "right" };
export type LogoGridContent = { title: RichTitle; logos: { image: Img; name?: string; href?: string }[] };
export type CtaBannerContent = { title: RichTitle; body?: string; cta: Cta };
export type CaseStudyContent = { title: RichTitle; body: string; bullets: string[]; image: Img; ctas: Cta[] };
export type ContactContent = {
  title: RichTitle;
  body?: string;
  phone?: string;
  email?: string;
  address?: string;
  mapUrl?: string;
  ctas: Cta[];
  formTitle?: string;
  submitLabel: string;
};
export type FooterContent = {
  description?: string;
  linkGroups: { title: string; links: Cta[] }[];
  socialLinks: Cta[];
  copyright?: string;
};

/** Section key → its content shape (12 fixed sections). */
export type SectionContent = {
  hero: HeroContent;
  "proof-of-scale": StatsContent;
  "trust-badges": FeatureCardsContent;
  about: TextImageContent;
  mission: TextImageContent;
  solutions: FeatureCardsContent;
  "global-impact": TextImageContent;
  "strategic-partners": LogoGridContent;
  "become-partner": CtaBannerContent;
  "case-study": CaseStudyContent;
  contact: ContactContent;
  footer: FooterContent;
};
export type SectionKey = keyof SectionContent;

/** One section as the website receives it. `language` is the language actually served (may be a fallback). */
export type HomeSection = { [K in SectionKey]: { key: K; language: string; content: SectionContent[K] } }[SectionKey];

export type PublicHomePage = { region: { code: string; name: string; path: string }; language: PublicLanguage; sections: HomeSection[] };

/* ------------------------------------------------------------------ */
/* Clean-up                                                            */
/* ------------------------------------------------------------------ */

/**
 * The CMS seed content was written for the old static site: images under
 * /images/home/<file>, which live here under /assets/images/<folder>/<file>
 * (same file names; the folder depends on the section, e.g. two different
 * icon-sustainable.png exist). Update the CMS content to /assets/... paths
 * and this map becomes a no-op.
 */
const LEGACY_IMAGE_DIR: Partial<Record<SectionKey, string>> = {
  hero: "/assets/images",
  "proof-of-scale": "/assets/images/stats",
  "trust-badges": "/assets/images/highlights",
  solutions: "/assets/images/offers",
  about: "/assets/images/content",
  mission: "/assets/images/content",
  "global-impact": "/assets/images/content",
  "case-study": "/assets/images/content",
  "strategic-partners": "/assets/images/partners",
};

/** Media URL as the browser should load it. */
export function mediaSrc(url: string, section?: string): string {
  const u = url.trim();
  // The API sometimes returns its internal host for uploads (http://localhost:4012/uploads/…).
  const upload = /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?(\/uploads\/.*)$/i.exec(u);
  if (upload) return MEDIA_ORIGIN + upload[1];
  if (u.startsWith("/uploads/")) return MEDIA_ORIGIN + u;
  const legacy = /^\/images\/home\/([^/]+)$/.exec(u);
  const dir = section ? LEGACY_IMAGE_DIR[section as SectionKey] : undefined;
  if (legacy && dir) return `${dir}/${legacy[1]}`;
  return u;
}

/** Links saved against the old static site (/pages/about.html) → the real route (/about), skipping a redirect. */
export function siteHref(href: string): string {
  const h = href.trim();
  if (h === "/index.html") return "/";
  const m = /^\/pages\/([\w-]+)\.html(?=$|[?#])(.*)$/.exec(h);
  return m ? `/${m[1]}${m[2]}` : h;
}

const MEDIA_KEYS = new Set(["url", "posterUrl"]);
const LINK_KEYS = new Set(["href", "mapUrl"]);

/** Applies mediaSrc / siteHref to every media and link field in a section's content. */
export function normalizeContent<T>(value: T, section?: string): T {
  const walk = (v: unknown, key?: string): unknown => {
    if (typeof v === "string") {
      if (key && MEDIA_KEYS.has(key)) return mediaSrc(v, section);
      if (key && LINK_KEYS.has(key)) return siteHref(v);
      return v;
    }
    if (Array.isArray(v)) return v.map((x) => walk(x));
    if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k)]));
    return v;
  };
  return walk(value) as T;
}
