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

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

  // Start bot game (easy, 1 bot)
  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);

  // Play multiple turns to see pieces move
  let turnCount = 0;
  let pieceMoved = false;

  for (let i = 0; i < 20; i++) {
    // Check if roll button is enabled
    const canRoll = await page.evaluate(() => {
      const btn = document.getElementById('ludo-roll-btn');
      return btn && !btn.hasAttribute('disabled');
    });

    if (canRoll) {
      turnCount++;
      console.log('Turn ' + turnCount + ': Rolling dice...');
      await page.click('#ludo-roll-btn');
      await page.waitForTimeout(1500); // Wait for dice animation

      // Check dice value and if pieces are highlighted
      const state = await page.evaluate(() => {
        const dice = document.querySelector('.ludo-dice');
        const diceValue = dice ? dice.dataset.value : null;
        const highlighted = document.querySelectorAll('.ludo-piece--highlight');
        const pieces = document.querySelectorAll('.ludo-piece');
        const piecesOnTrack = [];
        pieces.forEach(p => {
          const style = p.getAttribute('style') || '';
          if (style.includes('left') && !style.includes('display: none')) {
            piecesOnTrack.push({ player: p.dataset.player, piece: p.dataset.piece, style: style.substring(0, 80) });
          }
        });
        return {
          diceValue: diceValue,
          highlightedCount: highlighted.length,
          totalPieces: pieces.length,
          piecesOnTrack: piecesOnTrack.slice(0, 4)
        };
      });

      console.log('  Dice: ' + state.diceValue + ', Highlighted pieces: ' + state.highlightedCount);

      // Click a highlighted piece if available
      if (state.highlightedCount > 0) {
        await page.click('.ludo-piece--highlight');
        pieceMoved = true;
        console.log('  Clicked highlighted piece!');
        await page.waitForTimeout(1500); // Wait for move animation
      }
    }

    // Wait for bot turn
    await page.waitForTimeout(1500);
  }

  // Take final screenshot showing game progress
  await page.screenshot({ path: path.join(DIR, 'ludo-gameplay-test.png'), fullPage: true });

  // Get final game state
  const finalState = await page.evaluate(() => {
    const log = document.getElementById('ludo-log');
    const logEntries = log ? log.innerText.split('\n').filter(l => l.trim()).slice(-10) : [];
    const pieces = document.querySelectorAll('.ludo-piece');
    const onTrack = [];
    pieces.forEach(p => {
      const left = p.style.left;
      const top = p.style.top;
      if (left && top && left !== '' && top !== '') {
        onTrack.push(p.dataset.player + '-' + p.dataset.piece + ' at ' + left + ',' + top);
      }
    });
    return { logEntries, onTrack, totalPieces: pieces.length };
  });

  console.log('\n--- Final State ---');
  console.log('Pieces on track:', finalState.onTrack.length > 0 ? finalState.onTrack.join('; ') : 'NONE (all in base)');
  console.log('Game log (last 10):');
  finalState.logEntries.forEach(l => console.log('  ' + l));
  console.log('\nPiece moved by player: ' + pieceMoved);
  console.log('Console errors: ' + (errors.length ? errors.join('\n  ') : 'NONE'));
  console.log('Total turns played: ' + turnCount);

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