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

test('explicit dark theme is present on the server-rendered root', async ({ browser, baseURL }) => {
  const origin = new URL(baseURL ?? 'http://127.0.0.1:3000');
  const context = await browser.newContext();
  await context.addCookies([
    {
      name: 'hpc-theme',
      value: 'dark',
      domain: origin.hostname,
      path: '/',
      secure: false,
      sameSite: 'Lax',
    },
  ]);
  const page = await context.newPage();
  const response = await page.goto('/en/dark');
  await expect(page.locator('html')).toHaveAttribute('data-theme-preference', 'dark');
  await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
  const csp = response?.headers()['content-security-policy'] ?? '';
  const nonce = await page.locator('#theme-bootstrap').getAttribute('nonce');
  expect(nonce).toBeTruthy();
  expect(csp).toContain("'unsafe-inline'");
  expect(csp).not.toContain("'strict-dynamic'");
  await context.close();
});

test('system preference resolves before interaction', async ({ browser }) => {
  const context = await browser.newContext({ colorScheme: 'dark' });
  const page = await context.newPage();
  await page.goto('/en/system');
  await expect(page.locator('html')).toHaveAttribute('data-theme-preference', 'system');
  await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
  await context.close();
});

test('system follows operating-system changes while explicit preferences ignore them', async ({
  page,
}) => {
  await page.goto('/en/system');
  const selector = page.getByLabel('Theme').first();

  await selector.selectOption('system');
  await page.emulateMedia({ colorScheme: 'dark' });
  await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
  await page.emulateMedia({ colorScheme: 'light' });
  await expect(page.locator('html')).toHaveAttribute('data-theme', 'light');

  await selector.selectOption('dark');
  await expect(page).toHaveURL('/en/dark');
  await page.emulateMedia({ colorScheme: 'light' });
  await expect(page.locator('html')).toHaveAttribute('data-theme-preference', 'dark');
  await expect(page.locator('html')).toHaveAttribute('data-theme', 'dark');
  expect(await page.evaluate(() => window.localStorage.getItem('hpc.theme.preference'))).toBe(
    'dark',
  );
  expect(await page.context().cookies()).toEqual(
    expect.arrayContaining([expect.objectContaining({ name: 'hpc-theme', value: 'dark' })]),
  );
});
