import puppeteer from 'puppeteer';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SHOTS = path.join(__dirname, 'test-screenshots');
const BASE_URL = 'https://el3ab-player.caprover.al-arcade.com';

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

let step = 0;
async function shot(page, name) {
  step++;
  const filename = `${String(step).padStart(2, '0')}-${name}.png`;
  await page.screenshot({ path: path.join(SHOTS, filename), fullPage: true });
  console.log(`📸 ${filename}`);
}

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

  const page = await browser.newPage();
  await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 2 });

  console.log('🚀 Starting tournament UI test...\n');

  // Step 1: Load app
  console.log('1. Loading app...');
  await page.goto(BASE_URL, { waitUntil: 'networkidle2', timeout: 30000 });
  await delay(2000);
  await shot(page, 'app-load');

  // Step 2: Check if we need to login
  const isLoggedIn = await page.evaluate(() => {
    return !!localStorage.getItem('el3ab_store') &&
           JSON.parse(localStorage.getItem('el3ab_store') || '{}')?.auth?.token;
  });

  if (!isLoggedIn) {
    console.log('2. Need to login...');
    await shot(page, 'login-screen');

    // Look for login form
    const loginVisible = await page.$('#login-pass');
    if (!loginVisible) {
      // Try navigating to login
      const loginBtn = await page.$('[data-scene="auth-login"]') || await page.$('button');
      if (loginBtn) {
        await loginBtn.click();
        await delay(1500);
        await shot(page, 'login-form');
      }
    }

    // Fill login credentials
    const emailInput = await page.$('input[type="email"]') || await page.$('#login-email');
    const passInput = await page.$('#login-pass') || await page.$('input[type="password"]');

    if (emailInput && passInput) {
      await emailInput.click({ clickCount: 3 });
      await emailInput.type('test_puppet@el3ab.com');
      await passInput.click({ clickCount: 3 });
      await passInput.type('Test123!');
      await shot(page, 'login-filled');

      // Submit
      const submitBtn = await page.$('#login-btn') || await page.$('button[type="submit"]');
      if (submitBtn) {
        await submitBtn.click();
        await delay(3000);
        await shot(page, 'post-login');
      }
    } else {
      console.log('   ⚠️  Could not find login form, trying to register...');
      // Try register flow
      const regLink = await page.$('[data-action="register"]') || await page.$('a[href*="register"]');
      if (regLink) await regLink.click();
      await delay(1000);

      const regEmail = await page.$('input[type="email"]');
      const regPass = await page.$('input[type="password"]');
      const regName = await page.$('input[name="display_name"]') || await page.$('input[placeholder*="اسم"]');

      if (regEmail && regPass) {
        if (regName) { await regName.click({ clickCount: 3 }); await regName.type('TestBot'); }
        await regEmail.click({ clickCount: 3 });
        await regEmail.type('test_puppet@el3ab.com');
        await regPass.click({ clickCount: 3 });
        await regPass.type('Test123!');
        await shot(page, 'register-filled');

        const regBtn = await page.$('button[type="submit"]');
        if (regBtn) { await regBtn.click(); await delay(3000); }
        await shot(page, 'post-register');
      }
    }
  } else {
    console.log('2. Already logged in ✓');
  }

  // Step 3: Verify we're on the home screen
  await delay(1500);
  await shot(page, 'home-screen');

  // Step 4: Navigate to Rank tab (tournaments)
  console.log('3. Navigating to Rank tab...');
  const rankTab = await page.$('[data-world="rank"]');
  if (rankTab) {
    await rankTab.click();
    await delay(1500);
    await shot(page, 'rank-tab');
  } else {
    console.log('   ⚠️  Rank tab not found, trying alternative...');
    await page.evaluate(() => {
      const tabs = document.querySelectorAll('.tab-item');
      tabs.forEach(t => { if (t.textContent.includes('ترتيب') || t.dataset.world === 'rank') t.click(); });
    });
    await delay(1500);
    await shot(page, 'rank-tab-alt');
  }

  // Step 5: Navigate to Tournaments list
  console.log('4. Looking for tournaments scene...');
  // Check if there's a tournaments button/link on leaderboard
  const tourBtn = await page.evaluate(() => {
    const btns = document.querySelectorAll('button, a, [data-scene]');
    for (const b of btns) {
      if (b.textContent.includes('بطولات') || b.textContent.includes('tournament') || b.dataset?.scene === 'tournaments') {
        b.click();
        return true;
      }
    }
    return false;
  });

  if (tourBtn) {
    await delay(1500);
    await shot(page, 'tournaments-list');
  } else {
    // Try pushing scene directly
    console.log('   Pushing tournaments scene directly...');
    await page.evaluate(async () => {
      const scene = await import('/public/js/core/scene.js');
      scene.push('tournaments');
    });
    await delay(1500);
    await shot(page, 'tournaments-list-direct');
  }

  // Step 6: Check tournament list content
  console.log('5. Checking tournament list content...');
  const tourCards = await page.evaluate(() => {
    const cards = document.querySelectorAll('[data-tournament-id], .tour-card, [style*="border-radius"]');
    return cards.length;
  });
  console.log(`   Found ${tourCards} potential tournament cards`);
  await shot(page, 'tournaments-content');

  // Step 7: Try to open a tournament detail (click first card or push directly)
  console.log('6. Opening tournament detail...');
  const openedDetail = await page.evaluate(async () => {
    // First try clicking a tournament card
    const cards = document.querySelectorAll('[data-tournament-id]');
    if (cards.length > 0) {
      cards[0].click();
      return 'clicked';
    }
    // Try pushing directly with a known tournament or any clickable element
    const clickables = document.querySelectorAll('[onclick], [style*="cursor:pointer"]');
    for (const el of clickables) {
      if (el.closest('#tour-content') || el.textContent.includes('بطولة')) {
        el.click();
        return 'clicked-alt';
      }
    }
    return 'none';
  });
  console.log(`   Detail open: ${openedDetail}`);
  await delay(2000);
  await shot(page, 'tournament-detail');

  // Step 8: Check detail tabs
  console.log('7. Testing tournament detail tabs...');

  // Info tab (should be loaded)
  await shot(page, 'detail-info-tab');

  // Standings tab
  const standingsTab = await page.$('[data-tab="standings"]');
  if (standingsTab) {
    await standingsTab.click();
    await delay(1500);
    await shot(page, 'detail-standings-tab');
  }

  // Rounds tab
  const roundsTab = await page.$('[data-tab="rounds"]');
  if (roundsTab) {
    await roundsTab.click();
    await delay(1500);
    await shot(page, 'detail-rounds-tab');

    // Try to expand a round
    const roundEl = await page.$('[id^="round-pairings-"]');
    if (roundEl) {
      await roundEl.click();
      await delay(1500);
      await shot(page, 'detail-rounds-expanded');
    }
  }

  // My Games tab
  const myGamesTab = await page.$('[data-tab="my-games"]');
  if (myGamesTab) {
    await myGamesTab.click();
    await delay(1500);
    await shot(page, 'detail-mygames-tab');
  }

  // Bracket tab (if visible)
  const bracketTab = await page.$('#tab-bracket');
  if (bracketTab) {
    const isVisible = await page.evaluate(el => el.style.display !== 'none', bracketTab);
    if (isVisible) {
      await bracketTab.click();
      await delay(2000);
      await shot(page, 'bracket-view');
      // Go back
      const backBtn = await page.$('#back-btn');
      if (backBtn) { await backBtn.click(); await delay(1000); }
    }
  }

  // Arena tab (if visible)
  const arenaTab = await page.$('#tab-arena');
  if (arenaTab) {
    const isVisible = await page.evaluate(el => el.style.display !== 'none', arenaTab);
    if (isVisible) {
      await arenaTab.click();
      await delay(2000);
      await shot(page, 'arena-view');
      const backBtn = await page.$('#back-btn');
      if (backBtn) { await backBtn.click(); await delay(1000); }
    }
  }

  // Step 9: Test direct scene pushes for new scenes
  console.log('8. Testing new scenes directly...');

  // Tournament Bracket scene
  console.log('   Testing bracket scene...');
  await page.evaluate(async () => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-bracket', { tournamentId: '00000000-0000-0000-0000-000000000000' });
  });
  await delay(2000);
  await shot(page, 'scene-bracket');

  // Go back
  const backBtnBracket = await page.$('#back-btn');
  if (backBtnBracket) { await backBtnBracket.click(); await delay(1000); }

  // Tournament Arena scene
  console.log('   Testing arena scene...');
  await page.evaluate(async () => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-arena', { tournamentId: '00000000-0000-0000-0000-000000000000', tournamentName: 'أرينا تجريبية' });
  });
  await delay(2000);
  await shot(page, 'scene-arena');

  const backBtnArena = await page.$('#back-btn');
  if (backBtnArena) { await backBtnArena.click(); await delay(1000); }

  // Tournament Lobby scene
  console.log('   Testing lobby scene...');
  await page.evaluate(async () => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-lobby', {
      tournamentId: '00000000-0000-0000-0000-000000000000',
      tournamentName: 'بطولة الربيع 2026',
      startsAt: new Date(Date.now() + 600000).toISOString(),
      timeControl: 'blitz_5_3',
      format: 'swiss',
      prizePool: '1000'
    });
  });
  await delay(2000);
  await shot(page, 'scene-lobby');

  const backBtnLobby = await page.$('#leave-lobby');
  if (backBtnLobby) { await backBtnLobby.click(); await delay(1000); }

  // Tournament Live scene
  console.log('   Testing live scene...');
  await page.evaluate(async () => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-live', { tournamentId: '00000000-0000-0000-0000-000000000000', tournamentName: 'بطولة مباشرة' });
  });
  await delay(2000);
  await shot(page, 'scene-live');

  const backBtnLive = await page.$('#back-btn');
  if (backBtnLive) { await backBtnLive.click(); await delay(1000); }

  // Step 10: Test tournament-session toast notification
  console.log('9. Testing tournament toast notification...');
  await page.evaluate(async () => {
    const bus = await import('/public/js/core/bus.js');
    bus.emit('tournament:paired', {
      tournamentId: 'test-123',
      roundNumber: 2,
      opponentId: 'opp-456',
      pairingIndex: 0
    });
  });
  await delay(1000);
  await shot(page, 'toast-notification');

  // Step 11: Check HUD badge
  console.log('10. Testing HUD tournament badge...');
  await page.evaluate(async () => {
    const bus = await import('/public/js/core/bus.js');
    bus.emit('tournament:pending-updated', [{ tournament_id: '1' }, { tournament_id: '2' }]);
  });
  await delay(500);
  await shot(page, 'hud-badge');

  // Step 12: Navigate to chess game in tournament mode
  console.log('11. Testing chess game in tournament mode...');
  await page.evaluate(async () => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('chess-game', {
      mode: 'bot',
      botId: 'amina',
      timeControl: 'blitz_5_0',
      tournamentId: 'test-tournament-123',
      tournamentRound: 1
    });
  });
  await delay(3000);
  await shot(page, 'chess-game-tournament');

  // Step 13: Final overview
  console.log('12. Test complete!\n');
  await shot(page, 'final-state');

  // Summary
  console.log('═══════════════════════════════════════');
  console.log(`✅ ${step} screenshots saved to test-screenshots/`);
  console.log('═══════════════════════════════════════');

  await browser.close();
})().catch(err => {
  console.error('❌ Test failed:', err.message);
  process.exit(1);
});
