/**
 * Full audit (8 Nov 2026), discovery area: home, lists, CMS pages, header and
 * footer. Regression tests for the frontend defects fixed in this round; see
 * SC/cov/discovery.md (F-DISC-n).
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { toSponsorItems, type SponsorRecord } from "@/features/partners/sponsorRecord";
import { contactWhatsAppHref } from "@/lib/whatsapp";
import { footerPageLinks } from "@/components/layout/footerPages";

const src = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");

describe("F-DISC-1 — one cached shape for GET /sponsors/", () => {
  test("the list-page strip and the partners page share key, query function and envelope", () => {
    const strip = src("features/home/components/SponsorsClient.tsx");
    const partners = src("features/partners/components/usePartnerSponsors.ts");
    for (const file of [strip, partners]) {
      assert.match(file, /queryKey: \["sponsors"\]/);
      assert.match(file, /queryFn: getSponsors/);
    }
    // The strip narrows the envelope per observer instead of caching an array.
    assert.match(strip, /select: \(response\) => toSponsorItems\(response\?\.data\)/);
  });

  test("website sponsor rows become logo tiles; a nameless organization falls back to its contact", () => {
    const rows: SponsorRecord[] = [
      { id: 1, org_name: "Zain", person_name: null, sponsor_logo: "https://x/zain.png", _sponsor_type: null, _type_of_support: null },
      { id: 2, org_name: null, person_name: "Sara", sponsor_logo: null, _sponsor_type: null, _type_of_support: null },
    ];
    assert.deepEqual(toSponsorItems(rows), [
      { id: 1, sponsor_logo: "https://x/zain.png", org_name: "Zain" },
      { id: 2, sponsor_logo: null, org_name: "Sara" },
    ]);
    assert.deepEqual(toSponsorItems(undefined), []);
  });

  test("no approved sponsor hides the «رعاتنا وشركاؤنا» section instead of an empty heading", () => {
    assert.match(src("features/home/components/Sponsors.tsx"), /if \(sponsors\.length === 0\) return null;/);
    assert.match(src("features/home/components/SponsorsClient.tsx"), /if \(!isLoading && sponsors\.length === 0\) return null;/);
  });
});

describe("F-DISC-2 — the splash overlay no longer remounts the page", () => {
  test("children keep one position whether the overlay is shown or not", () => {
    const splash = src("components/shared/SplashScreen.tsx");
    assert.doesNotMatch(splash, /<div>\{children\}<\/div>/);
    assert.doesNotMatch(splash, /if \(!show\)/);
    assert.match(splash, /\{show && <div/);
  });
});

describe("F-DISC-3 — list load failures are errors with a retry, not empty results", () => {
  test("the opportunity feed reports the failure and retries the same page", () => {
    const feed = src("features/opportunities/components/useOpportunitiesFeed.ts");
    assert.match(feed, /isError: isError && !isFetching/);
    assert.match(feed, /retry: \(\) => \{ void retryPage\(\); \}/);
    const card = src("features/opportunities/components/OpportunitiesListCard.tsx");
    assert.match(card, /hasNoOpportunities && isError \?/);
    assert.match(card, /hasMore=\{hasMore && !isError\}/);
  });

  test("the home and /opportunities carousels show the same notice", () => {
    assert.match(src("features/home/components/VolunteerCard.tsx"), /hasNoOpportunities && isError \?/);
    assert.match(src("features/home/components/useVolunteerCard.ts"), /const isError = isLearnServe \? learnServeError : volunteerError;/);
  });

  test("«طوارئ» is sent as is_emergency by every volunteer list", () => {
    const carousel = src("features/home/components/useVolunteerCard.ts");
    assert.match(carousel, /is_emergency: filters\?\.isUrgent \|\| undefined/);
    assert.doesNotMatch(carousel, /is_urgent:/);
  });
});

describe("F-DISC-4/6 — admin-managed homepage chrome hides when the CMS is empty", () => {
  test("no bundled hero artwork stands in for missing banners", () => {
    const carousel = src("features/home/components/BannerCarousel.tsx");
    assert.doesNotMatch(carousel, /baner_img|FALLBACK_IMAGE/);
    assert.match(carousel, /if \(slides\.length === 0\)/);
    for (const file of ["features/home/components/Banner.tsx", "features/home/components/HomepageBannerClient.tsx"]) {
      assert.match(src(file), /statistics=\{cms\?\.statistics \?\? null\}/);
    }
  });

  test("a social account cleared in the dashboard is not shown with a bundled URL", () => {
    const footer = src("components/layout/Footer.tsx");
    assert.doesNotMatch(footer, /DEFAULT_SOCIAL_URLS/);
    assert.match(footer, /\.filter\(\(link\) => link\.href !== ""\)/);
    assert.doesNotMatch(src("components/layout/footerLinks.ts"), /tiktok\.com|instagram\.com/);
  });
});

describe("F-DISC-7 — contact WhatsApp link (number or link)", () => {
  test("a local 8-digit number gets Kuwait's code", () => {
    assert.equal(contactWhatsAppHref("9999 1234"), "https://wa.me/96599991234");
  });
  test("an international number keeps its digits", () => {
    assert.equal(contactWhatsAppHref("+965 5555 1234"), "https://wa.me/96555551234");
  });
  test("a link keeps its address and gains a scheme when pasted without one", () => {
    assert.equal(contactWhatsAppHref("https://chat.whatsapp.com/abc"), "https://chat.whatsapp.com/abc");
    assert.equal(contactWhatsAppHref("wa.me/96599991234"), "https://wa.me/96599991234");
  });
  test("an empty value yields no link", () => {
    assert.equal(contactWhatsAppHref(null), "");
    assert.equal(contactWhatsAppHref("  "), "");
  });
});

describe("F-DISC-5 — admin-published CMS pages are linked from the footer", () => {
  const t = (key: string) => `t:${key}`;

  test("core pages keep their routes and take the CMS title, else the chrome label", () => {
    const links = footerPageLinks([{ slug: "about", title_en: "About Fursa", title_ar: "عن فرصة" }], "ar", t);
    assert.deepEqual(links.slice(0, 3), [
      { slug: "about", href: "/about-us", label: "عن فرصة" },
      { slug: "privacy", href: "/privacy-policy", label: "t:COMMON.PRIVACYPOLICY" },
      { slug: "terms", href: "/termsofuse", label: "t:COMMON.TERMS.OF.USE" },
    ]);
  });

  test("any other published page is appended under /pages/{slug}, untitled ones skipped", () => {
    const links = footerPageLinks([
      { slug: "terms", title_en: "Terms", title_ar: null },
      { slug: "refund-policy", title_en: "Refund policy", title_ar: "سياسة الاسترجاع" },
      { slug: "draft", title_en: null, title_ar: "  " },
    ], "en", t);
    assert.equal(links.length, 4);
    assert.deepEqual(links[3], { slug: "refund-policy", href: "/pages/refund-policy", label: "Refund policy" });
  });

  test("no CMS payload still links the three core pages", () => {
    assert.deepEqual(footerPageLinks(null, "en", t).map((link) => link.href), ["/about-us", "/privacy-policy", "/termsofuse"]);
  });
});

describe("F-DISC-10 — home event tiles use the pin label, never «Loading location...»", () => {
  test("HomeEventTile reads eventCardLocation (map_desc) like the event lists", () => {
    const tile = src("features/home/components/HomeEventTile.tsx");
    assert.match(tile, /eventCardLocation\(/);
    assert.doesNotMatch(tile, /LOADING_LOCATION/);
  });
});
