import { expect, test } from '@playwright/test';
import { expectNoA11yViolations } from './support/axe';
import { gotoExpecting, KEY_PAGES } from './support/portal';

/**
 * @intent História 04 — axe/WCAG nas telas-chave (`histories/04-axe-wcag.md`).
 */

test.describe('História 04 — Axe (WCAG A/AA) nas telas-chave', () => {
  for (const keyPage of KEY_PAGES) {
    test(`axe sem violações — ${keyPage.name}`, async ({ page }) => {
      await gotoExpecting(page, keyPage.path, keyPage.status);
      await expectNoA11yViolations(page);
    });
  }

  test('hierarquia de cabeçalhos sem saltos em todas as telas-chave', async ({ page }) => {
    for (const keyPage of KEY_PAGES) {
      await gotoExpecting(page, keyPage.path, keyPage.status);

      const levels = await page.evaluate(() =>
        Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6')).map((heading) =>
          Number.parseInt(heading.tagName.slice(1), 10),
        ),
      );

      expect(levels.filter((level) => level === 1).length, `um <h1> em ${keyPage.path}`).toBe(1);
      expect(levels[0], `o primeiro cabeçalho é <h1> em ${keyPage.path}`).toBe(1);

      for (let index = 1; index < levels.length; index += 1) {
        expect(
          (levels[index] ?? 1) - (levels[index - 1] ?? 1),
          `salto de nível em ${keyPage.path}: ${levels.join(' → ')}`,
        ).toBeLessThanOrEqual(1);
      }
    }
  });

  test('landmarks presentes e <main> único', async ({ page }) => {
    for (const keyPage of KEY_PAGES) {
      await gotoExpecting(page, keyPage.path, keyPage.status);

      await expect(page.locator('header.site-header')).toHaveCount(1);
      await expect(page.locator('main')).toHaveCount(1);
      await expect(page.locator('footer')).toHaveCount(1);
      await expect(page.locator('nav')).not.toHaveCount(0);
    }
  });

  test('toda imagem tem alt e o documento tem lang/título', async ({ page }) => {
    for (const keyPage of KEY_PAGES) {
      await gotoExpecting(page, keyPage.path, keyPage.status);

      const imagesWithoutAlt = await page.evaluate(() =>
        Array.from(document.querySelectorAll('img'))
          .filter((image) => !image.hasAttribute('alt'))
          .map((image) => image.getAttribute('src') ?? '(sem src)'),
      );

      expect(imagesWithoutAlt, `imagens sem alt em ${keyPage.path}`).toEqual([]);
      await expect(page.locator('html')).toHaveAttribute('lang', 'pt-BR');
      expect((await page.title()).trim().length).toBeGreaterThan(0);
    }
  });
});
