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

/**
 * Enables Fruit King (and the "smallest bet wins" house-profit toggle) and pins
 * the per-spin symbol limit to a known value so the play-page enforcement tests
 * below are deterministic regardless of what other specs may have persisted in
 * the settings row.
 */
async function ensureFruitKingConfigured(page: Page, maxSymbols: number) {
    await loginAs(page, ADMIN.mobile, ADMIN.password);
    await page.goto(`${BASE_URL}/wfbo/fruit-king/settings`, { waitUntil: 'domcontentloaded' });

    const toggle = page.locator('[data-testid="toggle-fk-enabled"]');
    if (!(await toggle.isChecked())) {
        await toggle.check();
    }
    const safeWinToggle = page.locator('[data-testid="toggle-fk-smallest-bet-wins"]');
    if (!(await safeWinToggle.isChecked())) {
        await safeWinToggle.check();
    }
    await page.fill('[data-testid="input-fk-max-symbols-per-spin"]', String(maxSymbols));
    await page.click('[data-testid="btn-save-fk-settings"]');
    await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();
}

async function placeBet(page: Page, symbol: string) {
    await page.click(`[data-testid="fk-bet-btn-${symbol}"]`);
    await expect(page.locator('[data-testid="fk-bet-modal"]')).toBeVisible();
    await page.click('[data-testid="fk-bet-preset-1"]');
    await expect(page.locator('[data-testid="fk-bet-modal"]')).toBeHidden();
}

async function placeBetAmount(page: Page, symbol: string, amount: number) {
    await page.click(`[data-testid="fk-bet-btn-${symbol}"]`);
    await expect(page.locator('[data-testid="fk-bet-modal"]')).toBeVisible();
    await page.fill('[data-testid="fk-bet-custom-input"]', String(amount));
    await page.click('[data-testid="fk-bet-custom-btn"]');
    await expect(page.locator('[data-testid="fk-bet-modal"]')).toBeHidden();
}

test.describe('Fruit King — Max Symbols per Spin', () => {

    test.beforeEach(async ({ page }) => {
        await ensureFruitKingConfigured(page, 4);
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/fruit-king`, { waitUntil: 'domcontentloaded' });
        await expect(page.locator('[data-testid="fruit-king-page"]')).toBeVisible();
    });

    test('how-to overlay states the configured symbol limit', async ({ page }) => {
        await page.click('[data-testid="btn-fk-howto"]');
        const overlay = page.locator('[data-testid="fk-howto-overlay"]');
        await expect(overlay).toBeVisible();
        await expect(page.locator('#howtoMaxSymbols')).toHaveText('4');
        await expect(overlay).toContainText('Bet on up to 4 different symbols per spin.');
    });

    test('player can bet on up to the limit and is blocked past it', async ({ page }) => {
        const symbols = ['apple', 'bell', 'mango', 'orange'];

        for (const symbol of symbols) {
            await placeBet(page, symbol);
        }

        const dialogPromise = page.waitForEvent('dialog');
        const clickPromise  = page.click('[data-testid="fk-bet-btn-seven"]');

        const dialog = await dialogPromise;
        expect(dialog.message()).toContain('You can only bet on up to 4 symbols per spin.');
        await dialog.accept();
        await clickPromise;

        await expect(page.locator('[data-testid="fk-bet-modal"]')).toBeHidden();
    });

    test('multi-symbol spin wins the smallest safe bet below the total bet', async ({ page }) => {
        // Force player-favored spins (HWR 0) so the safe-win path is deterministic.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/fruit-king/settings`, { waitUntil: 'domcontentloaded' });
        await page.fill('[data-testid="input-fk-house-win-rate"]', '0');
        await page.click('[data-testid="btn-save-fk-settings"]');
        await expect(page.locator('[data-testid="flash-success"]')).toBeVisible();

        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/fruit-king`, { waitUntil: 'domcontentloaded' });
        await expect(page.locator('[data-testid="fruit-king-page"]')).toBeVisible();

        // Total ₱51: apple ₱50 + mango ₱1. Smallest safe bet is mango (₱1 × 10 = ₱10 < ₱51);
        // apple (₱50 × 5 = ₱250) is not safe. The wheel must land on mango.
        await placeBetAmount(page, 'apple', 50);
        await placeBetAmount(page, 'mango', 1);

        const responsePromise = page.waitForResponse(
            res => res.url().includes('/fruit-king/bet') && res.request().method() === 'POST',
        );
        await page.click('[data-testid="btn-fk-spin"]');
        const response = await responsePromise;
        expect(response.status()).toBe(200);

        const data = await response.json();
        expect(data.success).toBe(true);
        expect(data.outcome.symbol).toBe('mango');
        expect(data.outcome.tier).toBe('single');

        const mango = data.bets.find((b: { symbol: string }) => b.symbol === 'mango');
        const apple = data.bets.find((b: { symbol: string }) => b.symbol === 'apple');
        expect(mango.status).toBe('won');
        expect(Number(mango.payout)).toBe(10);
        expect(apple.status).toBe('lost');

        const totalBet = 51;
        expect(Number(mango.payout)).toBeLessThan(totalBet);
        expect(Number(data.walletBalance)).toBeLessThan(5000);
    });

});
