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();

  const errors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
  });
  page.on('pageerror', err => errors.push('PAGE ERROR: ' + err.message));

  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));
    }
  });

  console.log('Starting bot game (will play many turns)...');
  await page.goto(BASE + '/ludo-game?mode=bot&bots=1&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);

  let playerMoved = false;
  let turnCount = 0;
  let diceValues = [];

  for (let i = 0; i < 60 && !playerMoved; i++) {
    const canRoll = await page.evaluate(() => {
      const btn = document.getElementById('ludo-roll-btn');
      return btn && !btn.hasAttribute('disabled');
    });

    if (canRoll) {
      turnCount++;
      await page.click('#ludo-roll-btn');
      await page.waitForTimeout(1200);

      // Get dice value from the dots rendered
      const diceInfo = await page.evaluate(() => {
        const dots = document.querySelectorAll('.ludo-dice .ludo-dice-dot');
        return { dotCount: dots.length };
      });
      diceValues.push(diceInfo.dotCount);

      // Check if any pieces are highlighted
      const highlighted = await page.$$('.ludo-piece--highlight');
      if (highlighted.length > 0) {
        console.log('Turn ' + turnCount + ': Rolled ' + diceInfo.dotCount + ' - ' + highlighted.length + ' pieces highlighted!');

        // Take screenshot showing highlighted pieces
        await page.screenshot({ path: path.join(DIR, 'ludo-gameplay-highlight.png'), fullPage: true });

        // Click the highlighted piece
        await highlighted[0].click();
        playerMoved = true;
        console.log('  Clicked piece! Waiting for move...');
        await page.waitForTimeout(2000);

        // Take screenshot after move
        await page.screenshot({ path: path.join(DIR, 'ludo-gameplay-after-move.png'), fullPage: true });
      }
    }
    await page.waitForTimeout(1200);
  }

  if (!playerMoved) {
    console.log('Player never rolled 6 in ' + turnCount + ' turns (very unlucky!)');
  }

  // Now let game play more turns to show progression
  console.log('\nLetting game run for more turns...');
  for (let i = 0; i < 30; i++) {
    const canRoll = await page.evaluate(() => {
      const btn = document.getElementById('ludo-roll-btn');
      return btn && !btn.hasAttribute('disabled');
    });
    if (canRoll) {
      await page.click('#ludo-roll-btn');
      await page.waitForTimeout(1200);
      const hl = await page.$$('.ludo-piece--highlight');
      if (hl.length > 0) {
        await hl[0].click();
        await page.waitForTimeout(1500);
      }
    }
    await page.waitForTimeout(1200);
  }

  await page.screenshot({ path: path.join(DIR, 'ludo-gameplay-progress.png'), fullPage: true });

  // Get game log
  const finalLog = await page.evaluate(() => {
    const log = document.getElementById('ludo-log');
    return log ? log.innerText.split('\n').filter(l => l.trim()).slice(-15) : [];
  });

  console.log('\nGame log (last 15):');
  finalLog.forEach(l => console.log('  ' + l));
  console.log('\nDice values rolled by player:', diceValues.join(', '));
  console.log('Console errors:', errors.length ? errors.join('\n  ') : 'NONE');

  await browser.close();
})();
