import assert from "node:assert/strict";
import { after, before, describe, it } from "node:test";
import type { Browser, Page } from "playwright";
import { ADMIN_EMAIL, ADMIN_PASSWORD, BASE, axeSource, launch, startServer, stopServer } from "./helpers";

let browser: Browser;
before(async () => {
  await startServer();
  browser = await launch();
}, { timeout: 180_000 });
after(async () => {
  await browser?.close();
  stopServer();
});

async function violations(page: Page) {
  await page.addScriptTag({ content: axeSource() });
  return page.evaluate(async () => {
    // @ts-expect-error axe est injecté dans la page
    const r = await axe.run(document, { runOnly: ["wcag2a", "wcag2aa"] });
    return r.violations.map((v: { id: string; nodes: { target: unknown[]; any: { data?: { fgColor?: string; bgColor?: string; contrastRatio?: number } }[] }[] }) => `${v.id} ×${v.nodes.length} ${JSON.stringify(v.nodes[0]?.target)} ${JSON.stringify(v.nodes[0]?.any[0]?.data ?? {})}`);
  });
}

async function login(page: Page) {
  await page.goto(BASE + "/admin/login");
  await page.fill("input[name=email]", ADMIN_EMAIL);
  await page.fill("input[name=password]", ADMIN_PASSWORD);
  await page.locator("form button").last().click();
  await Promise.race([
    page.waitForURL(/\/admin$/),
    page.waitForSelector("[role=alert]:not(#__next-route-announcer__)").then(async () => {
      throw new Error("Connexion refusée : " + (await page.locator("[role=alert]:not(#__next-route-announcer__)").first().textContent()));
    }),
  ]);
}

/** Une seule connexion pour toute la suite (la connexion est limitée en débit côté serveur). */
let adminState: Awaited<ReturnType<import("playwright").BrowserContext["storageState"]>> | null = null;
async function adminPage() {
  if (!adminState) {
    const ctx = await browser.newContext();
    await login(await ctx.newPage());
    adminState = await ctx.storageState();
    await ctx.close();
  }
  const ctx = await browser.newContext({ storageState: adminState });
  return { ctx, page: await ctx.newPage() };
}

describe("site public", () => {
  it("l'accueil s'affiche, sans violation d'accessibilité (clair puis sombre)", async () => {
    for (const scheme of ["light", "dark"] as const) {
      const ctx = await browser.newContext({ colorScheme: scheme, reducedMotion: "reduce" });
      const page = await ctx.newPage();
      await page.goto(BASE + "/", { waitUntil: "networkidle" });
      assert.ok((await page.locator("h1").count()) >= 1);
      assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), scheme);
      assert.deepEqual(await violations(page), [], `accessibilité (${scheme})`);
      await ctx.close();
    }
  });

  it("le mode sombre se bascule et se mémorise", async () => {
    const ctx = await browser.newContext({ colorScheme: "light" });
    const page = await ctx.newPage();
    await page.goto(BASE + "/", { waitUntil: "networkidle" });
    await page.click('button[aria-label="Mode sombre"]');
    assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), "dark");
    await page.reload({ waitUntil: "domcontentloaded" });
    // Posé avant l'affichage : pas d'éclair blanc.
    assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), "dark");
    await ctx.close();
  });

  it("l'article s'ouvre avec partage, confiance et sources", async () => {
    // Animations coupées : les contrastes sont mesurés sur l'état final, pas en plein fondu.
    const ctx = await browser.newContext({ reducedMotion: "reduce" });
    const page = await ctx.newPage();
    await page.goto(BASE + "/", { waitUntil: "networkidle" });
    const href = await page.locator('a[href^="/actualite/"]').first().getAttribute("href");
    assert.ok(href);
    await page.goto(BASE + href!, { waitUntil: "networkidle" });
    assert.ok((await page.locator("h1").textContent())?.length);
    assert.ok((await page.getByRole("button", { name: "Copier le lien" }).count()) === 1);
    assert.deepEqual(await violations(page), []);
    await ctx.close();
  });

  it("la recherche filtre, retire un filtre et refuse une saisie trop courte", async () => {
    const ctx = await browser.newContext();
    const page = await ctx.newPage();
    await page.goto(BASE + "/recherche?q=incendie&period=7j", { waitUntil: "networkidle" });
    assert.ok((await page.getByText("résultat(s)").count()) >= 1);
    await page.getByRole("link", { name: /Retirer le filtre 7 derniers jours/ }).click();
    await page.waitForURL((u) => !u.search.includes("period="));
    await page.goto(BASE + "/recherche?q=a", { waitUntil: "networkidle" });
    assert.ok((await page.getByText("au moins 2 caractères").count()) >= 1);
    await ctx.close();
  });

  it("la carte « En direct » charge sans erreur de script", async () => {
    const ctx = await browser.newContext();
    const page = await ctx.newPage();
    const errors: string[] = [];
    page.on("pageerror", (e) => errors.push(e.message));
    await page.goto(BASE + "/direct", { waitUntil: "networkidle" });
    assert.deepEqual(errors, []);
    await ctx.close();
  });

  it("une page inconnue renvoie un 404 lisible", async () => {
    const ctx = await browser.newContext();
    const page = await ctx.newPage();
    const r = await page.goto(BASE + "/cette-page-n-existe-pas");
    assert.equal(r?.status(), 404);
    assert.deepEqual(await violations(page), []);
    await ctx.close();
  });
});

