/**
 * Étape 3 : annuaire, fiches, vérification, journal public, pages institutionnelles.
 * Le build e2e utilise TOUJOURS les données fictives (mode « e2e », voir src/lib/donnees.ts).
 */
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';

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

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 ouvrir(page: Page, chemin: string) {
  const reponse = await page.goto(chemin);
  // Les îlots React sont hydratés quand Astro retire l'attribut « ssr ».
  await page.waitForFunction(() => !document.querySelector('astro-island[ssr]'));
  return reponse;
}

/** Aucune requête vers les serveurs de tuiles pendant les tests : on sert une image vide. */
async function tuilesHorsLigne(page: Page) {
  await page.route('https://tile.openstreetmap.org/**', (route) =>
    route.fulfill({ status: 204, body: '' }),
  );
}

const PAGES = [
  '/',
  '/en/',
  '/annuaire',
  '/en/annuaire',
  '/annuaire/traore-seydou',
  '/en/annuaire/kone-aminata',
  '/verifier/notaire/traore-seydou',
  '/verifier/notaire/kone-aminata',
  '/en/verifier/notaire/dosso-lacina',
  '/journal',
  '/en/journal',
  '/faq',
  '/en/faq',
  '/mentions-legales',
  '/confidentialite',
  '/accessibilite',
  '/contact',
  '/en/contact',
  '/page-inexistante',
];

test.describe('toutes les pages', () => {
  for (const chemin of PAGES) {
    for (const preference of ['light', 'dark'] as const) {
      test(`${chemin} (${preference}) : stylée et sans violation axe`, async ({ page }) => {
        await page.emulateMedia({ colorScheme: preference });
        await ouvrir(page, chemin);
        // Régression Astro 7.4 / Vite 8 : la feuille de style partagée n'était plus liée.
        await expect(page.locator('header').first()).toHaveCSS(
          'background-color',
          'rgb(15, 61, 46)',
        );
        expect(await violationsAxe(page)).toEqual([]);
      });
    }
  }

  test('la page inexistante répond 404, en français et en anglais', async ({ page }) => {
    const reponse = await page.goto('/verifier/notaire/notaire-inconnu');
    expect(reponse?.status()).toBe(404);
    await expect(page.getByRole('heading', { level: 1 })).toHaveText('Page introuvable');
    await expect(page.getByRole('heading', { level: 2, name: 'Page not found' })).toBeVisible();
  });

  test('le lien de langue mène à la page équivalente', async ({ page }) => {
    await page.goto('/annuaire/kone-aminata');
    await page.getByRole('link', { name: 'Read this page in English' }).click();
    await expect(page).toHaveURL(/\/en\/annuaire\/kone-aminata\/?$/);
    await expect(page.locator('html')).toHaveAttribute('lang', 'en');
    await page.getByRole('link', { name: 'Lire cette page en français' }).click();
    await expect(page).toHaveURL(/\/annuaire\/kone-aminata\/?$/);
  });

  test('le bandeau « Démonstration » signale les données fictives', async ({ page }) => {
    await page.goto('/');
    await expect(page.locator('[data-donnees-fictives]')).toHaveText(
      'Démonstration : toutes les données affichées sont fictives.',
    );
  });
});

