/**
 * Étape 4 : simulateur de frais (barèmes FICTIFS du build e2e).
 * Valeurs attendues vérifiées à la main dans packages/simulateur/src/simulateur.test.ts.
 */
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';

const KO = 1024;

async function ouvrir(page: Page, chemin: string) {
  await page.goto(chemin);
  await page.waitForFunction(() => !document.querySelector('astro-island[ssr]'));
}

async function violationsAxe(page: Page) {
  const resultat = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
    .analyze();
  return resultat.violations.map((v) => ({ regle: v.id, elements: v.nodes.map((n) => n.target) }));
}

test.describe('simulateur de frais', () => {
  for (const chemin of ['/simulateur', '/en/simulateur']) {
    for (const preference of ['light', 'dark'] as const) {
      test(`${chemin} (${preference}) : aucune violation axe, avec un résultat affiché`, async ({
        page,
      }) => {
        await page.emulateMedia({ colorScheme: preference });
        await ouvrir(page, chemin);
        await page.getByRole('textbox').fill('25000000');
        await expect(page.getByRole('table').first()).toBeVisible();
        expect(await violationsAxe(page)).toEqual([]);
      });
    }
  }

  test('calcule en direct, par catégorie, et annonce le total', async ({ page }) => {
    await ouvrir(page, '/simulateur');
    await expect(page.locator('[data-bareme-fictif]')).toBeVisible();
    await page.getByRole('textbox', { name: 'Prix de vente, en francs CFA' }).fill('25 000 000');

    await expect(
      page.getByRole('heading', { level: 2, name: /^Estimation pour 25/ }),
    ).toBeVisible();
    await expect(page.getByRole('status').filter({ hasText: 'Total estimé' })).toHaveText(
      /^Total estimé : 2\s100\s000\sF\sCFA$/,
    );
    const tableau = page.getByRole('table').first();
    await expect(
      tableau.getByRole('row', { name: /Rémunération du notaire \(fictive\)/ }),
    ).toContainText(/750\s000/);
    await expect(tableau.getByRole('row', { name: /Total estimé/ })).toContainText(/2\s100\s000/);
  });

  test('changement de barème, minimum et maximum signalés', async ({ page }) => {
    await ouvrir(page, '/simulateur');
    await page.getByRole('combobox', { name: "Type d'acte" }).selectOption('constitution-societe');
    const montant = page.getByRole('textbox', { name: 'Capital social, en francs CFA' });

    await montant.fill('600000000');
    await expect(page.getByText('(maximum appliqué)')).toBeVisible();
    await montant.fill('100000');
    await expect(page.getByText('(minimum appliqué)')).toBeVisible();
  });

  test('saisie invalide : message d’erreur relié au champ, aucun résultat', async ({ page }) => {
    await ouvrir(page, '/simulateur');
    const champ = page.getByRole('textbox', { name: 'Prix de vente, en francs CFA' });
    await champ.fill('12,5 millions');
    await expect(champ).toHaveAttribute('aria-invalid', 'true');
    await expect(champ).toHaveAccessibleDescription(/Saisissez un montant en chiffres/);
    await expect(page.getByRole('table')).toHaveCount(0);
  });

  test('sans JavaScript : détail des barèmes et exemples chiffrés', async ({ browser }) => {
    const contexte = await browser.newContext({ javaScriptEnabled: false });
    const page = await contexte.newPage();
    await page.goto('/simulateur');
    await expect(page.getByRole('textbox')).toHaveCount(0);
    await page.getByText('Détail du barème : Vente immobilière (barème FICTIF)').click();
    const exemples = page.getByRole('table', { name: /Exemples chiffrés : Vente immobilière/ });
    await expect(exemples.getByRole('row', { name: /Total estimé/ })).toContainText(/2\s100\s000/);
    await expect(page.getByText('au-delà de 50 000 000 F CFA').first()).toBeVisible();
    await contexte.close();
  });

  test('la page transfère moins de 300 Ko', async ({ page }) => {
    const mesures: Promise<number>[] = [];
    page.on('requestfinished', (requete) => {
      mesures.push(requete.sizes().then((t) => t.responseBodySize + t.responseHeadersSize));
    });
    await page.goto('/simulateur', { waitUntil: 'networkidle' });
    const total = (await Promise.all(mesures)).reduce((s, n) => s + n, 0);
    expect(total, `${(total / KO).toFixed(1)} Ko`).toBeLessThan(300 * KO);
  });
});
