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

const BASE = 'https://el3ab-player.caprover.al-arcade.com';
const SCREENSHOTS_DIR = __dirname;

const pages = [
  { name: '01-login', path: '/login' },
  { name: '02-home', path: '/' },
  { name: '03-play', path: '/play' },
  { name: '04-bots', path: '/bots' },
  { name: '05-game-bot', path: '/game?bot=nour&color=w&time=300&inc=0&rated=true' },
  { name: '06-puzzles', path: '/puzzles' },
  { name: '07-tournaments', path: '/tournaments' },
  { name: '08-leaderboard', path: '/leaderboard' },
  { name: '09-friends', path: '/friends' },
  { name: '10-orgs', path: '/orgs' },
  { name: '11-shop', path: '/shop' },
  { name: '12-achievements', path: '/achievements' },
  { name: '13-profile', path: '/profile' },
  { name: '14-settings', path: '/settings' },
  { name: '15-notifications', path: '/notifications' },
  { name: '16-matchmaking', path: '/matchmaking?tc=blitz_5_0&time=300000&inc=0' },
];

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 900 },
    locale: 'ar',
  });
  const page = await context.newPage();

  // Screenshot login page first (before auth)
  console.log('Capturing: login');
  await page.goto(BASE + '/login', { waitUntil: 'networkidle', timeout: 15000 });
  await page.screenshot({ path: SCREENSHOTS_DIR + '/01-login.png', fullPage: true });

  // Login
  console.log('Logging in...');
  await page.fill('input[type="email"], input[name="email"], #email', 'uitest@el3ab.com');
  await page.fill('input[type="password"], input[name="password"], #password', 'UiTest2026!');
  await page.click('button[type="submit"], .btn-gold, button:has-text("دخول")');
  await page.waitForTimeout(3000);

  // Set token in localStorage in case the login redirect didn't work via UI
  const token = await page.evaluate(async () => {
    const res = await fetch('https://safe-supabase-kong.caprover.al-arcade.com/auth/v1/token?grant_type=password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84'
      },
      body: JSON.stringify({ email: 'uitest@el3ab.com', password: 'UiTest2026!' })
    });
    const data = await res.json();
    if (data.access_token) {
      localStorage.setItem('el3ab_token', data.access_token);
      localStorage.setItem('el3ab_user', JSON.stringify(data.user));
      return data.access_token;
    }
    return null;
  });

  if (!token) {
    console.error('Failed to login!');
    await browser.close();
    process.exit(1);
  }
  console.log('Logged in successfully');

  // Capture all pages
  for (const p of pages) {
    if (p.name === '01-login') continue; // already captured
    console.log('Capturing:', p.name, p.path);
    try {
      await page.goto(BASE + p.path, { waitUntil: 'networkidle', timeout: 15000 });
      await page.waitForTimeout(2000);
      await page.screenshot({ path: SCREENSHOTS_DIR + '/' + p.name + '.png', fullPage: true });
    } catch (e) {
      console.log('  Error on', p.name, ':', e.message.substring(0, 80));
      try {
        await page.screenshot({ path: SCREENSHOTS_DIR + '/' + p.name + '-error.png', fullPage: true });
      } catch (e2) {}
    }
  }

  // Special: game page after making a move (wait for bot to move too)
  console.log('Capturing: game in progress (with bot move)');
  try {
    await page.goto(BASE + '/game?bot=amina&color=w&time=600&inc=0&rated=true', { waitUntil: 'networkidle', timeout: 15000 });
    await page.waitForTimeout(3000);
    // Click e2 square then e4 to make a move
    const board = await page.$('#board');
    if (board) {
      const box = await board.boundingBox();
      if (box) {
        const sqSize = box.width / 8;
        // e2 = file 4, rank 6 (from top) for white
        const e2x = box.x + sqSize * 4 + sqSize / 2;
        const e2y = box.y + sqSize * 6 + sqSize / 2;
        const e4x = box.x + sqSize * 4 + sqSize / 2;
        const e4y = box.y + sqSize * 4 + sqSize / 2;
        await page.mouse.click(e2x, e2y);
        await page.waitForTimeout(300);
        await page.mouse.click(e4x, e4y);
        await page.waitForTimeout(4000); // wait for bot response
      }
    }
    await page.screenshot({ path: SCREENSHOTS_DIR + '/17-game-in-progress.png', fullPage: true });
  } catch (e) {
    console.log('  Error on game-in-progress:', e.message.substring(0, 80));
  }

  // Capture analysis page (if accessible)
  console.log('Capturing: analysis');
  try {
    await page.goto(BASE + '/analysis', { waitUntil: 'networkidle', timeout: 10000 });
    await page.waitForTimeout(1500);
    await page.screenshot({ path: SCREENSHOTS_DIR + '/18-analysis.png', fullPage: true });
  } catch (e) {
    console.log('  Skipped analysis');
  }

  // Mobile viewport captures
  console.log('Capturing mobile views...');
  await page.setViewportSize({ width: 390, height: 844 });

  const mobilePages = [
    { name: '19-mobile-home', path: '/' },
    { name: '20-mobile-play', path: '/play' },
    { name: '21-mobile-game', path: '/game?bot=nour&color=w&time=300&inc=0&rated=true' },
    { name: '22-mobile-profile', path: '/profile' },
  ];

  for (const p of mobilePages) {
    console.log('Capturing mobile:', p.name);
    try {
      await page.goto(BASE + p.path, { waitUntil: 'networkidle', timeout: 15000 });
      await page.waitForTimeout(2000);
      await page.screenshot({ path: SCREENSHOTS_DIR + '/' + p.name + '.png', fullPage: true });
    } catch (e) {
      console.log('  Error:', e.message.substring(0, 60));
    }
  }

  await browser.close();
  console.log('\nDone! Screenshots saved to:', SCREENSHOTS_DIR);
})();
