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', 'swiss-flow');
const BASE_URL = 'https://el3ab-player.caprover.al-arcade.com';

const ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzM1Njg5NjAwLCJleHAiOjE4OTM0NTYwMDB9.31PF6PvP-pSrvRuQwLFptQoejR0W1A7o53lZhEbnz84';
const AUTH_URL = 'https://safe-supabase-kong.caprover.al-arcade.com/auth/v1';

const TEST_EMAIL = 'mahmoudaglan@al-arcade.com';
const TEST_PASS = 'TestTour123!';
const TOURNAMENT_ID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
const ROUND_ID = 'a1111111-1111-1111-1111-111111111111';

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 function getAuthToken() {
  const res = await fetch(`${AUTH_URL}/token?grant_type=password`, {
    method: 'POST',
    headers: { 'apikey': ANON_KEY, 'Content-Type': 'application/json' },
    body: JSON.stringify({ email: TEST_EMAIL, password: TEST_PASS })
  });
  const data = await res.json();
  if (!data.access_token) throw new Error('Login failed: ' + JSON.stringify(data));
  return data;
}

(async () => {
  console.log('🏆 Swiss Tournament UI Test\n');
  console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');

  // Create screenshots directory
  const { mkdirSync } = await import('fs');
  mkdirSync(SHOTS, { recursive: true });

  // Get auth token first
  console.log('\n1️⃣  Authenticating as aglan...');
  const authData = await getAuthToken();
  console.log(`   ✅ Logged in as ${authData.user.email} (${authData.user.id})`);

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

  // Collect console errors
  const errors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
  });
  page.on('pageerror', err => errors.push(err.message));

  // Step 1: Load app and inject auth
  console.log('\n2️⃣  Loading app and injecting auth session...');
  await page.goto(BASE_URL, { waitUntil: 'networkidle2', timeout: 30000 });
  await delay(1000);

  // Inject the auth token into localStorage (key is 'el3ab_state')
  await page.evaluate((auth) => {
    const storeData = JSON.parse(localStorage.getItem('el3ab_state') || '{}');
    storeData.auth = {
      token: auth.access_token,
      refreshToken: auth.refresh_token,
      userId: auth.user.id
    };
    localStorage.setItem('el3ab_state', JSON.stringify(storeData));
  }, authData);

  // Reload to pick up the auth
  await page.reload({ waitUntil: 'networkidle2', timeout: 30000 });
  await delay(2000);
  await shot(page, 'home-authenticated');

  // Verify we're logged in
  const isLoggedIn = await page.evaluate(() => {
    const store = JSON.parse(localStorage.getItem('el3ab_state') || '{}');
    return !!store.auth?.token;
  });
  console.log(`   Auth status: ${isLoggedIn ? '✅ Logged in' : '❌ Not logged in'}`);

  // Step 2: Navigate to Rank tab
  console.log('\n3️⃣  Navigating to Rank tab...');
  const rankClicked = await page.evaluate(() => {
    const tab = document.querySelector('[data-world="rank"]');
    if (tab) { tab.click(); return true; }
    return false;
  });
  await delay(1500);
  await shot(page, 'rank-tab');
  console.log(`   Rank tab clicked: ${rankClicked ? '✅' : '❌'}`);

  // Step 3: Navigate to tournaments list
  console.log('\n4️⃣  Opening tournaments list...');
  const tourClicked = await page.evaluate(() => {
    const btns = document.querySelectorAll('button, a, [data-scene]');
    for (const b of btns) {
      if (b.textContent.includes('بطولات') || b.dataset?.scene === 'tournaments') {
        b.click();
        return true;
      }
    }
    return false;
  });

  if (!tourClicked) {
    // Push scene directly
    await page.evaluate(async () => {
      const scene = await import('/public/js/core/scene.js');
      scene.push('tournaments');
    });
  }
  await delay(2000);
  await shot(page, 'tournaments-list');

  // Check if our tournament appears
  const tourCards = await page.evaluate((tid) => {
    const content = document.querySelector('#tour-content') || document.body;
    const text = content.innerText;
    return {
      hasSwissTournament: text.includes('سويسرية تجريبية') || text.includes(tid),
      cardCount: document.querySelectorAll('[data-tournament-id]').length,
      allText: text.substring(0, 500)
    };
  }, TOURNAMENT_ID);
  console.log(`   Tournament cards: ${tourCards.cardCount}`);
  console.log(`   Swiss tournament visible: ${tourCards.hasSwissTournament ? '✅' : '⚠️ Not found in list'}`);

  // Step 4: Open tournament detail directly
  console.log('\n5️⃣  Opening tournament detail...');
  await page.evaluate(async (tid) => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-detail', { tournamentId: tid });
  }, TOURNAMENT_ID);
  await delay(2500);
  await shot(page, 'tournament-detail-info');

  // Check tournament loaded
  const tourInfo = await page.evaluate(() => {
    const title = document.querySelector('#tour-title');
    const content = document.querySelector('#tour-content');
    return {
      title: title?.textContent || '',
      hasContent: content?.children?.length > 0,
      contentText: content?.innerText?.substring(0, 300) || ''
    };
  });
  console.log(`   Title: ${tourInfo.title}`);
  console.log(`   Content loaded: ${tourInfo.hasContent ? '✅' : '❌'}`);

  // Step 5: Check Standings tab
  console.log('\n6️⃣  Checking Standings tab...');
  await page.evaluate(() => {
    const tab = document.querySelector('[data-tab="standings"]');
    if (tab) tab.click();
  });
  await delay(1500);
  await shot(page, 'tournament-standings');

  const standingsContent = await page.evaluate(() => {
    return document.querySelector('#tour-content')?.innerText?.substring(0, 200) || '';
  });
  console.log(`   Standings: ${standingsContent.substring(0, 80)}...`);

  // Step 6: Check Rounds tab — this should show our pairing with Play button
  console.log('\n7️⃣  Checking Rounds tab (should show our pairing)...');
  await page.evaluate(() => {
    const tab = document.querySelector('[data-tab="rounds"]');
    if (tab) tab.click();
  });
  await delay(1500);
  await shot(page, 'tournament-rounds');

  // Click to expand the round pairings
  const roundExpanded = await page.evaluate(async (roundId) => {
    const roundEl = document.querySelector(`#round-pairings-${roundId}`);
    if (roundEl) {
      roundEl.click();
      return true;
    }
    // Try any round pairings element
    const anyRound = document.querySelector('[id^="round-pairings-"]');
    if (anyRound) {
      anyRound.click();
      return true;
    }
    return false;
  }, ROUND_ID);
  await delay(2000);
  await shot(page, 'tournament-rounds-expanded');
  console.log(`   Round expanded: ${roundExpanded ? '✅' : '❌'}`);

  // Check if Play button appeared
  const playBtnVisible = await page.evaluate(() => {
    const btn = document.querySelector('.play-pairing-btn');
    return btn ? { text: btn.textContent, roundId: btn.dataset.roundId, idx: btn.dataset.idx } : null;
  });
  console.log(`   Play button: ${playBtnVisible ? `✅ "${playBtnVisible.text}" (round: ${playBtnVisible.roundId}, idx: ${playBtnVisible.idx})` : '❌ Not found'}`);

  // Step 7: Check My Games tab
  console.log('\n8️⃣  Checking My Games tab...');
  await page.evaluate(() => {
    const tab = document.querySelector('[data-tab="my-games"]');
    if (tab) tab.click();
  });
  await delay(2000);
  await shot(page, 'tournament-my-games');

  const myGamesContent = await page.evaluate(() => {
    const content = document.querySelector('#tour-content');
    const playBtn = content?.querySelector('.play-pending-btn');
    return {
      text: content?.innerText?.substring(0, 300) || '',
      hasPlayBtn: !!playBtn,
      playBtnText: playBtn?.textContent || ''
    };
  });
  console.log(`   My Games content: ${myGamesContent.text.substring(0, 100)}`);
  console.log(`   Play pending button: ${myGamesContent.hasPlayBtn ? `✅ "${myGamesContent.playBtnText}"` : '❌ Not found'}`);

  // Step 8: Try launching the tournament match
  console.log('\n9️⃣  Launching tournament match (create-or-join)...');

  // First try clicking the play button if it exists
  let matchLaunched = false;
  if (myGamesContent.hasPlayBtn) {
    await page.evaluate(() => {
      const btn = document.querySelector('.play-pending-btn');
      if (btn) btn.click();
    });
    await delay(3000);
    matchLaunched = true;
  } else if (playBtnVisible) {
    // Go back to rounds tab and click
    await page.evaluate(() => {
      const tab = document.querySelector('[data-tab="rounds"]');
      if (tab) tab.click();
    });
    await delay(1500);
    await page.evaluate(async (roundId) => {
      const roundEl = document.querySelector(`#round-pairings-${roundId}`) || document.querySelector('[id^="round-pairings-"]');
      if (roundEl) roundEl.click();
    }, ROUND_ID);
    await delay(2000);
    await page.evaluate(() => {
      const btn = document.querySelector('.play-pairing-btn');
      if (btn) btn.click();
    });
    await delay(3000);
    matchLaunched = true;
  } else {
    // Try direct API call via scene push
    console.log('   No play button found, launching match directly...');
    await page.evaluate(async (tournamentId, roundId) => {
      const net = await import('/public/js/core/net.js');
      const scene = await import('/public/js/core/scene.js');
      try {
        const data = await net.post('tournament-match.php', {
          action: 'create-or-join',
          tournament_id: tournamentId,
          round_id: roundId,
          pairing_index: 0
        });
        console.log('[test] create-or-join result:', JSON.stringify(data));
        if (data.match_id) {
          scene.push('chess-game', {
            mode: 'live',
            matchId: data.match_id,
            color: data.color || 'white',
            timeControl: 'blitz_5_0',
            tournamentId: tournamentId,
            tournamentRound: 1
          });
        }
      } catch (e) {
        console.error('[test] create-or-join error:', e.message);
      }
    }, TOURNAMENT_ID, ROUND_ID);
    await delay(3000);
    matchLaunched = true;
  }

  await shot(page, 'match-launched');

  // Check if we're in a chess game scene
  const inChessGame = await page.evaluate(() => {
    const board = document.querySelector('#chess-board') || document.querySelector('[data-chess-board]') || document.querySelector('canvas');
    const timer = document.querySelector('[id*="clock"]') || document.querySelector('[id*="timer"]');
    return {
      hasBoard: !!board,
      hasTimer: !!timer,
      bodyText: document.body.innerText.substring(0, 200)
    };
  });
  console.log(`   Chess board visible: ${inChessGame.hasBoard ? '✅' : '❌'}`);
  console.log(`   Timer visible: ${inChessGame.hasTimer ? '✅' : '❌'}`);

  if (inChessGame.hasBoard) {
    await shot(page, 'chess-game-tournament-mode');

    // Check tournament indicator
    const tourIndicator = await page.evaluate(() => {
      const body = document.body.innerText;
      return body.includes('جولة') || body.includes('بطولة') || body.includes('🏆');
    });
    console.log(`   Tournament indicator: ${tourIndicator ? '✅' : '⚠️'}`);
  }

  // Step 9: Test the tournament toast notification
  console.log('\n🔟  Testing tournament toast notification...');
  await page.evaluate(async () => {
    const bus = await import('/public/js/core/bus.js');
    bus.emit('tournament:paired', {
      tournamentId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
      roundNumber: 2,
      opponentId: '2c2a5770-f080-4134-8557-b24901635638',
      pairingIndex: 0
    });
  });
  await delay(1500);
  await shot(page, 'toast-notification');

  const toastVisible = await page.evaluate(() => {
    const toasts = document.querySelectorAll('[style*="position:fixed"], [style*="position: fixed"]');
    for (const t of toasts) {
      if (t.textContent.includes('جولة') || t.textContent.includes('بطولة') || t.textContent.includes('العب')) {
        return t.textContent.substring(0, 100);
      }
    }
    return null;
  });
  console.log(`   Toast: ${toastVisible ? `✅ "${toastVisible}"` : '⚠️ Not visible'}`);

  // Step 10: Test HUD badge
  console.log('\n1️⃣1️⃣  Testing HUD tournament badge...');
  await page.evaluate(async () => {
    const bus = await import('/public/js/core/bus.js');
    bus.emit('tournament:pending-updated', [
      { tournament_id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890', round_number: 1 }
    ]);
  });
  await delay(500);
  await shot(page, 'hud-badge');

  const badgeVisible = await page.evaluate(() => {
    const dots = document.querySelectorAll('[style*="background"][style*="border-radius"]');
    for (const d of dots) {
      if (d.offsetWidth <= 10 && d.offsetHeight <= 10) return true;
    }
    return false;
  });
  console.log(`   HUD badge dot: ${badgeVisible ? '✅' : '⚠️ Not detected'}`);

  // Step 11: Test Live tournament scene with our tournament
  console.log('\n1️⃣2️⃣  Testing Live tournament scene...');
  await page.evaluate(async (tid) => {
    const scene = await import('/public/js/core/scene.js');
    scene.push('tournament-live', { tournamentId: tid, tournamentName: 'بطولة سويسرية تجريبية' });
  }, TOURNAMENT_ID);
  await delay(3000);
  await shot(page, 'tournament-live');

  const liveContent = await page.evaluate(() => {
    return document.querySelector('#live-content')?.innerText?.substring(0, 200) || '';
  });
  console.log(`   Live content: ${liveContent.substring(0, 80)}`);

  // Final summary
  console.log('\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
  console.log(`✅ ${step} screenshots saved to test-screenshots/swiss-flow/`);
  console.log(`\n📊 Console Errors (${errors.length}):`);
  if (errors.length > 0) {
    errors.slice(0, 10).forEach(e => console.log(`   ❌ ${e.substring(0, 120)}`));
    if (errors.length > 10) console.log(`   ... and ${errors.length - 10} more`);
  } else {
    console.log('   None! 🎉');
  }
  console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');

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