import { test, expect } from '@playwright/test';
import { BASE_URL, USER, loginAs } from '../helpers';

// Custom error pages (templates/bundles/TwigBundle/Exception): in prod a 404 /
// 500 / 403 shows our branded page instead of Symfony's. In dev the debug page
// still shows for real errors, so these use the dev-only preview routes
// /_error/{code}, which render exactly what prod would.

const CASES = [
    { code: 404, tab: 'Page not found', title: "We can't find that page", message: 'the link is no longer working' },
    { code: 500, tab: 'Something went wrong', title: 'Something went wrong on our end', message: 'your account and balance are safe' },
    { code: 403, tab: 'No access', title: "This page isn't available to you", message: 'please contact support' },
];

test.describe('Custom error pages', () => {
    test.beforeEach(async ({ page }) => {
        await loginAs(page, USER.mobile, USER.password);
    });

    for (const c of CASES) {
        test(`${c.code} shows the branded page, not Symfony's`, async ({ page }, testInfo) => {
            const res = await page.goto(`${BASE_URL}/_error/${c.code}`);
            expect(res?.status()).toBe(c.code);

            await expect(page.locator('[data-testid="error-page"]')).toBeVisible();
            await expect(page.locator('[data-testid="error-title"]')).toHaveText(c.title);
            await expect(page.locator('[data-testid="error-message"]')).toContainText(c.message);
            await expect(page).toHaveTitle(new RegExp(`^${c.tab} — `));

            // Plain language only: no status number, no technical words (the dev-only web debug toolbar is ignored).
            const text = (await page.locator('[data-testid="error-page"]').textContent()) ?? '';
            expect(text).not.toMatch(/\b(404|500|403)\b|Symfony|Oops! An Error Occurred|Exception|Stack trace|Not Found|Internal Server Error|Forbidden/i);
            await expect(page.getByText('Oops! An Error Occurred')).toHaveCount(0);

            await page.setViewportSize({ width: 390, height: 844 });   // a player's phone
            await page.addStyleTag({ content: '.sf-toolbar, .sf-minitoolbar, .sf-toolbarreset { display: none !important; }' });
            await page.screenshot({ path: testInfo.outputPath(`error-${c.code}-phone.png`) });
        });
    }

    test('Go to Home and Go Back work', async ({ page }) => {
        await page.goto(`${BASE_URL}/`);
        await page.goto(`${BASE_URL}/_error/404`);

        await page.click('[data-testid="btn-error-back"]');
        await expect(page).toHaveURL(`${BASE_URL}/`);

        await page.goto(`${BASE_URL}/_error/404`);
        await expect(page.locator('[data-testid="btn-error-home"]')).toHaveAttribute('href', '/');
        await page.click('[data-testid="btn-error-home"]');
        await expect(page).toHaveURL(`${BASE_URL}/`);
    });
});
