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: 1440, height: 900 },
    locale: 'ar',
  });
  const page = await context.newPage();

  // Login
  console.log('Logging in...');
  await page.goto(BASE + '/login', { waitUntil: 'networkidle', timeout: 15000 });
  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('Login failed!');
    await browser.close();
    process.exit(1);
  }
  console.log('Logged in');

  // Desktop screenshots
  const desktopPages = [
    { name: 'ludo-01-menu', path: '/ludo' },
    { name: 'ludo-02-local-4p', path: '/ludo-game?mode=local&players=4' },
    { name: 'ludo-03-bot-easy', path: '/ludo-game?mode=bot&bots=1&difficulty=easy' },
    { name: 'ludo-04-bot-hard-3', path: '/ludo-game?mode=bot&bots=3&difficulty=hard' },
    { name: 'ludo-05-matchmaking', path: '/ludo-matchmaking' },
    { name: 'ludo-06-live-create', path: '/ludo-live?action=create' },
  ];

  for (const p of desktopPages) {
    console.log('Desktop:', p.name);
    try {
      await page.goto(BASE + p.path, { waitUntil: 'networkidle', timeout: 15000 });
      await page.waitForTimeout(2500);
      await page.screenshot({ path: path.join(DIR, p.name + '.png'), fullPage: true });
    } catch (e) {
      console.log('  Error:', e.message.substring(0, 100));
      try { await page.screenshot({ path: path.join(DIR, p.name + '-error.png'), fullPage: true }); } catch (e2) {}
    }
  }

  // Test bot game interaction - wait for bot to roll dice
  console.log('Testing bot game with dice interaction...');
  try {
    await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
    await page.waitForTimeout(1500);

    // Click roll button if visible
    const rollBtn = await page.$('#ludo-roll-btn');
    if (rollBtn) {
      const isDisabled = await rollBtn.getAttribute('disabled');
      if (isDisabled === null) {
        await rollBtn.click();
        await page.waitForTimeout(2000);
      }
    }
    await page.waitForTimeout(3000); // Wait for bot turn
    await page.screenshot({ path: path.join(DIR, 'ludo-07-game-playing.png'), fullPage: true });
  } catch (e) {
    console.log('  Error:', e.message.substring(0, 100));
  }

  // Check console errors
  const errors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
  });
  await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(3000);
  if (errors.length) {
    console.log('\nConsole errors found:');
    errors.forEach(e => console.log('  -', e.substring(0, 150)));
  }

  // Mobile screenshots
  console.log('\nMobile views...');
  await page.setViewportSize({ width: 390, height: 844 });

  const mobilePages = [
    { name: 'ludo-08-mobile-menu', path: '/ludo' },
    { name: 'ludo-09-mobile-game', path: '/ludo-game?mode=bot&bots=1&difficulty=easy' },
    { name: 'ludo-10-mobile-local', path: '/ludo-game?mode=local&players=2' },
  ];

  for (const p of mobilePages) {
    console.log('Mobile:', p.name);
    try {
      await page.goto(BASE + p.path, { waitUntil: 'networkidle', timeout: 15000 });
      await page.waitForTimeout(2500);
      await page.screenshot({ path: path.join(DIR, p.name + '.png'), fullPage: true });
    } catch (e) {
      console.log('  Error:', e.message.substring(0, 100));
      try { await page.screenshot({ path: path.join(DIR, p.name + '-error.png'), fullPage: true }); } catch (e2) {}
    }
  }

  // Mobile bot game with dice
  console.log('Mobile bot game interaction...');
  try {
    await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
    await page.waitForTimeout(1500);
    const rollBtn = await page.$('#ludo-roll-btn');
    if (rollBtn) {
      const isDisabled = await rollBtn.getAttribute('disabled');
      if (isDisabled === null) {
        await rollBtn.click();
        await page.waitForTimeout(2000);
      }
    }
    await page.waitForTimeout(3000);
    await page.screenshot({ path: path.join(DIR, 'ludo-11-mobile-playing.png'), fullPage: true });
  } catch (e) {
    console.log('  Error:', e.message.substring(0, 100));
  }

  await browser.close();
  console.log('\nDone! Ludo screenshots saved to:', DIR);
})();
