import { chromium } from 'playwright';

const targetUrl = process.env.VERIFY_URL ?? 'http://localhost:5173/';

const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1280, height: 720 } });

await page.goto(targetUrl, { waitUntil: 'networkidle' });
await page.waitForSelector('canvas');
await page.waitForFunction(() => window.__HEROS_GAME__ !== undefined);
await page.waitForTimeout(500);

await page.mouse.click(962, 240);
await page.waitForTimeout(250);

for (let i = 0; i < 20; i += 1) {
  const isBattleActive = await page.evaluate(() => {
    const activeScenes = window.__HEROS_GAME__?.scene.getScenes(true) ?? [];
    return activeScenes.some((scene) => scene.scene.key === 'BattleScene');
  });

  if (isBattleActive) {
    break;
  }

  await page.keyboard.press('Space');
  await page.waitForTimeout(220);
}

await page.waitForFunction(() => {
  const activeScenes = window.__HEROS_GAME__?.scene.getScenes(true) ?? [];
  return activeScenes.some((scene) => scene.scene.key === 'BattleScene');
});

await page.screenshot({ path: 'dist/verification-battle.png', fullPage: true });

const result = await page.evaluate(() => {
  const canvas = document.querySelector('canvas');
  const activeScenes = window.__HEROS_GAME__?.scene.getScenes(true).map((scene) => scene.scene.key) ?? [];

  return {
    activeScenes,
    canvasWidth: canvas?.width ?? 0,
    canvasHeight: canvas?.height ?? 0
  };
});

await browser.close();

if (result.canvasWidth !== 1280 || result.canvasHeight !== 720) {
  throw new Error(`Unexpected canvas size: ${result.canvasWidth}x${result.canvasHeight}`);
}

if (!result.activeScenes.includes('BattleScene')) {
  throw new Error(`BattleScene was not active. Active scenes: ${result.activeScenes.join(', ')}`);
}

console.log(`Verified title-to-battle flow at ${targetUrl}`);