test.describe('annuaire', () => {
  test('sans JavaScript : liste complète, groupée par ville', async ({ browser }) => {
    const contexte = await browser.newContext({ javaScriptEnabled: false });
    const page = await contexte.newPage();
    await page.goto('/annuaire');
    await expect(page.locator('main li a[href^="/annuaire/"]')).toHaveCount(30);
    await expect(page.getByRole('heading', { level: 2, name: 'Bouaké' })).toBeVisible();
    await expect(page.getByRole('navigation', { name: 'Aller à une ville' })).toBeVisible();
    // Aucune commande inutilisable sans JavaScript.
    await expect(page.getByRole('searchbox')).toHaveCount(0);
    await expect(page.getByRole('button', { name: 'Afficher la carte des études' })).toHaveCount(0);
    await contexte.close();
  });

  test('recherche instantanée, tolérante aux accents et aux fautes de frappe', async ({ page }) => {
    await ouvrir(page, '/annuaire');
    const recherche = page.getByRole('searchbox', { name: 'Rechercher un notaire' });
    const statut = page.getByRole('status').filter({ hasText: 'Résultats' });

    await recherche.fill('kone');
    await expect(statut).toHaveText('Résultats : 1');
    await expect(page.locator('main li a').first()).toHaveText('Maître Aminata Koné');

    await recherche.fill('kouasi');
    await expect(page.getByRole('link', { name: 'Maître Yao Désiré Kouassi' })).toBeVisible();

    await recherche.fill('');
    await page.getByRole('combobox', { name: 'Ville' }).selectOption('Bouaké');
    await expect(statut).toHaveText('Résultats : 2');

    await page.getByRole('combobox', { name: 'Statut' }).selectOption('suspendu');
    await expect(statut).toHaveText('Résultats : 0');
    await expect(page.getByText('Aucun notaire ne correspond à votre recherche.')).toBeVisible();

    await page.getByRole('button', { name: 'Effacer la recherche' }).click();
    await expect(page.locator('main li a[href^="/annuaire/"]')).toHaveCount(30);
    expect(await violationsAxe(page)).toEqual([]);
  });

  test('carte : chargée seulement à la demande, une étude par point', async ({ page }) => {
    await tuilesHorsLigne(page);
    const scripts: string[] = [];
    page.on('request', (requete) => {
      if (requete.resourceType() === 'script') scripts.push(requete.url());
    });
    await ouvrir(page, '/annuaire');
    expect(scripts.some((url) => url.includes('leaflet'))).toBe(false);

    const bouton = page.getByRole('button', { name: 'Afficher la carte des études' });
    await bouton.click();
    await expect(page.locator('.leaflet-container')).toBeVisible();
    await expect(page.locator('path.leaflet-interactive')).toHaveCount(16);
    expect(scripts.some((url) => url.includes('leaflet'))).toBe(true);

    await page.locator('path.leaflet-interactive').first().click({ force: true });
    await expect(page.locator('.leaflet-popup-content a').first()).toBeVisible();
    expect(await violationsAxe(page)).toEqual([]);

    await page.getByRole('button', { name: 'Masquer la carte' }).click();
    await expect(page.locator('.leaflet-container')).toHaveCount(0);
  });
});

test.describe('fiche d’un notaire', () => {
  test('statut accordé, détenteur des minutes, définition sans JavaScript', async ({ browser }) => {
    const contexte = await browser.newContext({ javaScriptEnabled: false });
    const page = await contexte.newPage();
    await page.goto('/annuaire/traore-seydou');
    await expect(page.getByRole('heading', { level: 1 })).toHaveText('Maître Seydou Traoré');
    await expect(page.getByText('Suspendu', { exact: true })).toBeVisible();
    await expect(page.getByText('Ne peut pas recevoir d’actes.')).toHaveCount(0);
    await expect(page.getByText("Ne peut pas recevoir d'actes.")).toBeVisible();

    const terme = page.locator('summary', { hasText: 'minutes' });
    await terme.click();
    await expect(page.getByText('Les minutes sont les originaux des actes')).toBeVisible();

    await page.getByRole('link', { name: 'Maître Akissi Christelle N’Guessan' }).click();
    await expect(page.getByRole('heading', { level: 1 })).toHaveText(
      'Maître Akissi Christelle N’Guessan',
    );
    await contexte.close();
  });

  test('le libellé s’accorde au féminin (Q-011)', async ({ page }) => {
    await page.goto('/annuaire/ahoua-marie-laure');
    await expect(page.getByText('Suspendue', { exact: true })).toBeVisible();
  });

  test('QR code de vérification nommé, et lien équivalent', async ({ page }) => {
    await page.goto('/annuaire/kone-aminata');
    await expect(
      page.getByRole('img', { name: 'QR code de vérification de Aminata Koné' }),
    ).toBeVisible();
    await expect(
      page.getByRole('link', { name: 'Ouvrir la page de vérification' }),
    ).toHaveAttribute('href', '/verifier/notaire/kone-aminata');
  });
});