describe("back-office", () => {
  it("l'accès est refusé sans connexion, accordé après connexion", async () => {
    const anon = await browser.newContext();
    const anonPage = await anon.newPage();
    await anonPage.goto(BASE + "/admin/articles");
    await anonPage.waitForURL(/\/admin\/login/);
    await anon.close();
    const { ctx, page } = await adminPage();
    for (const path of ["/admin/articles", "/admin/events", "/admin/doublons", "/admin/qualite", "/admin/sante", "/admin/newsletter"]) {
      const r = await page.goto(BASE + path, { waitUntil: "networkidle" });
      assert.equal(r?.status(), 200, path);
      assert.ok((await page.locator("h1").count()) >= 1, path);
    }
    await ctx.close();
  });

  it("un mauvais mot de passe est refusé", async () => {
    const ctx = await browser.newContext();
    const page = await ctx.newPage();
    await page.goto(BASE + "/admin/login");
    await page.fill("input[name=email]", "inconnu@example.fr");
    await page.fill("input[name=password]", "mauvais-mot-de-passe-123");
    await page.locator("form button").last().click();
    await page.waitForSelector("[role=alert]:not(#__next-route-announcer__)");
    assert.match(page.url(), /login/);
    await ctx.close();
  });
});

describe("page Le Récap du Jour", () => {
  it("préparation, recherche, publication puis page publique", async () => {
    const admin = await adminPage();
    await admin.page.goto(BASE + "/admin/newsletter", { waitUntil: "networkidle" });
    await Promise.all([admin.page.waitForURL(/\/admin\/newsletter\/.+/), admin.page.click('button:has-text("Préparer le récap du jour")')]);
    await admin.page.waitForLoadState("networkidle");
    const boxes = admin.page.locator("section[aria-labelledby=nl-candidates] input[type=checkbox]");
    await admin.page.selectOption("section[aria-labelledby=nl-candidates] select >> nth=1", "0");
    await admin.page.waitForLoadState("networkidle");
    assert.ok((await boxes.count()) > 0, "des articles à choisir");
    await boxes.nth(0).check();
    assert.equal(await admin.page.locator("button[value=publish]").isDisabled(), true, "la publication exige la confirmation explicite");
    await admin.page.check("input[name=confirm]");
    await admin.page.click("button[value=publish]");
    await admin.page.waitForSelector("[role=status]");

    const ctx = await browser.newContext();
    const page = await ctx.newPage();
    await page.goto(BASE + "/recap", { waitUntil: "networkidle" });
    assert.ok((await page.locator("ol li").count()) > 0, "le récap publié apparaît sur /recap");
    assert.equal(await page.locator("input[name=email]").count(), 0, "plus de formulaire d'inscription");
    await ctx.close();
    await admin.ctx.close();
  });
});
