// apps/client/test/e2e/cookie-reload.e2e.test.ts
// [int->REQ-CLI-09] [int->REQ-CLI-04]
//
// Plan 06-15 Task 3 — Cookie auto-login reload regression test.
// UAT Finding #2 (D-25) reproducer: login via form, reload page, assert GameScene
// re-renders via the cookie auto-login fast-path (BootScene → LoginScene fast-path
// → GameScene with session_token threaded through).
//
// Assertions use window.__rebno deterministic test hook (D-35, exposed by 06-14
// Task 3 in dev/test mode only) — NOT WebGL canvas-pixel sampling.
// Room slug asserted as 'mvp-room' per D-30.

import { test, expect, loginAs, waitForGameReady } from './fixtures.js';

test('Cookie auto-login: login → reload → GameScene re-renders within 5s + chat works', async ({
  page,
  accountA,
  inviteSuffix,
}) => {
  // 1. Login via form and confirm game is ready.
  await loginAs(page, accountA, inviteSuffix);
  await waitForGameReady(page);

  // Confirm initial state via __rebno hook (D-35).
  const initialRoomId = await page.evaluate(
    () => (window as unknown as { __rebno?: { roomId?: string } }).__rebno?.roomId,
  );
  expect(initialRoomId).toBe('mvp-room');

  // 2. Reload the page — this triggers the cookie auto-login fast-path.
  await page.reload();

  // 3. Re-assert game-ready within 5s — this is the D-25 regression assertion.
  //    If session_token is not threaded through BootScene → LoginScene → GameScene,
  //    GameScene.connect() silently early-returns and canvas never becomes ready.
  await expect(page.locator('canvas[data-game-ready="true"]')).toBeVisible({
    timeout: 5_000,
  });

  // 4. Confirm room ID and atlas texture are correct via __rebno hook (D-35 + D-30).
  const postReloadRoomId = await page.evaluate(
    () => (window as unknown as { __rebno?: { roomId?: string } }).__rebno?.roomId,
  );
  expect(postReloadRoomId).toBe('mvp-room');

  const loadedTextures = await page.evaluate(
    () =>
      (window as unknown as { __rebno?: { loadedTextures?: string[] } }).__rebno
        ?.loadedTextures ?? [],
  );
  // The 'mvp' atlas is loaded by BootScene on the cookie reload path (06-14).
  expect(loadedTextures).toContain('mvp');

  // 5. Chat round-trip: send a message and assert the chat line appears.
  await page.keyboard.press('Enter');
  await page.locator('[data-chat-input]').waitFor({ timeout: 5_000 });
  await page.fill('[data-chat-input]', 'hello-after-reload');
  await page.locator('[data-chat-input]').press('Enter');
  await expect(
    page.locator('[data-chat-line]').filter({ hasText: 'hello-after-reload' }),
  ).toBeVisible({ timeout: 5_000 });
});
