import { test, expect } from '@playwright/test';
import { fetchOpenDrawNo, tickDraws } from '../api/_helper';

const FRONT_URL = process.env.PLAYWRIGHT_FRONT_URL ?? 'http://localhost:3800';
const USER = process.env.E2E_PLAYER_USERNAME ?? 'demo_player';
const PASS = process.env.E2E_PLAYER_PASSWORD ?? '12345678';

async function loginToHall(page: import('@playwright/test').Page): Promise<void> {
  await page.goto(`${FRONT_URL}/login`);
  const userInput = page.locator('#login-user');
  await userInput.waitFor({ state: 'visible', timeout: 60_000 });
  await userInput.fill(USER);
  await page.locator('#login-pass').fill(PASS);
  await page.locator('img[src^="data:image"]').waitFor({ state: 'visible', timeout: 30_000 });
  await page.locator('#login-captcha').fill('LOTTERY_E2E_BYPASS');
  await page.getByRole('button', { name: /^登录$|Sign in|submit/i }).click();
  await page.waitForURL(/\/hall/, { timeout: 45_000 });
}

test('玩家端大厅 → 填写号码金额 → 预览并提交下注', async ({ page }) => {
  test.setTimeout(180_000);

  await fetchOpenDrawNo();
  await tickDraws();

  await loginToHall(page);

  const grid = page.getByRole('section', { name: /下注表格|Betting/i });
  await grid.waitFor({ state: 'visible', timeout: 60_000 });

  const numberInput = grid.locator('input[inputmode="text"]').first();
  await numberInput.waitFor({ state: 'visible', timeout: 30_000 });
  await numberInput.fill('12');

  const amountInput = grid.locator('input[inputmode="decimal"]').first();
  await amountInput.fill('10');

  const submitBtn = page.getByRole('button', { name: /提交下注|Submit bet/i });
  await expect(submitBtn).toBeEnabled({ timeout: 60_000 });
  await submitBtn.click();

  const confirmBtn = page.getByRole('button', { name: /确认提交|Confirm/i });
  await confirmBtn.waitFor({ state: 'visible', timeout: 30_000 });
  await confirmBtn.click();

  await expect(page.getByText(/下注成功|Bet placed|订单号|Order/i)).toBeVisible({
    timeout: 45_000,
  });
});
