import { expect, test } from '@playwright/test';

for (const scenario of [
  { locale: 'en', dir: 'ltr', title: /RentalDriveGo/ },
  { locale: 'fr', dir: 'ltr', title: /RentalDriveGo/ },
  { locale: 'ar', dir: 'rtl', title: /RentalDriveGo/ },
] as const) {
  test(`${scenario.locale} shell is server rendered`, async ({ page, request }) => {
    const raw = await request.get(`/${scenario.locale}`);
    const html = await raw.text();
    expect(raw.status()).toBe(200);
    expect(html).toMatch(
      new RegExp(`<html[^>]*lang=\"${scenario.locale}\"[^>]*dir=\"${scenario.dir}\"`),
    );

    const response = await page.goto(`/${scenario.locale}`);
    expect(response?.status()).toBe(200);
    await expect(page.locator('html')).toHaveAttribute('lang', scenario.locale);
    await expect(page.locator('html')).toHaveAttribute('dir', scenario.dir);
    await expect(page).toHaveTitle(scenario.title);
    await expect(page.locator('h1')).toBeVisible();
    await expect(page.locator('header')).toBeVisible();
    await expect(page.locator('footer')).toBeVisible();
    await expect(page.locator('link[rel="canonical"]')).toHaveAttribute(
      'href',
      new RegExp(`/${scenario.locale}$`),
    );
    for (const language of ['en', 'fr', 'ar', 'x-default']) {
      await expect(page.locator(`link[rel="alternate"][hreflang="${language}"]`)).toHaveCount(1);
    }
    await expect(page.locator('meta[property="og:locale"]')).toHaveAttribute(
      'content',
      scenario.locale,
    );
  });
}

test('root locale detection honors Accept-Language', async ({ browser }) => {
  const context = await browser.newContext({
    extraHTTPHeaders: { 'Accept-Language': 'ar;q=1,en;q=0.8' },
  });
  const page = await context.newPage();
  await page.goto('/');
  await expect(page).toHaveURL(/\/ar$/);
  await context.close();
});

test('locale switching keeps the semantic route and approved campaign state', async ({ page }) => {
  await page.goto('/en/privacy?utm_source=qa&email=drop-me#ignored');
  await page.getByLabel('Language').first().selectOption('fr');
  await expect(page).toHaveURL('/fr/confidentialite?utm_source=qa');
});

test('pending route shells are localized and noindex', async ({ page }) => {
  await page.goto('/fr/confidentialite');
  await expect(page.locator('h1')).toContainText('Confidentialité');
  await expect(page.locator('meta[name="robots"]')).toHaveAttribute('content', /noindex/);
});