test.describe('vérification d’un notaire (QR)', () => {
  for (const [slug, resultat, message] of [
    ['kone-aminata', 'valide', 'En exercice : peut recevoir vos actes.'],
    ['traore-seydou', 'revoque', "Suspendu : ne peut pas recevoir d'actes."],
    ['seri-zadi-patrice', 'revoque', "Destitué : ne peut pas recevoir d'actes."],
    ['dosso-lacina', 'neutre', "Nommé, pas encore installé : ne peut pas recevoir d'actes."],
    ['diallo-mamadou', 'neutre', "Décédé : ne peut pas recevoir d'actes."],
  ] as const) {
    test(`${slug} : ${resultat}, lisible sans JavaScript`, async ({ browser }) => {
      const contexte = await browser.newContext({ javaScriptEnabled: false });
      const page = await contexte.newPage();
      await page.goto(`/verifier/notaire/${slug}`);
      const panneau = page.locator(`[data-resultat="${resultat}"]`);
      await expect(panneau.getByRole('heading', { level: 2 })).toHaveText(message);
      await expect(page.getByText(/^Information à jour au /)).toBeVisible();
      await contexte.close();
    });
  }

  test('le détenteur des minutes est indiqué', async ({ page }) => {
    await ouvrir(page, '/verifier/notaire/diallo-mamadou');
    await expect(page.getByRole('link', { name: 'Maître Jean-Marc Loukou' })).toBeVisible();
  });
});

test.describe('journal public', () => {
  test('montre les entrées publiées, jamais les brouillons', async ({ page }) => {
    await page.goto('/journal');
    await expect(page.locator('main article')).toHaveCount(3);
    await expect(page.getByText(/brouillon/i)).toHaveCount(0);
    await expect(
      page.getByRole('heading', { level: 2, name: 'Suspension de Maître Seydou Traoré' }),
    ).toBeVisible();
  });

  test('en anglais : version du bureau si elle existe, sinon le texte français (Q-016)', async ({
    page,
  }) => {
    await page.goto('/en/journal');
    const avis = page.locator('main article');
    await expect(avis.filter({ hasText: 'Always check a notary before signing' })).toHaveAttribute(
      'lang',
      'en',
    );
    await expect(
      avis.filter({ hasText: 'Destitution de Maître Zadi Patrice Séri' }),
    ).toHaveAttribute('lang', 'fr');
    await expect(page.getByText('the notice is shown in French')).toBeVisible();
  });
});

test.describe('décisions du 2026-11-26', () => {
  test('la fiche indique la forme d’exercice et la section (Q-015)', async ({ page }) => {
    await page.goto('/annuaire/traore-seydou');
    await expect(page.getByText('Société civile professionnelle (SCP)')).toBeVisible();
    await expect(page.getByText('Section d’Abidjan (démonstration)')).toBeVisible();
  });

  test('les informations de la Chambre sont paramétrables, « à compléter » sinon (Q-014)', async ({
    page,
  }) => {
    await page.goto('/contact');
    const bloc = page.getByRole('region', { name: "Chambre des Notaires de Côte d'Ivoire" });
    await expect(bloc.getByText('Téléphone')).toBeVisible();
    await expect(bloc.getByText('À compléter par la Chambre')).toHaveCount(5);
    await page.goto('/mentions-legales');
    await expect(page.getByText('Directeur de la publication')).toBeVisible();
  });

  test('la tête du registre VérifActe est publique (Q-019)', async ({ page }) => {
    await page.goto('/verifier');
    await expect(page.locator('[data-tete-registre]')).toHaveText(/^[0-9a-f]{64}$/);
    await expect(page.getByText(/Le registre compte 4 lignes/)).toBeVisible();
  });
});

test.describe('FAQ', () => {
  test('définit les 9 statuts et les minutes', async ({ page }) => {
    await page.goto('/faq');
    await expect(page.locator('#statuts dd')).toHaveCount(9);
    await expect(page.locator('#minutes')).toContainText('originaux des actes');
  });
});

test.describe('budgets de poids (3G)', () => {
  for (const chemin of ['/annuaire', '/verifier/notaire/kone-aminata', '/annuaire/kone-aminata']) {
    test(`${chemin} transfère moins de 300 Ko`, async ({ page }) => {
      await tuilesHorsLigne(page);
      const mesures: Promise<number>[] = [];
      page.on('requestfinished', (requete) => {
        mesures.push(
          requete.sizes().then((tailles) => tailles.responseBodySize + tailles.responseHeadersSize),
        );
      });
      await page.goto(chemin, { waitUntil: 'networkidle' });
      const total = (await Promise.all(mesures)).reduce((somme, taille) => somme + taille, 0);
      expect(total, `${(total / KO).toFixed(1)} Ko`).toBeLessThan(300 * KO);
    });
  }

  test('la fiche d’un notaire ne charge aucun script', async ({ page }) => {
    const scripts: string[] = [];
    page.on('request', (requete) => {
      if (requete.resourceType() === 'script') scripts.push(requete.url());
    });
    await page.goto('/annuaire/kone-aminata', { waitUntil: 'networkidle' });
    expect(scripts).toEqual([]);
  });
});
