import { expect, test } from '@playwright/test';
import { expectNoA11yViolations } from './support/axe';
import { signIn } from './support/cms';
import { clearDraftSections } from './support/home';

/**
 * História 26 — Publicação e prévia autenticada da home (P5.S2.2, emenda ADR-016).
 *
 * O spec cria o próprio documento: limpa as seções do rascunho, adiciona um `hero` com título
 * único (pt_BR + en), publica e confere o portal e a prévia no shell real. Publicar a home é
 * **estado global**, então o arquivo roda no projeto `cms-serial` (um worker, antes dos demais).
 * O axe mobile é medido no mesmo teste via `setViewportSize`, sem um segundo projeto concorrente.
 */

/** Portal público: a base do `BASE_URL` (o painel vive em `cms.<base>`). */
function portal(path: string): string {
  return new URL(path, process.env.BASE_URL ?? 'http://localhost:50700').toString();
}

test.describe('CMS — publicação e prévia da home', () => {
  test('publica o rascunho, invalida a home e abre a prévia autenticada por locale', async ({
    page,
  }) => {
    const marker = `Home e2e ${Date.now()}`;
    const english = `E2E home ${Date.now()}`;

    await signIn(page);
    await page.goto('/home');
    await expect(page.getByRole('heading', { level: 1, name: 'Editor da home' })).toBeVisible();

    await clearDraftSections(page);

    // Composição própria: um hero com título traduzido (a seção nova só persiste no salvar).
    await page.goto('/home?novo=hero');

    const pending = page.getByRole('region', { name: 'Nova seção (ainda não salva)' });
    await pending.getByRole('button', { name: 'Editar seção' }).click();

    const dialog = page.getByRole('dialog');
    await expect(dialog).toBeVisible();

    const titleGroup = dialog.getByRole('group', { name: 'Título' });
    await titleGroup.getByLabel('Português (Brasil)').fill(marker);
    await titleGroup.getByLabel('English').fill(english);

    const close = dialog.getByRole('button', { name: 'Concluir edição' });
    await close.scrollIntoViewIfNeeded();
    await close.click();
    await expect(dialog).not.toBeVisible();

    await page.getByRole('button', { name: 'Salvar rascunho' }).click();
    await expect(page.getByText('Rascunho salvo.')).toBeVisible();

    // Publicar exige `home.aprovar` (semente demo tem o conjunto completo).
    await page.getByRole('button', { name: 'Publicar home' }).click();
    await expect(page.getByText(/Home publicada \(versão \d+\)\./)).toBeVisible();

    // Prévia autenticada: mesmo conteúdo, shell do portal, por locale, com noindex.
    const previewLinks = page.getByRole('region', { name: 'Prévia autenticada (shell do portal)' });
    const [previewResponse] = await Promise.all([
      page.waitForResponse(
        (response) =>
          response.url().includes('/home/preview?locale=pt_BR') &&
          response.request().method() === 'GET',
      ),
      previewLinks.getByRole('link', { name: 'Português (Brasil)' }).click(),
    ]);

    expect(previewResponse?.status()).toBe(200);
    expect(previewResponse?.headers()['x-robots-tag'] ?? '').toContain('noindex');
    expect(previewResponse?.headers()['x-robots-tag'] ?? '').toContain('nofollow');

    await expect(page).toHaveURL(/\/home\/preview\?locale=pt_BR$/);
    await expect(page.locator('main#main-content h1')).toHaveText(marker);
    await expect(page.locator('main#main-content h1')).toHaveCount(1);
    await expect(page.locator('link[rel="canonical"]')).toHaveCount(0);
    await expectNoA11yViolations(page);

    // Mesma página no viewport mobile (alvos/contraste sob pointer grosso são cobertos por 16/22).
    await page.setViewportSize({ width: 390, height: 844 });
    await expectNoA11yViolations(page);

    // Portal público: a publicação aparece imediatamente, inclusive traduzida.
    const home = await page.goto(portal('/'), { waitUntil: 'load' });
    expect(home?.status()).toBe(200);
    await expect(page.locator('main#main-content h1')).toHaveText(marker);
    await expectNoA11yViolations(page);

    await page.goto(portal('/en'), { waitUntil: 'load' });
    await expect(page.locator('main#main-content h1')).toHaveText(english);
    await expect(page.locator('link[rel="canonical"]')).toHaveAttribute(
      'href',
      portal('/en'),
    );
    await expect(page.locator('link[rel="alternate"][hreflang="pt-BR"]')).toHaveCount(1);
  });
});
