import { cmsPageHref, pickLocalized, type FooterPageLink } from "@/features/shared/types/cms";

/** The three core pages the footer always links, CMS title or not. */
export const CORE_PAGE_LINKS = [
  {
    slug: "about",
    href: "/about-us",
    translationKey: "COMMON.ABOUTUS",
  },
  {
    slug: "privacy",
    href: "/privacy-policy",
    translationKey: "COMMON.PRIVACYPOLICY",
  },
  {
    slug: "terms",
    href: "/termsofuse",
    translationKey: "COMMON.TERMS.OF.USE",
  },
] as const;

export interface FooterPageEntry {
  slug: string;
  href: string;
  label: string;
}

/**
 * The footer's page links: the three core pages (CMS title, else the chrome
 * label), then every other page the admin has published, in the CMS order.
 *
 * The extra pages are what makes `/pages/[slug]` reachable at all (PDF p.32 —
 * the platform pages are managed from the dashboard). `GET /home/` lists them
 * under `footer.pages`, but only the three core slugs were ever drawn, so a
 * newly published page existed at a URL nothing linked to. A page with no title
 * in either language is skipped rather than shown as a blank link.
 */
export function footerPageLinks(
  pages: readonly FooterPageLink[] | null | undefined,
  language: string,
  t: (key: string) => string,
): FooterPageEntry[] {
  const published = Array.isArray(pages) ? pages : [];
  const core: FooterPageEntry[] = CORE_PAGE_LINKS.map((page) => {
    const cmsPage = published.find((item) => item.slug === page.slug);
    return {
      slug: page.slug,
      href: page.href,
      label: pickLocalized(cmsPage?.title_en, cmsPage?.title_ar, language) || t(page.translationKey),
    };
  });
  const coreSlugs = new Set<string>(CORE_PAGE_LINKS.map((page) => page.slug));
  const extra = published
    .filter((page) => page.slug && page.slug !== "contact" && !coreSlugs.has(page.slug))
    .map((page) => ({
      slug: page.slug,
      href: cmsPageHref(page.slug),
      label: pickLocalized(page.title_en, page.title_ar, language),
    }))
    .filter((page) => page.label !== "");
  return [...core, ...extra];
}
