const fs = require('fs');
const path = require('path');
const { chromium } = require('playwright');

const url = process.argv[2] || 'http://127.0.0.1:5175/';
const outputDir = path.resolve(__dirname, '..', 'verification');
fs.mkdirSync(outputDir, { recursive: true });

async function runScenario(browser, name, viewport) {
  const page = await browser.newPage({ viewport });
  const errors = [];
  page.on('console', (message) => {
    if (message.type() === 'error') errors.push(`console: ${message.text()}`);
  });
  page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));

  await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });
  await page.waitForSelector('canvas');
  await page.waitForTimeout(800);

  const stages = [];
  const capture = async (stage) => {
    const file = `${name}-${stage}.png`;
    await page.screenshot({ path: path.join(outputDir, file) });
    stages.push({
      stage,
      prompt: await page.locator('#prompt').textContent(),
      canvas: await page.locator('canvas').evaluate((node) => ({
        width: node.width,
        height: node.height,
        clientWidth: node.clientWidth,
        clientHeight: node.clientHeight,
      })),
    });
  };

  await capture('carousel');
  await page.mouse.click(viewport.width / 2, viewport.height * 0.52);
  await page.waitForFunction(() => document.querySelector('#prompt')?.textContent === 'Slice the seal');
  await page.waitForTimeout(3400);
  await capture('focus');

  const tearStartX = viewport.width >= 800 ? viewport.width * 0.41 : viewport.width * 0.19;
  await page.mouse.move(tearStartX, viewport.height * 0.52);
  await page.mouse.down();
  await page.mouse.move(viewport.width * 0.55, viewport.height * 0.52, { steps: 18 });
  await capture('tear');
  await page.mouse.move(viewport.width * 0.94, viewport.height * 0.52, { steps: 18 });
  await page.mouse.up();
  await page.waitForFunction(() => document.querySelector('#prompt')?.textContent === 'Tap to speed up');
  await page.waitForTimeout(3500);
  await capture('reveal');

  await page.mouse.click(viewport.width / 2, viewport.height * 0.52);
  await page.waitForFunction(() => document.querySelector('#prompt')?.textContent === 'Tap to continue');
  await page.waitForTimeout(300);
  await capture('complete');

  const layout = await page.evaluate(() => ({
    bodyWidth: document.body.scrollWidth,
    viewportWidth: window.innerWidth,
    bodyHeight: document.body.scrollHeight,
    viewportHeight: window.innerHeight,
  }));
  await page.close();
  return { name, viewport, errors, stages, layout };
}

(async () => {
  const browser = await chromium.launch({
    headless: true,
    executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
    args: ['--ignore-gpu-blocklist', '--enable-webgl'],
  });
  try {
    const desktop = await runScenario(browser, 'desktop', { width: 1440, height: 900 });
    const mobile = await runScenario(browser, 'mobile', { width: 390, height: 844 });
    const report = { url, desktop, mobile };
    fs.writeFileSync(path.join(outputDir, 'verification.json'), JSON.stringify(report, null, 2));
    process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  } finally {
    await browser.close();
  }
})().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
