import { test, expect, type Page } from '@playwright/test';
import { execFileSync } from 'child_process';
import {
    BASE_URL,
    ADMIN,
    FINANCE,
    loginAs,
    configurePusoy,
    newPlayer,
    leaveAll,
    type PusoyTestPlayer,
} from '../helpers';

// The standalone Pusoy Dos wall monitor: /wfbo/pusoy/monitor (shell) and
// /wfbo/pusoy/monitor/data (the bare fragment it re-polls every 3s). Every open
// table is drawn with its seats - card counts only while a hand is played, so
// nobody watching can read a player's hand - plus players, chat and today's money.

const MONITOR = `${BASE_URL}/wfbo/pusoy/monitor`;

async function playHandToTheEnd(page: Page): Promise<void> {
    const result = page.locator('[data-testid="pd-result"]');
    const deadline = Date.now() + 150_000;

    while (Date.now() < deadline) {
        if (await result.isVisible()) {
            return;
        }
        const pass = page.locator('[data-testid="pd-pass"]');
        if (await pass.isEnabled()) {
            await pass.click();
        } else if ((await page.locator('[data-testid="pd-banner"]').textContent())?.includes('YOUR LEAD')) {
            // The glowing card is the one to open with (the 3♣, or the lowest card dealt when it is face down).
            const opening = page.locator('[data-testid="pd-hand"] [data-hint="1"]');
            const card = (await opening.count()) > 0 ? opening.first() : page.locator('[data-testid="pd-hand"] [data-testid^="pd-card-"]').first();
            await card.click();
            await page.click('[data-testid="pd-play"]');
        }
        await page.waitForTimeout(500);
    }
    throw new Error('The hand did not finish in time.');
}

