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

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

  // 1. Games Hub with animated background
  console.log('1. Games Hub...');
  await page.goto(BASE + '/games', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);
  await page.screenshot({ path: path.join(DIR, 'phase23-01-games.png'), fullPage: true });

  // 2. Home page (streak + fire badge + number animations)
  console.log('2. Home...');
  await page.goto(BASE + '/', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);
  await page.screenshot({ path: path.join(DIR, 'phase23-02-home.png'), fullPage: true });

  // 3. Ludo game with 3D dice + capture particles
  console.log('3. Ludo game (playing for captures)...');
  await page.goto(BASE + '/ludo-game?mode=bot&bots=3&difficulty=hard', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);
  // Play several turns for captures
  for (let i = 0; i < 60; i++) {
    const canRoll = await page.evaluate(() => {
      const btn = document.getElementById('ludo-roll-btn');
      return btn && !btn.hasAttribute('disabled');
    });
    if (canRoll) {
      await page.click('#ludo-roll-btn');
      await page.waitForTimeout(800);
      await page.evaluate(() => {
        var hl = document.querySelectorAll('.ludo-piece--highlight');
        if (hl.length > 0) hl[0].click();
      });
    }
    await page.waitForTimeout(700);
  }
  await page.screenshot({ path: path.join(DIR, 'phase23-03-ludo-playing.png'), fullPage: true });

  // 4. Test toast
  console.log('4. Toast test...');
  await page.evaluate(() => { App.toast('هذا اختبار توست!', 'success'); });
  await page.waitForTimeout(500);
  await page.screenshot({ path: path.join(DIR, 'phase23-04-toast.png'), fullPage: true });

  // 5. Test celebration
  console.log('5. Celebration...');
  await page.evaluate(() => { App.celebrate('مبروك! فزت!'); });
  await page.waitForTimeout(1000);
  await page.screenshot({ path: path.join(DIR, 'phase23-05-celebrate.png'), fullPage: true });

  // 6. Mobile with bottom sheet
  console.log('6. Bottom sheet...');
  await page.setViewportSize({ width: 390, height: 844 });
  await page.goto(BASE + '/games', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(1500);
  await page.evaluate(() => {
    App.showSheet('<h3 style="font-size:16px;font-weight:700;margin-bottom:12px;">اختر وضع اللعب</h3><button class="btn btn-gold btn-block" style="margin-bottom:8px;">سريع 5+0</button><button class="btn btn-cyan btn-block">كلاسيكي 10+5</button>');
  });
  await page.waitForTimeout(500);
  await page.screenshot({ path: path.join(DIR, 'phase23-06-sheet-mobile.png'), fullPage: true });

  // 7. Check console errors
  const errors = [];
  page.on('console', msg => { if (msg.type() === 'error') errors.push(msg.text()); });
  await page.goto(BASE + '/', { waitUntil: 'networkidle', timeout: 15000 });
  await page.waitForTimeout(2000);
  if (errors.length > 0) console.log('ERRORS:', errors.join('\n'));
  else console.log('No console errors!');

  await browser.close();
  console.log('Done!');
})();
