import { test, expect, type Page } from '@playwright/test';
import {
    BASE_URL, USER, AGENT, ADMIN, loginAs, registerUserWithReferralCode,
    createPaymentDetail, requestDeposit, approveNewestDepositOf,
} from '../helpers';

// Every agent portal page opens with a banner: how many of the agent's DIRECT
// players are active (loaded in the last 30 days) vs inactive, and the %.
// AGENT (+10000000002, referral code ABCDEF01) already has direct players from
// the fixtures and other specs on the shared DB, so this test works with deltas.

type Counts = { active: number; total: number; inactive: number; percent: number };

async function readBanner(page: Page): Promise<Counts> {
    const banner = page.locator('[data-testid="agent-player-activity-banner"]');
    await expect(banner).toBeVisible();
    const num = async (id: string) => Number((await banner.locator(`[data-testid="agent-activity-${id}"]`).innerText()).replace('%', ''));
    return { active: await num('active'), total: await num('total'), inactive: await num('inactive'), percent: await num('percent') };
}

function expectConsistent(c: Counts): void {
    expect(c.active + c.inactive).toBe(c.total);
    expect(c.percent).toBe(Math.round((c.active / c.total) * 100));
}

test.describe('Agent Portal — active direct players banner', () => {
    test.setTimeout(150_000);

    test.beforeEach(async ({ page }) => {
        // Accepts the WFBO "Approve this deposit?" confirm.
        page.on('dialog', (d) => { d.accept().catch(() => {}); });
    });

    test('shows active vs inactive direct players on every portal page and follows new players and loads', async ({ page }, testInfo) => {
        await loginAs(page, AGENT.mobile, AGENT.password);
        await page.goto(`${BASE_URL}/agent/dashboard`);
        const before = await readBanner(page);
        expectConsistent(before);
        await expect(page.locator('[data-testid="agent-player-activity-banner"]')).toContainText('Active = loaded in the last 30 days');

        // A new direct player who never loaded: one more player, one more inactive.
        const player = await registerUserWithReferralCode(page, 'ABCDEF01');
        await loginAs(page, AGENT.mobile, AGENT.password);
        await page.goto(`${BASE_URL}/agent/dashboard`);
        const joined = await readBanner(page);
        expect(joined.total).toBe(before.total + 1);
        expect(joined.inactive).toBe(before.inactive + 1);
        expect(joined.active).toBe(before.active);

        // They load (approved deposit): now active.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        const account = await createPaymentDetail(page, `Activity ${Date.now()}`);
        await loginAs(page, player.mobile, player.password);
        await requestDeposit(page, account, '500');
        await approveNewestDepositOf(page, player.mobile);

        await loginAs(page, AGENT.mobile, AGENT.password);
        for (const [label, path] of [['dashboard', '/agent/dashboard'], ['downline', '/agent/downline'], ['player-monitor', '/agent/player-monitor'], ['insight', '/agent/insight']] as const) {
            await page.goto(`${BASE_URL}${path}`);
            const after = await readBanner(page);
            expect(after.total).toBe(before.total + 1);
            expect(after.active).toBe(before.active + 1);
            expect(after.inactive).toBe(before.inactive);
            expectConsistent(after);
            const level = after.percent >= 60 ? 'good' : after.percent >= 30 ? 'warn' : 'low';
            await expect(page.locator('[data-testid="agent-player-activity-banner"]')).toHaveAttribute('data-level', level);
            await page.screenshot({ path: testInfo.outputPath(`agent-activity-${label}-desktop.png`) });
        }

        // On a phone, and the link opens the Player Monitor.
        await page.setViewportSize({ width: 390, height: 844 });
        await page.goto(`${BASE_URL}/agent/dashboard`);
        await expect(page.locator('[data-testid="agent-player-activity-banner"]')).toBeVisible();
        expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
        await page.screenshot({ path: testInfo.outputPath('agent-activity-dashboard-phone.png') });
        await page.click('[data-testid="agent-activity-link"]');
        await expect(page).toHaveURL(/\/agent\/player-monitor\?scope=direct/);
        await expect(page.locator('[data-testid="agent-player-monitor-title"]')).toBeVisible();
    });

    test('players never see the banner', async ({ page }) => {
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/`);
        await expect(page.locator('[data-testid="agent-player-activity-banner"]')).toHaveCount(0);
    });
});
