const puppeteer = require('puppeteer');
const path = require('path');

const BASE = 'https://el3ab-player.caprover.al-arcade.com';
const OUT = path.join(__dirname, 'screenshots');
const PHONE = { width: 390, height: 844, deviceScaleFactor: 2 };

const wait = ms => new Promise(r => setTimeout(r, ms));

const EMAIL = 'promo-test@el3ab.com';
const PASS = 'PromoTest123';

async function run() {
  const browser = await puppeteer.launch({
    headless: 'new',
    args: ['--no-sandbox', '--disable-setuid-sandbox']
  });

  const page = await browser.newPage();
  await page.setViewport(PHONE);

  // ─── 1. LOGIN ───
  console.log('1. Loading app...');
  await page.goto(BASE, { waitUntil: 'networkidle2', timeout: 30000 });
  await wait(3000);

  await page.screenshot({ path: path.join(OUT, '01-login.png') });
  console.log('   ✓ 01-login.png');

  console.log('2. Logging in...');
  const inputs = await page.$$('input');
  if (inputs.length >= 2) {
    await inputs[0].click({ clickCount: 3 });
    await inputs[0].type(EMAIL);
    await inputs[1].click({ clickCount: 3 });
    await inputs[1].type(PASS);
    await wait(300);
    const btn = await page.$('button');
    if (btn) await btn.click();
    await wait(6000);
  }

  // ─── 2. HOME SCREEN ───
  await page.screenshot({ path: path.join(OUT, '02-home.png') });
  console.log('   ✓ 02-home.png');

  // ─── 3. CHESS: Navigate to chess ───
  console.log('3. Navigating to Chess...');
  try {
    const chessEl = await page.evaluateHandle(() => {
      const all = document.querySelectorAll('*');
      for (const el of all) {
        const txt = el.textContent?.trim();
        if (txt === 'شطرنج' || txt === 'Chess') return el;
      }
      for (const el of all) {
        if (el.textContent?.includes('شطرنج') && el.tagName !== 'BODY' && el.tagName !== 'HTML' && el.children.length < 5) return el;
      }
      return null;
    });
    if (chessEl) {
      await chessEl.click();
      await wait(3000);
      await page.screenshot({ path: path.join(OUT, '03-chess-menu.png') });
      console.log('   ✓ 03-chess-menu.png');
    }
  } catch(e) { console.log('   ✗ Chess nav failed:', e.message); }

  // ─── 4. CHESS: Click "لاعب واحد" (single player) ───
  console.log('4. Selecting single player mode...');
  try {
    const singleEl = await page.evaluateHandle(() => {
      const all = document.querySelectorAll('*');
      for (const el of all) {
        const txt = el.textContent?.trim();
        if (txt === 'لاعب واحد' || txt === 'Single Player') return el;
      }
      return null;
    });
    if (singleEl) {
      await singleEl.click();
      await wait(3000);
    }
  } catch(e) { console.log('   ✗ Single player:', e.message); }

  // ─── 5. CHESS: Bot selection screen ───
  await page.screenshot({ path: path.join(OUT, '04-bot-select.png') });
  console.log('   ✓ 04-bot-select.png');

  // ─── 6. CHESS: Click first bot card ───
  console.log('5. Selecting a bot...');
  try {
    const botCard = await page.evaluateHandle(() => {
      const card = document.querySelector('.bot-card');
      return card || null;
    });
    if (botCard) {
      await botCard.click();
      await wait(2000);
      console.log('   → Bot selected, now on time select');

      // ─── 7. CHESS: Click a time control (5+0 blitz) ───
      const timeBtn = await page.evaluateHandle(() => {
        const btns = document.querySelectorAll('.time-btn, button');
        for (const b of btns) {
          if (b.textContent?.includes('5+0') || b.textContent?.includes('3+0')) return b;
        }
        // Fallback: first time button
        const firstTime = document.querySelector('.time-btn');
        return firstTime || null;
      });
      if (timeBtn) {
        await timeBtn.click();
        console.log('   → Time control selected, game starting...');
        await wait(6000);
        await page.screenshot({ path: path.join(OUT, '05-chess-start.png') });
        console.log('   ✓ 05-chess-start.png');

        // ─── 8. CHESS: Play moves by clicking canvas ───
        console.log('6. Playing chess moves...');
        const canvas = await page.$('canvas');
        if (canvas) {
          const box = await canvas.boundingBox();
          if (box) {
            const sq = box.width / 8;
            // Click e2 then e4 (column 4, rows from bottom: row 6 = e2, row 4 = e4)
            await page.mouse.click(box.x + sq * 4.5, box.y + sq * 6.5);
            await wait(500);
            await page.mouse.click(box.x + sq * 4.5, box.y + sq * 4.5);
            await wait(3000); // Wait for bot response
            // Click d2 then d4
            await page.mouse.click(box.x + sq * 3.5, box.y + sq * 6.5);
            await wait(500);
            await page.mouse.click(box.x + sq * 3.5, box.y + sq * 4.5);
            await wait(3000); // Wait for bot response
            // Click Nf3 (g1 to f3)
            await page.mouse.click(box.x + sq * 6.5, box.y + sq * 7.5);
            await wait(500);
            await page.mouse.click(box.x + sq * 5.5, box.y + sq * 5.5);
            await wait(3000);
          }
        }
        await page.screenshot({ path: path.join(OUT, '06-chess-midgame.png') });
        console.log('   ✓ 06-chess-midgame.png');
      }
    }
  } catch(e) { console.log('   ✗ Bot/game flow:', e.message); }

  // ─── 9. LUDO ───
  console.log('7. Navigating to Ludo...');
  await page.goto(BASE, { waitUntil: 'networkidle2', timeout: 30000 });
  await wait(4000);

  try {
    const ludoEl = await page.evaluateHandle(() => {
      const all = document.querySelectorAll('*');
      for (const el of all) {
        const txt = el.textContent?.trim();
        if (txt === 'لودو' || txt === 'Ludo') return el;
      }
      for (const el of all) {
        if (el.textContent?.includes('لودو') && el.tagName !== 'BODY' && el.tagName !== 'HTML' && el.children.length < 5) return el;
      }
      return null;
    });
    if (ludoEl) {
      await ludoEl.click();
      await wait(3000);
      await page.screenshot({ path: path.join(OUT, '07-ludo-menu.png') });
      console.log('   ✓ 07-ludo-menu.png');

      // Start ludo game vs bot
      const ludoPlayBtn = await page.evaluateHandle(() => {
        const all = document.querySelectorAll('button, .btn, [class*="play"], [class*="start"]');
        for (const el of all) {
          const txt = el.textContent?.trim();
          if (txt && (txt.includes('العب') || txt.includes('ابدأ') || txt.includes('بوت') || txt.includes('لاعب واحد'))) return el;
        }
        return null;
      });
      if (ludoPlayBtn) {
        await ludoPlayBtn.click();
        await wait(6000);
        await page.screenshot({ path: path.join(OUT, '08-ludo-game.png') });
        console.log('   ✓ 08-ludo-game.png');
      }
    }
  } catch(e) { console.log('   ✗ Ludo:', e.message); }

  // ─── 10. DOMINO ───
  console.log('8. Navigating to Domino...');
  await page.goto(BASE, { waitUntil: 'networkidle2', timeout: 30000 });
  await wait(4000);

  try {
    const domEl = await page.evaluateHandle(() => {
      const all = document.querySelectorAll('*');
      for (const el of all) {
        const txt = el.textContent?.trim();
        if (txt === 'دومينو' || txt === 'Domino') return el;
      }
      return null;
    });
    if (domEl) {
      await domEl.click();
      await wait(3000);
      await page.screenshot({ path: path.join(OUT, '09-domino-menu.png') });
      console.log('   ✓ 09-domino-menu.png');
    }
  } catch(e) { console.log('   ✗ Domino:', e.message); }

  // ─── 11. FINAL HOME ───
  console.log('9. Final home capture...');
  await page.goto(BASE, { waitUntil: 'networkidle2', timeout: 30000 });
  await wait(5000);
  await page.screenshot({ path: path.join(OUT, '10-home-final.png') });
  console.log('   ✓ 10-home-final.png');

  await browser.close();
  console.log('\n✅ Done! Screenshots saved to:', OUT);
}

run().catch(e => { console.error(e); process.exit(1); });
