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

// Agent Performance: each of the agent's own direct agents (a master's agents,
// an agent's sub-agents) with their direct players active vs inactive - active
// = loaded in the last 30 days, the same rule as the portal banner.
// Fixtures: "Sub Ken" (SUB_AGENT, referral SUBAAG01) sits under the master
// AGENT. Other specs may add players under Sub Ken, so this test uses deltas.

const PAGE = `${BASE_URL}/agent/agent-performance`;

type Row = { total: number; active: number; inactive: number; percent: string };

async function subKenRow(page: Page): Promise<{ id: string; row: Row }> {
    const tr = page.locator('[data-testid="agent-performance-table"] tbody tr', { hasText: 'Sub Ken' });
    await expect(tr).toBeVisible();
    const id = ((await tr.getAttribute('data-testid')) ?? '').replace('agent-performance-row-', '');
    const cell = (k: string) => page.locator(`[data-testid="agent-performance-${k}-${id}"]`).innerText();
    return {
        id,
        row: {
            total: Number(await cell('total')),
            active: Number(await cell('active')),
            inactive: Number(await cell('inactive')),
            percent: (await cell('percent')).trim(),
        },
    };
}

test.describe('Agent Portal — Agent Performance', () => {
    test.setTimeout(150_000);

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

    test('a master agent sees each agent\'s players active vs inactive, following new players and loads', async ({ page }, testInfo) => {
        await loginAs(page, AGENT.mobile, AGENT.password);
        await page.goto(`${BASE_URL}/agent/dashboard`);
        await page.click('text=Downline');
        await page.click('[data-testid="agent-nav-agent-performance"]');
        await expect(page).toHaveURL(PAGE);
        await expect(page.locator('[data-testid="agent-performance-title"]')).toBeVisible();
        // The portal banner is on this page too.
        await expect(page.locator('[data-testid="agent-player-activity-banner"]')).toBeVisible();
        const before = (await subKenRow(page)).row;
        expect(before.active + before.inactive).toBe(before.total);

        // A new player under Sub Ken who never loaded: +1 player, +1 inactive.
        const player = await registerUserWithReferralCode(page, 'SUBAAG01');
        await loginAs(page, AGENT.mobile, AGENT.password);
        await page.goto(PAGE);
        const joined = await subKenRow(page);
        expect(joined.row.total).toBe(before.total + 1);
        expect(joined.row.inactive).toBe(before.inactive + 1);
        expect(joined.row.active).toBe(before.active);

        // They load (approved deposit): now active.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        const account = await createPaymentDetail(page, `AgentPerf ${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);
        await page.goto(PAGE);
        const after = await subKenRow(page);
        expect(after.row.total).toBe(before.total + 1);
        expect(after.row.active).toBe(before.active + 1);
        expect(after.row.inactive).toBe(before.inactive);
        const pct = Math.round((after.row.active / after.row.total) * 100);
        expect(after.row.percent).toBe(`${pct}%`);
        await expect(page.locator(`[data-testid="agent-performance-row-${after.id}"]`))
            .toHaveAttribute('data-level', pct >= 60 ? 'good' : pct >= 30 ? 'warn' : 'low');

        // The summary cards add up the table.
        const cardValue = async (k: string) => (await page.locator(`[data-testid="agent-performance-card-${k}"] .stat-value--lg`).innerText()).trim();
        expect(Number(await cardValue('players'))).toBeGreaterThanOrEqual(after.row.total);
        expect(Number(await cardValue('active'))).toBeGreaterThanOrEqual(after.row.active);
        await page.screenshot({ path: testInfo.outputPath('agent-performance-desktop.png'), fullPage: true });

        // Sort pills and search.
        for (const sort of ['highest', 'players', 'lowest'] as const) {
            await page.click(`[data-testid="agent-performance-sort-${sort}"]`);
            await expect(page).toHaveURL(new RegExp(`sort=${sort}`));
            await expect(page.locator(`[data-testid="agent-performance-sort-${sort}"]`)).toHaveClass(/is-active/);
        }
        await page.fill('[data-testid="agent-performance-search"]', 'Sub Ken');
        await page.click('[data-testid="agent-performance-search-btn"]');
        await expect(page).toHaveURL(/search=Sub\+Ken/);
        await expect(page.locator('[data-testid="agent-performance-table"] tbody tr')).toHaveCount(1);
        await expect(page.locator('[data-testid="agent-performance-sort-lowest"]')).toHaveAttribute('href', /search=Sub/);
        await page.fill('[data-testid="agent-performance-search"]', 'nobody-like-this');
        await page.click('[data-testid="agent-performance-search-btn"]');
        await expect(page).toHaveURL(/search=nobody-like-this/);
        await expect(page.locator('[data-testid="agent-performance-empty"]')).toBeVisible();

        // Phone.
        await page.setViewportSize({ width: 390, height: 844 });
        await page.goto(PAGE);
        await expect(page.locator('[data-testid="agent-performance-table"]')).toBeVisible();
        await page.screenshot({ path: testInfo.outputPath('agent-performance-phone.png'), fullPage: true });
    });

    test('a sub-agent has no agents of their own: no menu item and the page is denied', async ({ page }) => {
        await loginAs(page, SUB_AGENT.mobile, SUB_AGENT.password);
        await page.goto(`${BASE_URL}/agent/dashboard`);
        await expect(page.locator('[data-testid="agent-nav-agent-performance"]')).toHaveCount(0);
        const res = await page.goto(PAGE);
        expect(res?.status()).toBe(403);
    });
});
