const { chromium } = require('playwright');
const path = require('path');
const BASE = 'https://el3ab-player.caprover.al-arcade.com';
const DIR = __dirname;

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

  await page.goto(BASE + '/login', { waitUntil: 'networkidle', timeout: 15000 });
  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)); }
  });

  // Mobile screenshots of all pages
  const pages = [
    ['/', 'audit-home-mobile'],
    ['/games', 'audit-games-mobile'],
    ['/play', 'audit-chess-lobby-mobile'],
    ['/ludo', 'audit-ludo-lobby-mobile'],
    ['/profile', 'audit-profile-mobile'],
    ['/shop', 'audit-shop-mobile'],
    ['/friends', 'audit-friends-mobile'],
    ['/leaderboard', 'audit-leaderboard-mobile'],
    ['/settings', 'audit-settings-mobile'],
    ['/achievements', 'audit-achievements-mobile'],
  ];

  for (const [url, name] of pages) {
    await page.goto(BASE + url, { waitUntil: 'networkidle', timeout: 15000 });
    await page.waitForTimeout(2000);
    await page.screenshot({ path: path.join(DIR, name + '.png'), fullPage: true });
    console.log(name);
  }

  // Ludo game mobile
  await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);
  await page.screenshot({ path: path.join(DIR, 'audit-ludo-game-mobile.png'), fullPage: true });
  console.log('audit-ludo-game-mobile');

  await browser.close();
  console.log('Done!');
})();
