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 ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ar' });
  const page = await ctx.newPage();

  // Collect JS errors
  const errors = [];
  page.on('pageerror', err => errors.push(err.message));
  page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); });

  // Login
  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));
    }
  });
  await page.waitForTimeout(500);

  console.log('\n=== BACKGAMMON GAMEPLAY ===');

  // 1. Start a bot game - initial state
  await page.goto(BASE + '/backgammon-game?mode=bot&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(3000);
  await page.screenshot({ path: path.join(DIR, 'bg-gameplay-01-initial.png') });
  console.log('✓ bg-gameplay-01-initial.png');

  // 2. Click roll button if visible
  const rollBtn = await page.$('#bg-roll-btn');
  if (rollBtn) {
    const isVisible = await rollBtn.isVisible();
    if (isVisible) {
      await rollBtn.click();
      await page.waitForTimeout(2000);
      await page.screenshot({ path: path.join(DIR, 'bg-gameplay-02-rolled.png') });
      console.log('✓ bg-gameplay-02-rolled.png');
    } else {
      console.log('  Roll btn hidden (bot turn)');
      await page.screenshot({ path: path.join(DIR, 'bg-gameplay-02-bot-turn.png') });
      console.log('✓ bg-gameplay-02-bot-turn.png');
    }
  }

  // 3. Try clicking a checker to see highlights
  const points = await page.$$('.bg-point');
  if (points.length > 0) {
    // Click a point with white checkers (player 0)
    for (let p of points) {
      const checker = await p.$('.bg-checker--white');
      if (checker) {
        await p.click();
        await page.waitForTimeout(500);
        break;
      }
    }
    await page.screenshot({ path: path.join(DIR, 'bg-gameplay-03-selected.png') });
    console.log('✓ bg-gameplay-03-selected.png');
  }

  // 4. Fresh game - local mode, wider view
  await page.goto(BASE + '/backgammon-game?mode=local', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2500);
  await page.screenshot({ path: path.join(DIR, 'bg-gameplay-04-local.png') });
  console.log('✓ bg-gameplay-04-local.png');

  // 5. Mobile view
  const mCtx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ar', isMobile: true });
  const mobile = await mCtx.newPage();
  await mobile.goto(BASE + '/login', { waitUntil: 'networkidle', timeout: 15000 });
  await mobile.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));
    }
  });
  await mobile.waitForTimeout(500);

  await mobile.goto(BASE + '/backgammon-game?mode=bot&difficulty=medium', { waitUntil: 'networkidle', timeout: 15000 });
  await mobile.waitForTimeout(3000);
  await mobile.screenshot({ path: path.join(DIR, 'bg-gameplay-05-mobile.png') });
  console.log('✓ bg-gameplay-05-mobile.png');

  // 6. Zoomed in board screenshot for detail
  const boardEl = await page.$('.bg-board');
  if (boardEl) {
    await boardEl.screenshot({ path: path.join(DIR, 'bg-gameplay-06-board-zoom.png') });
    console.log('✓ bg-gameplay-06-board-zoom.png');
  }

  if (errors.length > 0) {
    console.log('\n⚠ JS Errors:');
    errors.forEach(e => console.log('  ' + e));
  } else {
    console.log('\n✓ No JS errors detected');
  }

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