import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';

const NORMES_WCAG = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];

async function violationsAxe(page: Page) {
  const resultat = await new AxeBuilder({ page }).withTags(NORMES_WCAG).analyze();
  return resultat.violations.map((violation) => ({
    regle: violation.id,
    elements: violation.nodes.map((noeud) => noeud.target.join(' ')),
  }));
}

async function ouvrirDemoHydratee(page: Page) {
  await page.goto('/demo');
  // L'îlot React est hydraté quand Astro retire l'attribut « ssr ».
  await page.waitForFunction(() => !document.querySelector('astro-island[ssr]'));
}

test.describe('page /demo du design system', () => {
  for (const preference of ['light', 'dark'] as const) {
    test(`aucune violation axe WCAG 2.1 AA (préférence système : ${preference})`, async ({
      page,
    }) => {
      await page.emulateMedia({ colorScheme: preference });
      await ouvrirDemoHydratee(page);
      expect(await violationsAxe(page)).toEqual([]);
    });
  }

  test('affiche les deux thèmes', async ({ page }) => {
    await page.goto('/demo');
    await expect(page.getByRole('heading', { level: 2, name: 'Thème clair' })).toBeVisible();
    await expect(page.getByRole('heading', { level: 2, name: 'Thème sombre' })).toBeVisible();
  });

  test('fenêtre modale : ouverture au clavier, Échap, retour du focus, aucune violation axe', async ({
    page,
  }) => {
    await ouvrirDemoHydratee(page);
    const panneau = page.locator('[data-theme="sombre"]');
    const bouton = panneau.getByRole('button', { name: 'Ouvrir la fenêtre' });

    await bouton.focus();
    await page.keyboard.press('Enter');
    const dialogue = page.getByRole('dialog', { name: 'Fenêtre de démonstration' });
    await expect(dialogue).toBeVisible();
    expect(await violationsAxe(page)).toEqual([]);

    await page.keyboard.press('Escape');
    await expect(dialogue).toBeHidden();
    await expect(bouton).toBeFocused();
  });

  test('infobulle : visible au focus, fermée par Échap, définition reliée au terme', async ({
    page,
  }) => {
    await ouvrirDemoHydratee(page);
    const terme = page.locator('[data-theme="clair"]').getByRole('button', { name: 'authentique' });

    await terme.focus();
    const infobulle = page.locator('[data-theme="clair"]').getByRole('tooltip');
    await expect(infobulle).toBeVisible();
    await expect(terme).toHaveAccessibleDescription(/Définition de démonstration/);

    await page.keyboard.press('Escape');
    await expect(infobulle).toBeHidden();
  });

  test('notification : annoncée dans une zone « status », puis fermable', async ({ page }) => {
    await ouvrirDemoHydratee(page);
    await page
      .locator('[data-theme="clair"]')
      .getByRole('button', { name: 'Afficher une notification' })
      .click();

    const zone = page.getByRole('region', { name: 'Notifications' }).getByRole('status');
    await expect(zone).toContainText('Notification de démonstration.');
    // Une notification affichée ne doit créer aucune violation (régression : liste dans la zone vivante).
    expect(await violationsAxe(page)).toEqual([]);
    await zone.getByRole('button', { name: 'Fermer' }).click();
    await expect(zone).not.toContainText('Notification de démonstration.');
  });

  test('toutes les cibles interactives mesurent au moins 44 × 44 px', async ({ page }) => {
    await ouvrirDemoHydratee(page);
    const cibles = page.locator('main button:visible, main select:visible, main input:visible');
    const tropPetites: string[] = [];
    for (const cible of await cibles.all()) {
      const boite = await cible.boundingBox();
      // Exception WCAG 2.5.8 : un terme d'infobulle dans une phrase (cible « en ligne »).
      const enLigne =
        (await cible.getAttribute('aria-expanded')) !== null &&
        (await cible.getAttribute('aria-describedby')) !== null;
      if (boite && !enLigne && (boite.height < 44 || boite.width < 44)) {
        tropPetites.push(`${(await cible.textContent()) ?? ''} ${boite.width}×${boite.height}`);
      }
    }
    expect(tropPetites).toEqual([]);
  });
});
