/**
 * Full audit (8 Nov 2026), Discovery2: shared policy/record helpers, data
 * constants, organizer contact links, register-now and the home community
 * section. Regression tests for SC/cov/discovery2.md (F-DISC2-n).
 */
import { test, describe, afterEach } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { isEventCard, isOpportunityCard } from "@/features/opportunities/opportunityRecord";
import { opportunityNationalityLabel } from "@/data/Constants";
import { formatHoursMinutes, parseHoursInput } from "@/features/shared/clientReviewPolicy";
import { fetchCoordinates } from "@/lib/helpers";

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

describe("F-DISC2-1 — event rows of the mixed list are recognised", () => {
  test("WebsiteEventResource rows carry opportunity_type 'event' and are events", () => {
    const rows = [
      { id: 1, opportunity_type: "event" },
      { id: 2, opportunity_type: "volunteer_opportunity" },
      { id: 3, opportunity_type: "learn_serve_opportunity" },
      { id: 4 },
    ] as Array<{ id: number; opportunity_type?: string }>;
    assert.deepEqual(rows.filter(isEventCard).map((r) => r.id), [1, 4]);
    assert.deepEqual(rows.filter(isOpportunityCard).map((r) => r.id), [2, 3]);
  });
});

describe("F-DISC2-2 — a saved retired audience is not labelled «الكل»", () => {
  test("non_arabic reads as its own audience in both languages", () => {
    assert.equal(opportunityNationalityLabel("non_arabic", "ar"), "غير ناطق بالعربية");
    assert.equal(opportunityNationalityLabel("non_arabic", "en"), "Non-Arabic speakers");
    assert.equal(opportunityNationalityLabel("kuwaitis", "ar"), "كويتي فقط");
    assert.equal(opportunityNationalityLabel(null, "ar"), "الكل");
  });
});

describe("F-DISC2-3 — WhatsApp hrefs on the development detail and «تم تسجيلك»", () => {
  test("organizer links normalise the opportunity and profile WhatsApp (number or scheme-less link)", () => {
    const links = src("features/opportunities/components/OrganizerContactLinks.tsx");
    assert.match(links, /href=\{contactWhatsAppHref\(opportunityData\.whatsapp_link\)\}/);
    assert.match(links, /key === "whatsapp_link" \? contactWhatsAppHref\(raw\) : raw/);
    assert.doesNotMatch(links, /toWhatsAppLink/);
    assert.match(src("features/opportunities/components/RegisterNow.tsx"), /contactWhatsAppHref\(details\.whatsapp_link\)/);
  });
});

describe("F-DISC2-4 — forward geocoding can place an address outside Kuwait", () => {
  const realFetch = globalThis.fetch;
  afterEach(() => { globalThis.fetch = realFetch; });

  test("Kuwait first, then a worldwide search", async () => {
    const urls: string[] = [];
    globalThis.fetch = (async (url: string) => {
      urls.push(url);
      const body = url.includes("countrycodes=kw") ? [] : [{ lat: "51.48", lon: "-0.16" }];
      return { json: async () => body } as Response;
    }) as typeof fetch;
    assert.deepEqual(await fetchCoordinates("Battersea Park London"), { lat: 51.48, lng: -0.16 });
    assert.equal(urls.length, 2);
    assert.match(urls[0], /countrycodes=kw/);
    assert.doesNotMatch(urls[1], /countrycodes/);
  });

  test("a Kuwaiti hit is used without a second request", async () => {
    let calls = 0;
    globalThis.fetch = (async () => {
      calls += 1;
      return { json: async () => [{ lat: "29.3", lon: "48.0" }] } as Response;
    }) as typeof fetch;
    assert.deepEqual(await fetchCoordinates("Salmiya"), { lat: 29.3, lng: 48 });
    assert.equal(calls, 1);
  });
});

describe("F-DISC2-5 — home community section reports a failed load", () => {
  test("an error renders QueryErrorNotice with retry instead of «لا توجد منشورات»", () => {
    const section = src("features/home/components/VolunteerContributions.tsx");
    assert.match(section, /isError && !postsData \?/);
    assert.match(section, /<QueryErrorNotice error=\{error\} onRetry=/);
  });
});

describe("F-DISC2-6 — H:MM helpers accept the Arabic decimal separator", () => {
  test("formatHoursMinutes and parseHoursInput", () => {
    assert.equal(formatHoursMinutes("٢٫٥"), "2:30");
    assert.equal(formatHoursMinutes("١٠"), "10:00");
    assert.equal(formatHoursMinutes(null), "0:00");
    assert.equal(formatHoursMinutes(""), "0:00");
    assert.equal(parseHoursInput("١٫٥"), 1.5);
    assert.equal(parseHoursInput("٢:٣٠"), 2.5);
    assert.equal(parseHoursInput("25:00"), null);
  });
});
