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

test('game state stays local across reload and offline use', async ({ page, context }) => {
  const requests = [];
  page.on('request', (request) => requests.push({ method: request.method(), path: new URL(request.url()).pathname }));

  await page.goto('/');
  await page.getByRole('button', { name: 'Start a 3-letter game' }).click();

  const stored = await page.evaluate(() => localStorage.getItem('spellray-state-v1'));
  expect(stored).toContain('"version":1');

  await page.reload();
  await expect(page.getByRole('button', { name: /Continue your 3-letter sun/ })).toBeVisible();
  await expect.poll(() => page.evaluate(() => navigator.serviceWorker.controller !== null)).toBe(true);
  expect(await page.evaluate(() => new URL(navigator.serviceWorker.controller.scriptURL).pathname)).toBe(
    '/spellray-service-worker.js'
  );

  await context.setOffline(true);
  await page.reload();
  await expect(page.getByRole('button', { name: /Continue your 3-letter sun/ })).toBeVisible();

  expect(requests.every(({ method }) => method === 'GET')).toBe(true);
  expect(requests.some(({ path }) => path.startsWith('/api/'))).toBe(false);
});
