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...');
  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;

  for (let i = 0; i < 60; 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(1500);

      // Check highlighted pieces using evaluate + click via JS (bypass Playwright stability check)
      const clicked = await page.evaluate(() => {
        var hl = document.querySelectorAll('.ludo-piece--highlight');
        if (hl.length > 0) {
          hl[0].click();
          return true;
        }
        return false;
      });

      if (clicked && !playerMoved) {
        playerMoved = true;
        console.log('Turn ' + turnCount + ': Player moved a piece!');
        await page.waitForTimeout(2000);
        await page.screenshot({ path: path.join(DIR, 'ludo-gameplay-first-move.png'), fullPage: true });
      }
    }
    await page.waitForTimeout(1200);
  }

  // Continue playing for more progression
  for (let i = 0; i < 40; 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(1500);
      await page.evaluate(() => {
        var hl = document.querySelectorAll('.ludo-piece--highlight');
        if (hl.length > 0) hl[0].click();
      });
    }
    await page.waitForTimeout(1200);
  }

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

  // Get final state
  const finalState = await page.evaluate(() => {
    var log = document.getElementById('ludo-log');
    var entries = log ? log.innerText.split('\n').filter(function(l) { return l.trim(); }) : [];
    var pieces = document.querySelectorAll('.ludo-piece');
    var positions = [];
    pieces.forEach(function(p) {
      if (p.style.left && p.style.top) {
        positions.push(p.dataset.player + '-' + p.dataset.piece + ': ' + p.style.left + ',' + p.style.top);
      }
    });
    var result = document.querySelector('.ludo-result');
    return {
      log: entries.slice(-15),
      positions: positions,
      gameOver: !!result,
      resultText: result ? result.innerText : null
    };
  });

  console.log('\nFinal game log (last 15):');
  finalState.log.forEach(l => console.log('  ' + l));
  console.log('\nPiece positions:', finalState.positions.join('; '));
  console.log('Game over:', finalState.gameOver);
  if (finalState.resultText) console.log('Result:', finalState.resultText);
  console.log('Console errors:', errors.length ? errors.join('\n  ') : 'NONE');

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