/**
 * Closure review (8 Nov 2026, afternoon) — Accounts / UI area regressions.
 *
 * Pure logic is exercised directly; wiring inside `.tsx` files that this
 * runner cannot mount is pinned by reading the source, stated as such.
 */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, test } from "node:test";

import { sessionFlagsUpdate } from "@/features/auth/sessionFlags";
import { isValidKuwaitiIban, normalizeIban } from "@/features/trainer/trainerRequest";

const src = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");
const locale = (lng: "ar" | "en") =>
  JSON.parse(readFileSync(new URL(`../locales/${lng}/translation.json`, import.meta.url), "utf8")) as Record<string, string>;

describe("C-ACC-1 directory «View more» is translated in Arabic", () => {
  test("COMMON.VIEW_MORE exists in both locales", () => {
    assert.equal(locale("ar")["COMMON.VIEW_MORE"], "عرض المزيد");
    assert.ok(locale("en")["COMMON.VIEW_MORE"]);
  });
});

describe("C-ACC-2 session flags never copied from another account's /account/", () => {
  const user = { id: 7, is_trainer: false, trainer_types: [], is_publishing_paused: false };

  test("a cached response for another account is ignored", () => {
    assert.equal(sessionFlagsUpdate(user as never, { id: 9, is_trainer: true, is_publishing_paused: true }), null);
  });

  test("the signed-in account's own response still updates the session", () => {
    assert.deepEqual(sessionFlagsUpdate(user as never, { id: 7, is_trainer: true }), { is_trainer: true });
    // ids may arrive as strings after digit normalization
    assert.deepEqual(sessionFlagsUpdate(user as never, { id: "7", is_publishing_paused: true }), { is_publishing_paused: true });
  });
});

describe("C-ACC-3 IBAN typed with Arabic-Indic digits", () => {
  const western = "KW81CBKU0000000000001234560101";
  const arabic = western.replace(/\d/g, (d) => "٠١٢٣٤٥٦٧٨٩"[Number(d)]);

  test("normalizes to ASCII digits, which is what the API validates", () => {
    assert.equal(normalizeIban(` ${arabic.toLowerCase()} `), western);
  });

  test("validity does not depend on the keyboard's digits", () => {
    assert.equal(isValidKuwaitiIban(western), true);
    assert.equal(isValidKuwaitiIban(arabic), true);
  });
});

describe("C-ACC-4 achievements load failure shows the error alone (source pin)", () => {
  test("returns the notice before the counters, charts and boards render", () => {
    const code = src("features/achievements/components/Achievements.tsx");
    const early = code.indexOf("if (loadError != null)");
    assert.ok(early > 0);
    assert.ok(early < code.indexOf("<DonutChart"));
  });
});
