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 = [];
  const logs = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
    else logs.push(msg.type() + ': ' + 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));
    }
  });

  // Test LOCAL 4-player mode
  console.log('Testing LOCAL 4-player mode...');
  await page.goto(BASE + '/ludo-game?mode=local&players=4', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(3000);

  // Check DOM state
  const domState = await page.evaluate(() => {
    const board = document.querySelector('.ludo-board');
    const cells = document.querySelectorAll('.ludo-cell');
    const pieces = document.querySelectorAll('.ludo-piece');
    const dice = document.querySelector('.ludo-dice');
    const rollBtn = document.querySelector('#ludo-roll-btn');
    return {
      boardExists: !!board,
      boardChildren: board ? board.children.length : 0,
      cellCount: cells.length,
      pieceCount: pieces.length,
      diceExists: !!dice,
      rollBtnExists: !!rollBtn,
      rollBtnDisabled: rollBtn ? rollBtn.hasAttribute('disabled') : null,
      boardHTML: board ? board.innerHTML.substring(0, 500) : 'NO BOARD'
    };
  });

  console.log('\nDOM State:', JSON.stringify(domState, null, 2));
  console.log('\nConsole errors:', errors.length ? errors.join('\n') : 'NONE');
  console.log('\nConsole logs:', logs.slice(0, 10).join('\n'));

  await page.screenshot({ path: path.join(DIR, 'debug-local-4p.png'), fullPage: true });

  // Also test local 2-player
  console.log('\n\nTesting LOCAL 2-player mode...');
  errors.length = 0;
  logs.length = 0;
  await page.goto(BASE + '/ludo-game?mode=local&players=2', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(3000);

  const domState2 = await page.evaluate(() => {
    const board = document.querySelector('.ludo-board');
    const cells = document.querySelectorAll('.ludo-cell');
    const pieces = document.querySelectorAll('.ludo-piece');
    return {
      boardExists: !!board,
      cellCount: cells.length,
      pieceCount: pieces.length,
    };
  });
  console.log('DOM State 2P:', JSON.stringify(domState2, null, 2));
  console.log('Console errors:', errors.length ? errors.join('\n') : 'NONE');

  await page.screenshot({ path: path.join(DIR, 'debug-local-2p.png'), fullPage: true });

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