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 ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ar' });
  const page = await ctx.newPage();

  // 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));
    }
  });
  await page.waitForTimeout(500);

  // Start a 2P bot game
  await page.goto(BASE + '/domino-game?mode=2p&type=bot&players=2&difficulty=easy', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(3000);
  await page.screenshot({ path: path.join(DIR, 'domino-play-01-start.png') });
  console.log('✓ domino-play-01-start.png (game started, bot may have played)');

  // Try to click first playable tile
  const tiles = await page.$$('.domino-tile--playable');
  console.log(`  Found ${tiles.length} playable tiles`);
  if (tiles.length > 0) {
    await tiles[0].click();
    await page.waitForTimeout(500);
    await page.screenshot({ path: path.join(DIR, 'domino-play-02-selected.png') });
    console.log('✓ domino-play-02-selected.png (tile selected)');

    // Click an end button if visible
    const endBtns = await page.$$('.domino-end-btn');
    console.log(`  Found ${endBtns.length} end buttons`);
    if (endBtns.length > 0) {
      await endBtns[0].click();
      await page.waitForTimeout(2000);
      await page.screenshot({ path: path.join(DIR, 'domino-play-03-placed.png') });
      console.log('✓ domino-play-03-placed.png (tile placed, bot responds)');
    }
  }

  // Wait for more bot turns
  await page.waitForTimeout(3000);
  await page.screenshot({ path: path.join(DIR, 'domino-play-04-progress.png') });
  console.log('✓ domino-play-04-progress.png (game progressed)');

  // Try playing a few more tiles
  for (let i = 0; i < 3; i++) {
    const playable = await page.$$('.domino-tile--playable');
    if (playable.length > 0) {
      await playable[0].click();
      await page.waitForTimeout(300);
      const ends = await page.$$('.domino-end-btn');
      if (ends.length > 0) {
        await ends[0].click();
        await page.waitForTimeout(2000);
      }
    } else {
      // Try draw button
      const drawBtn = await page.$('.domino-draw-btn');
      if (drawBtn) {
        await drawBtn.click();
        await page.waitForTimeout(1500);
      }
    }
  }

  await page.screenshot({ path: path.join(DIR, 'domino-play-05-midgame.png') });
  console.log('✓ domino-play-05-midgame.png (after several turns)');

  await browser.close();
  console.log('\n✅ Domino gameplay test complete!');
})();
