import puppeteer from 'puppeteer';
import { mkdir } from 'fs/promises';

const BASE_URL = 'https://el3ab-player.caprover.al-arcade.com';
const AUTH_URL = 'https://safe-supabase-kong.caprover.al-arcade.com/auth/v1';
const API_URL = `${BASE_URL}/api`;
const ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84';

const PLAYER1 = { email: 'testplayer1@el3ab.com', password: 'ChessTest1!', id: 'd14a27c6-2448-4319-a775-a9f94dd6de87', name: 'testplayer1', displayName: 'لاعب اختبار' };
const PLAYER2 = { email: 'test@el3ab.com', password: 'ChessTest2!', id: '37f947c0-e10b-4bef-88ec-c0aa0e8b8034', name: 'TestPlayer', displayName: 'TestPlayer' };

const wait = ms => new Promise(r => setTimeout(r, ms));
const SHOT_DIR = '/Users/mahmoudaglan/el3ab-player/screenshots/chess-test';

async function getToken(email, password) {
  const res = await fetch(`${AUTH_URL}/token?grant_type=password`, {
    method: 'POST',
    headers: { 'apikey': ANON_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password })
  });
  const data = await res.json();
  if (!data.access_token) throw new Error(`Login failed: ${JSON.stringify(data)}`);
  return { token: data.access_token, refreshToken: data.refresh_token };
}

async function setupPage(browser, player, auth) {
  const page = await browser.newPage();
  await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 2 });
  page.on('console', msg => {
    if (msg.type() === 'error' && !msg.text().includes('favicon'))
      console.log(`  [${player.name} ERR] ${msg.text().slice(0, 120)}`);
  });

  await page.goto(BASE_URL, { waitUntil: 'networkidle2', timeout: 30000 });
  await page.evaluate((token, refreshToken, userId, displayName, username) => {
    localStorage.setItem('el3ab_state', JSON.stringify({
      auth: { token, refreshToken, userId },
      player: { id: userId, display_name: displayName, username, level: 5, coins: 1000, xp: 500 },
      activeWorld: 'play', audioEnabled: false, language: 'ar'
    }));
  }, auth.token, auth.refreshToken, player.id, player.displayName, player.name);
  await page.reload({ waitUntil: 'networkidle2', timeout: 30000 });
  await wait(2000);
  return page;
}

async function navigateToQueue(page, playerName) {
  // 1. Click chess tile
  console.log(`   [${playerName}] Clicking chess tile...`);
  await page.evaluate(() => document.querySelector('[data-game="chess"]').click());
  await wait(1000);

  // 2. Click "أونلاين" (#btn-multi) in the popup menu
  console.log(`   [${playerName}] Clicking أونلاين...`);
  await page.evaluate(() => document.querySelector('#btn-multi').click());
  await wait(1000);

  // 3. Now on time-select — click a time control to start search
  console.log(`   [${playerName}] Clicking time control...`);
  const clicked = await page.evaluate(() => {
    // Look for time control buttons in the scene
    const allEls = document.querySelectorAll('button, [class*="btn"], [class*="time"], [role="button"]');
    for (const el of allEls) {
      const t = el.textContent.trim();
      if (t.includes('10+0') || t.includes('10 + 0') || t.includes('سريعة') || t.includes('Rapid') || t.includes('10')) {
        el.click(); return t;
      }
    }
    // Fallback: look for any button in the current scene
    const scene = document.querySelector('.scene');
    if (scene) {
      const btns = scene.querySelectorAll('button, [style*="cursor: pointer"]');
      for (const btn of btns) {
        if (btn.id !== 'menu-close') { btn.click(); return btn.textContent.slice(0,30); }
      }
    }
    return null;
  });
  console.log(`   [${playerName}] Clicked: "${clicked}"`);
  await wait(500);
}

async function run() {
  await mkdir(SHOT_DIR, { recursive: true });
  console.log('=== Chess Multiplayer UI Test ===\n');

  console.log('1. Authenticating...');
  const p1Auth = await getToken(PLAYER1.email, PLAYER1.password);
  const p2Auth = await getToken(PLAYER2.email, PLAYER2.password);
  console.log('   ✓ Both authenticated');

  console.log('\n2. Launching browser...');
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--ignore-certificate-errors']
  });

  const page1 = await setupPage(browser, PLAYER1, p1Auth);
  const page2 = await setupPage(browser, PLAYER2, p2Auth);
  console.log('   ✓ Both pages loaded');

  // Navigate Player 1 to queue
  console.log('\n3. Player 1 navigates to matchmaking...');
  await navigateToQueue(page1, PLAYER1.name);
  await page1.screenshot({ path: `${SHOT_DIR}/01-p1-queue.png` });

  // Navigate Player 2 to queue
  console.log('\n4. Player 2 navigates to matchmaking...');
  await navigateToQueue(page2, PLAYER2.name);
  await page2.screenshot({ path: `${SHOT_DIR}/02-p2-queue.png` });

  // Wait for match — polling happens every 3s
  console.log('\n5. Waiting for match (8s)...');
  await wait(8000);

  await page1.screenshot({ path: `${SHOT_DIR}/03-p1-matched.png` });
  await page2.screenshot({ path: `${SHOT_DIR}/03-p2-matched.png` });

  // Check if chess board appeared
  const p1Board = await page1.$('canvas');
  const p2Board = await page2.$('canvas');
  console.log(`   P1 has chess board: ${!!p1Board}`);
  console.log(`   P2 has chess board: ${!!p2Board}`);

  if (p1Board && p2Board) {
    console.log('   ✓ BOTH PLAYERS IN GAME!');
    await wait(2000);
    await page1.screenshot({ path: `${SHOT_DIR}/04-p1-board.png` });
    await page2.screenshot({ path: `${SHOT_DIR}/04-p2-board.png` });

    // Verify they're not playing against themselves — check opponent name
    const p1OpponentName = await page1.evaluate(() => {
      const el = document.querySelector('#opponent-name');
      return el ? el.textContent : 'not found';
    });
    const p2OpponentName = await page2.evaluate(() => {
      const el = document.querySelector('#opponent-name');
      return el ? el.textContent : 'not found';
    });
    console.log(`   P1 opponent: "${p1OpponentName}"`);
    console.log(`   P2 opponent: "${p2OpponentName}"`);

    // Wait for syncing to happen (poll cycle)
    await wait(5000);
    await page1.screenshot({ path: `${SHOT_DIR}/05-p1-playing.png` });
    await page2.screenshot({ path: `${SHOT_DIR}/05-p2-playing.png` });
  } else {
    // Debug: what page are they on?
    const p1Text = await page1.evaluate(() => document.body.innerText.slice(0, 200));
    const p2Text = await page2.evaluate(() => document.body.innerText.slice(0, 200));
    console.log(`   P1 page: ${p1Text.slice(0, 100)}`);
    console.log(`   P2 page: ${p2Text.slice(0, 100)}`);
  }

  await browser.close();
  console.log(`\n   Screenshots saved to: ${SHOT_DIR}/`);
  console.log('\n=== Done ===');
}

run().catch(err => {
  console.error('\n✗ FATAL ERROR:', err.message);
  process.exit(1);
});