test.describe.serial('WFBO — Pusoy Dos live monitor', () => {
    test.setTimeout(240_000);

    test.beforeAll(async ({ browser }) => {
        const page = await browser.newPage();
        await configurePusoy(page, { enabled: true });
        await page.close();
    });

    test.afterAll(async ({ browser }) => {
        const page = await browser.newPage();
        await configurePusoy(page, { enabled: false, testUsersOnly: true, seats: '4' });
        await page.close();
    });

    test('admins open it from Games ▸ Pusoy; finance staff cannot', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/games/pusoy`);
        const card = page.locator('[data-testid="pd-hub-monitor"]');
        await expect(card).toBeVisible();
        await expect(card).toHaveAttribute('href', '/wfbo/pusoy/monitor');
        await expect(card).toHaveAttribute('target', '_blank');

        await page.goto(MONITOR);
        await expect(page.locator('[data-testid="pd-monitor"]')).toBeVisible();
        await expect(page.locator('[data-testid="pd-monitor-live"]')).toBeAttached();
        // A bare wall screen: no WFBO sidebar.
        await expect(page.locator('.wfbo-sidebar')).toHaveCount(0);
        for (const kpi of ['entries', 'payouts', 'fee', 'revenue', 'hands', 'online', 'tables', 'queue']) {
            await expect(page.locator(`[data-testid="pd-mon-kpi-${kpi}"]`)).toBeVisible();
        }
        await expect(page.locator('[data-testid="pd-mon-chat"]')).toBeVisible();
        await expect(page.locator('[data-testid="pd-mon-players"]')).toBeVisible();
        // Nothing picked yet: the game view asks for a table.
        await expect(page.locator('[data-testid="pd-mon-game-empty"]')).toContainText('Pick a table to watch the game');

        // The polled fragment is just the live region - no page chrome.
        const res = await page.request.get(`${MONITOR}/data`);
        expect(res.status()).toBe(200);
        const html = await res.text();
        expect(html).toContain('data-testid="pd-mon-kpis"');
        expect(html).not.toContain('<html');

        await loginAs(page, FINANCE.mobile, FINANCE.password);
        expect((await page.goto(MONITOR))?.status()).toBe(403);
        expect((await page.request.get(`${MONITOR}/data`)).status()).toBe(403);
    });

    test('playing tables are listed; clicking one opens the game: seats with card counts but no faces, plays, chat as typed', async ({ page, browser }, testInfo) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(MONITOR);

        const players: PusoyTestPlayer[] = [await newPlayer(browser), await newPlayer(browser), await newPlayer(browser)];
        for (const p of players) {
            await p.page.click('[data-testid="pd-join-bronze"]');
        }
        await expect.poll(async () => players[0].page.locator('[data-testid="pd-hand"] [data-testid^="pd-card-"]').count(), { timeout: 20_000 }).toBeGreaterThanOrEqual(17);

        // The monitor lists the table on its own (3s poll) - no reload - with its
        // players and card counts, but the game itself only opens once it is clicked.
        const row = page.locator('[data-testid^="pd-mon-table-"][data-status="playing"]').first();
        await expect(row).toBeVisible({ timeout: 10_000 });
        const tableId = (await row.getAttribute('data-testid'))!.replace('pd-mon-table-', '');
        await expect(page.locator('[data-testid="pd-mon-tables"]')).toContainText('Playing tables (1)');
        await expect(row).toContainText('bronze');
        await expect(row).toContainText('Pot ₱270.00');
        await expect(row).toContainText('Test U.');
        await expect(page.locator(`[data-testid="pd-mon-felt-${tableId}"]`)).toHaveCount(0);
        await expect(page.locator('[data-testid="pd-mon-player-row"]')).toHaveCount(3);
        await expect(page.locator('[data-testid="pd-mon-kpi-online"]')).toContainText('3');

        // Chat: staff see the original words, flagged when players get them masked.
        const talker = players[1].page;
        await talker.click('[data-testid="pd-chat-toggle"]');
        await talker.fill('[data-testid="pd-chat-input"]', 'ang bobo mo');
        await talker.click('[data-testid="pd-chat-send"]');
        const chatRow = page.locator('[data-testid="pd-mon-chat-row"]').filter({ hasText: 'ang bobo mo' });
        await expect(chatRow).toBeVisible({ timeout: 10_000 });
        await expect(chatRow).toContainText('Flagged');

        // Clicking the table opens the game: the felt with every seat, its plays and its chat.
        await row.click();
        const focus = page.locator('[data-testid="pd-mon-game"]');
        await expect(focus).toContainText(`Table #${tableId}`);
        await expect(page).toHaveURL(new RegExp(`table=${tableId}`));
        await expect(page.locator(`[data-testid="pd-mon-felt-${tableId}"]`)).toBeVisible();
        for (const seat of [0, 1, 2]) {
            await expect(page.locator(`[data-testid="pd-mon-seat-${tableId}-${seat}"]`)).toContainText('Test U.');
            await expect(page.locator(`[data-testid="pd-mon-seat-count-${tableId}-${seat}"]`)).toHaveText(/^\s*\d+\s*$/);
        }
        // Card faces stay hidden mid-hand.
        await expect(page.locator(`[data-testid^="pd-mon-seat-left-${tableId}-"]`)).toHaveCount(0);
        await expect(focus.locator('[data-testid="pd-mon-focus-chat"]')).toContainText('ang bobo mo');
        await expect(focus.locator('[data-testid="pd-mon-focus-hand"]')).toBeVisible();
        // Players stay listed below the game while a table is being watched.
        await expect(page.locator('[data-testid="pd-mon-players"]')).toBeVisible();
        await expect(page.locator('[data-testid="pd-mon-player-row"]')).toHaveCount(3);
        await expect(page.locator('[data-testid="pd-mon-recent"]')).toBeVisible();

        // Play a few turns, then check the plays show while faces stay hidden.
        const playing = Promise.all(players.map(p => playHandToTheEnd(p.page)));
        await expect(focus.locator('[data-testid="pd-mon-focus-move"]').first()).toBeVisible({ timeout: 30_000 });
        await expect(page.locator(`[data-testid^="pd-mon-seat-left-${tableId}-"]`)).toHaveCount(0);
        await page.screenshot({ path: testInfo.outputPath('pusoy-monitor-live-table.png') });

        await playing;
        // After the hand the seats show their leftover cards and the winner.
        await expect(page.locator(`[data-testid="pd-mon-felt-${tableId}"]`)).toContainText('Won ₱270.00', { timeout: 10_000 });
        await expect(page.locator(`[data-testid^="pd-mon-seat-left-${tableId}-"]`)).toHaveCount(2);
        // The settled hand shows in the recent list with its winner while the table is still open.
        const recent = page.locator('[data-testid="pd-mon-recent-row"]').first();
        await expect(recent).toBeVisible({ timeout: 10_000 });
        await expect(recent).toContainText('Test U.');
        await expect(page.locator('[data-testid="pd-mon-players"]')).toBeVisible();
        await page.screenshot({ path: testInfo.outputPath('pusoy-monitor-after-hand.png') });

        // Close goes back to the list.
        await page.click('[data-testid="pd-mon-focus-close"]');
        await expect(page.locator('[data-testid="pd-mon-game-empty"]')).toBeVisible();
        await expect(page).not.toHaveURL(/table=/);

        await leaveAll(players);
    });

    test('only a table nobody is at can be deleted', async ({ page, browser }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(MONITOR);

        // One player waiting alone at a fresh 3-seat table: no Delete while they are there.
        const [player] = [await newPlayer(browser)];
        await player.page.click('[data-testid="pd-join-bronze"]');
        await expect(player.page.locator('[data-testid="pd-banner"]')).toContainText('1 of 3', { timeout: 15_000 });
        const row = page.locator('[data-testid^="pd-mon-table-"][data-status="waiting"]').filter({ hasText: 'Test U.' }).first();
        await expect(row).toBeVisible({ timeout: 10_000 });
        const tableId = (await row.getAttribute('data-testid'))!.replace('pd-mon-table-', '');
        await expect(page.locator(`[data-testid="pd-mon-delete-${tableId}"]`)).toHaveCount(0);
        // The server refuses too, even if asked directly.
        const token = await page.locator('[data-testid="pd-monitor"]').getAttribute('data-pd-monitor-close-token-value');
        const refused = await page.request.post(`${MONITOR}/tables/${tableId}/close`, { form: { _token: token! } });
        expect(refused.status()).toBe(409);
        expect((await refused.json()).message).toBe('Players are still at this table.');

        // The player leaves: the empty table can now be deleted.
        await leaveAll([player]);
        const del = page.locator(`[data-testid="pd-mon-delete-${tableId}"]`);
        await expect(del).toBeVisible({ timeout: 10_000 });
        page.once('dialog', d => d.accept());
        await del.click();
        await expect(page.locator('[data-testid="pd-mon-notice"]')).toHaveText(`Table #${tableId} deleted.`);
        await expect(page.locator(`[data-testid="pd-mon-table-${tableId}"]`)).toHaveCount(0);
        // Gone for good: asking again says it is closed.
        const again = await page.request.post(`${MONITOR}/tables/${tableId}/close`, { form: { _token: token! } });
        expect((await again.json()).message).toBe('That table is already closed.');
    });
    test('Kick offline removes players not seen for 10 minutes and keeps everyone else', async ({ page, browser }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(MONITOR);

        const [gone, here] = [await newPlayer(browser), await newPlayer(browser)];
        await gone.page.click('[data-testid="pd-join-bronze"]');
        await here.page.click('[data-testid="pd-join-bronze"]');
        await expect(here.page.locator('[data-testid="pd-banner"]')).toContainText('2 of 3', { timeout: 15_000 });

        // One of them closes the app, and was last seen 11 minutes ago.
        await gone.ctx.close();
        execFileSync('php', ['bin/console', 'dbal:run-sql',
            `UPDATE pusoy_player p JOIN user u ON u.id = p.user_id SET p.last_seen_at = DATE_SUB(p.last_seen_at, INTERVAL 11 MINUTE) WHERE u.mobile_number = '${gone.mobile}'`]);

        const kick = page.locator('[data-testid="pd-mon-kick-offline"]');
        await expect(kick).toHaveText('Kick offline 10m+ (1)', { timeout: 10_000 });
        await expect(kick).toBeEnabled();
        await expect(page.locator('[data-testid="pd-mon-player-row"]')).toHaveCount(2);
        page.once('dialog', d => d.accept());
        await kick.click();
        await expect(page.locator('[data-testid="pd-mon-notice"]')).toHaveText('Kicked 1 offline player.');

        // Only the player still around is left, at the same table.
        await expect(page.locator('[data-testid="pd-mon-player-row"]')).toHaveCount(1);
        await expect(kick).toHaveText('Kick offline 10m+ (0)');
        await expect(kick).toBeDisabled();
        await expect(here.page.locator('[data-testid="pd-banner"]')).toContainText('1 of 3', { timeout: 10_000 });
        await page.screenshot({ path: test.info().outputPath('pusoy-monitor-kick-offline.png') });

        // Asked again with nobody offline that long, nothing happens.
        const token = await page.locator('[data-testid="pd-monitor"]').getAttribute('data-pd-monitor-kick-token-value');
        const again = await page.request.post(`${MONITOR}/kick-offline`, { form: { _token: token! } });
        expect((await again.json()).message).toBe('Nobody has been offline for 10 minutes.');

        await leaveAll([here]);
    });

    test('staff move a waiting player to another table to fill it, and it deals; nobody mid-hand can be moved', async ({ page, browser }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(MONITOR);
        const tableOf = async (p: PusoyTestPlayer): Promise<number> =>
            (await (await p.page.request.get(`${BASE_URL}/play/pusoy/state`)).json()).tableId as number;
        const setStatus = (id: number, status: string): void => {
            execFileSync('php', ['bin/console', 'dbal:run-sql', `UPDATE pusoy_table SET status = '${status}' WHERE id = ${id}`]);
        };

        // Two Bronze tables waiting for players: one alone at the first, two at the second.
        // (Players fill the first table with room, so the first is closed for a moment while the others sit down.)
        const lone = await newPlayer(browser);
        await lone.page.click('[data-testid="pd-join-bronze"]');
        await expect(lone.page.locator('[data-testid="pd-banner"]')).toContainText('1 of 3', { timeout: 15_000 });
        const fromId = await tableOf(lone);
        setStatus(fromId, 'closed');
        const pair = [await newPlayer(browser), await newPlayer(browser)];
        for (const p of pair) {
            await p.page.click('[data-testid="pd-join-bronze"]');
        }
        await expect(pair[1].page.locator('[data-testid="pd-banner"]')).toContainText('2 of 3', { timeout: 15_000 });
        setStatus(fromId, 'open');
        const toId = await tableOf(pair[0]);
        expect(toId).not.toBe(fromId);

        // The lone player's row has Move; the box lists the other table, which one more player fills.
        const row = page.locator('[data-testid="pd-mon-player-row"]').filter({ hasText: `#${fromId}` });
        const moveBtn = row.locator('[data-testid^="pd-mon-move-"]');
        await expect(moveBtn).toBeVisible({ timeout: 10_000 });
        const userId = (await moveBtn.getAttribute('data-testid'))!.replace('pd-mon-move-', '');
        await moveBtn.click();
        const target = page.locator(`[data-testid="pd-mon-move-to-${toId}"]`);
        await expect(target).toHaveText(`Table #${toId} · bronze · 2/3 players - fills it, deals now`);
        // The box stays open across the 3s refresh.
        await page.waitForTimeout(3_500);
        await expect(page.locator('[data-testid="pd-mon-movebox"]')).toBeVisible();
        await page.screenshot({ path: test.info().outputPath('pusoy-monitor-move-box.png') });
        await target.click();
        await expect(page.locator('[data-testid="pd-mon-notice"]')).toHaveText(`Moved Test U. to table #${toId} - the table is full, dealing now.`);
        await expect(page.locator('[data-testid="pd-mon-movebox"]')).toBeHidden();

        // The moved player is told, and the full table deals to all three.
        await expect(lone.page.locator('.pd-toast')).toContainText(`You were moved to table #${toId}`, { timeout: 10_000 });
        for (const p of [lone, ...pair]) {
            await expect.poll(async () => p.page.locator('[data-testid="pd-hand"] [data-testid^="pd-card-"]').count(), { timeout: 20_000 }).toBeGreaterThanOrEqual(17);
        }
        await expect(page.locator(`[data-testid="pd-mon-table-status-${toId}"]`)).toHaveText('playing', { timeout: 10_000 });
        // The old table is empty: it can be deleted. Mid-hand, nobody at the table has a Move button.
        await expect(page.locator(`[data-testid="pd-mon-delete-${fromId}"]`)).toBeVisible();
        const dealtRows = page.locator('[data-testid="pd-mon-player-row"]').filter({ hasText: `#${toId}` });
        await expect(dealtRows).toHaveCount(3);
        await expect(dealtRows.locator('[data-testid^="pd-mon-move-"]')).toHaveCount(0);
        await page.screenshot({ path: test.info().outputPath('pusoy-monitor-moved-and-dealt.png') });

        // The server refuses a mid-hand move too, even if asked directly.
        const token = await page.locator('[data-testid="pd-monitor"]').getAttribute('data-pd-monitor-move-token-value');
        const refused = await page.request.post(`${MONITOR}/players/${userId}/move`, { form: { _token: token!, target: String(fromId) } });
        expect(refused.status()).toBe(409);
        expect((await refused.json()).message).toBe(`A hand is being played at table #${toId}.`);

        await leaveAll([lone, ...pair]);
    });
});
