import puppeteer from 'puppeteer';

const BASE_URL = 'https://el3ab-player.caprover.al-arcade.com';
const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkMTRhMjdjNi0yNDQ4LTQzMTktYTc3NS1hOWY5NGRkNmRlODciLCJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNzgwNzMzOTIxLCJpYXQiOjE3ODA3MzAzMjEsImVtYWlsIjoidGVzdHBsYXllcjFAZWwzYWIuY29tIiwicGhvbmUiOiIiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJlbWFpbCIsInByb3ZpZGVycyI6WyJlbWFpbCJdfSwidXNlcl9tZXRhZGF0YSI6eyJkaXNwbGF5X25hbWUiOiLZhNin2LnYqCDYp9iu2KrYqNin2LEiLCJlbWFpbCI6InRlc3RwbGF5ZXIxQGVsM2FiLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaG9uZV92ZXJpZmllZCI6ZmFsc2UsInN1YiI6ImQxNGEyN2M2LTI0NDgtNDMxOS1hNzc1LWE5Zjk0ZGQ2ZGU4NyIsInVzZXJuYW1lIjoidGVzdHBsYXllcjEifSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJwYXNzd29yZCIsInRpbWVzdGFtcCI6MTc4MDczMDMyMX1dLCJzZXNzaW9uX2lkIjoiZjcxZDRmZDktOWU3YS00ZTk1LWIwNDItNzM2YmQ5MjIxODYyIiwiaXNfYW5vbnltb3VzIjpmYWxzZX0.xJmblxW4Kgf0vBZlDV6K8AOyolAOuijgMmz9z8De-58';
const USER_ID = 'd14a27c6-2448-4319-a775-a9f94dd6de87';
const wait = ms => new Promise(r => setTimeout(r, ms));

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

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

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

  console.log('1. Loading app...');
  await page.goto(BASE_URL, { waitUntil: 'networkidle2', timeout: 30000 });

  console.log('2. Injecting auth...');
  await page.evaluate((token, userId) => {
    localStorage.setItem('el3ab_state', JSON.stringify({
      auth: { token, refreshToken: '7emeg6xkuddg', userId },
      player: { id: userId, display_name: 'لاعب اختبار', username: 'testplayer1', level: 5, coins: 1000, xp: 500 },
      activeWorld: 'play', audioEnabled: false, language: 'ar'
    }));
  }, TOKEN, USER_ID);

  await page.reload({ waitUntil: 'networkidle2', timeout: 30000 });
  await wait(2000);
  console.log('3. Logged in');

  // Click domino game card
  console.log('4. Clicking domino card...');
  await page.click('[data-game="domino"]');
  await wait(1000);

  // Click "لاعب واحد" (single player button in popup)
  console.log('5. Clicking #btn-single...');
  const singleClicked = await page.evaluate(() => {
    const btn = document.querySelector('#btn-single');
    if (btn) { btn.click(); return 'clicked'; }
    return 'not found';
  });
  console.log('   Result:', singleClicked);
  await wait(1500);

  // Check for bot picker or game
  const state1 = await page.evaluate(() => ({
    text: document.body.innerText.slice(0, 300),
    hasBotPicker: document.body.innerText.includes('خبير'),
    hasGame: !!document.querySelector('#domino-wrap')
  }));
  console.log('6. After single:', state1.hasBotPicker ? 'BOT PICKER' : state1.hasGame ? 'GAME' : 'OTHER');
  console.log('   Text:', state1.text.slice(0, 150));
  await page.screenshot({ path: '/tmp/domino-step6.png' });

  // Click intermediate
  if (state1.hasBotPicker) {
    console.log('7. Clicking intermediate...');
    await page.evaluate(() => {
      const btns = [...document.querySelectorAll('[data-level], button')];
      const mid = btns.find(b => b.dataset?.level === 'intermediate' || b.textContent?.includes('متوسط'));
      if (mid) mid.click();
    });
    await wait(3000);
  }

  await page.screenshot({ path: '/tmp/domino-step7.png' });

  // ===== MAIN GAME STATE CHECK =====
  const gs = await page.evaluate(() => {
    const wrap = document.querySelector('#domino-wrap');
    const canvas = document.querySelector('canvas');
    const hand = document.querySelector('#domino-hand-area');
    const board = document.querySelector('#domino-board');
    const drawBtn = document.querySelector('#btn-draw');
    const turnEl = document.querySelector('#turn-status');
    const boneEl = document.querySelector('#boneyard-count');
    const oppEl = document.querySelector('#opp-count');
    const scoreEl = document.querySelector('#my-score');

    let handChildren = [];
    if (hand) {
      handChildren = [...hand.children].map(c => ({
        tag: c.tagName,
        class: c.className,
        style: c.getAttribute('style')?.slice(0, 80),
        dataId: c.dataset?.tileId || c.getAttribute('data-tile-id') || '',
        childCount: c.children.length
      }));
    }

    return {
      hasWrap: !!wrap,
      wrapChildren: wrap ? wrap.children.length : 0,
      hasCanvas: !!canvas,
      canvasW: canvas?.width, canvasH: canvas?.height,
      hasBoard: !!board,
      boardChildren: board ? board.children.length : 0,
      hasHand: !!hand,
      handChildCount: hand ? hand.children.length : 0,
      handChildren: handChildren.slice(0, 10),
      hasDrawBtn: !!drawBtn,
      turnText: turnEl?.textContent,
      boneText: boneEl?.textContent,
      oppText: oppEl?.textContent,
      scoreText: scoreEl?.textContent,
      fullHTML: document.querySelector('#domino-wrap')?.innerHTML?.slice(0, 800) || document.body.innerHTML.slice(0, 800)
    };
  });

  console.log('\n======= GAME STATE =======');
  console.log('Has #domino-wrap:', gs.hasWrap, '| children:', gs.wrapChildren);
  console.log('Has canvas:', gs.hasCanvas, gs.canvasW + 'x' + gs.canvasH);
  console.log('Has #domino-board:', gs.hasBoard, '| children:', gs.boardChildren);
  console.log('Has #domino-hand-area:', gs.hasHand, '| children:', gs.handChildCount);
  console.log('Hand children:', JSON.stringify(gs.handChildren, null, 2));
  console.log('Has #btn-draw:', gs.hasDrawBtn);
  console.log('Turn:', gs.turnText);
  console.log('Boneyard:', gs.boneText);
  console.log('Opponent:', gs.oppText);
  console.log('Score:', gs.scoreText);

  if (!gs.hasWrap) {
    console.log('\nFull HTML preview:', gs.fullHTML.slice(0, 500));
  }

  // ===== TILE INTERACTION TEST =====
  if (gs.hasHand && gs.handChildCount > 0) {
    console.log('\n======= INTERACTION TEST =======');

    // Get first tile position
    const tileInfo = await page.evaluate(() => {
      const hand = document.querySelector('#domino-hand-area');
      if (!hand || !hand.children.length) return null;
      const firstTile = hand.children[0];
      const rect = firstTile.getBoundingClientRect();
      return {
        x: rect.x + rect.width / 2,
        y: rect.y + rect.height / 2,
        w: rect.width, h: rect.height,
        text: firstTile.textContent?.slice(0, 20),
        style: firstTile.getAttribute('style')?.slice(0, 80)
      };
    });
    console.log('First tile:', JSON.stringify(tileInfo));

    if (tileInfo && tileInfo.w > 0) {
      // TAP test
      console.log('\nA) TAP on tile...');
      await page.mouse.click(tileInfo.x, tileInfo.y);
      await wait(500);
      const afterTap = await page.evaluate(() => ({
        turnText: document.querySelector('#turn-status')?.textContent,
        handHTML: document.querySelector('#domino-hand-area')?.innerHTML?.slice(0, 200),
        canvasChanged: document.querySelector('canvas')?.toDataURL()?.length
      }));
      console.log('   After tap - turn:', afterTap.turnText);
      await page.screenshot({ path: '/tmp/domino-tap.png' });

      // DRAG test
      console.log('\nB) DRAG tile to board...');
      const boardPos = await page.evaluate(() => {
        const b = document.querySelector('#domino-board');
        if (!b) return null;
        const r = b.getBoundingClientRect();
        return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
      });

      if (boardPos) {
        await page.mouse.move(tileInfo.x, tileInfo.y);
        await page.mouse.down();
        // Move in steps
        const steps = 15;
        for (let i = 1; i <= steps; i++) {
          const p = i / steps;
          await page.mouse.move(
            tileInfo.x + (boardPos.x - tileInfo.x) * p,
            tileInfo.y + (boardPos.y - tileInfo.y) * p
          );
          await wait(20);
        }
        await wait(200);

        // Check for proxy/ghost
        const duringDrag = await page.evaluate(() => {
          const proxy = document.querySelector('.drag-proxy, .domino-drag-proxy, [style*="position: fixed"]');
          const ghost = document.querySelector('[style*="opacity: 0.5"], .ghost');
          return { hasProxy: !!proxy, hasGhost: !!ghost };
        });
        console.log('   During drag:', duringDrag);
        await page.screenshot({ path: '/tmp/domino-drag.png' });

        await page.mouse.up();
        await wait(1000);
        await page.screenshot({ path: '/tmp/domino-afterdrag.png' });
      }
    }
  }

  // Errors
  if (errors.length > 0) {
    console.log('\n======= JS ERRORS =======');
    errors.slice(0, 20).forEach(e => console.log('  ✗', e.slice(0, 300)));
  } else {
    console.log('\n✓ No JS errors');
  }

  await browser.close();
}

run().catch(e => { console.error('FATAL:', e.message); process.exit(1); });
