"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayPage = void 0;
const test_1 = require("@playwright/test");
const clickLocatorWithRetry_1 = require("../../utils/assertionHelpers/clickLocatorWithRetry");
const maxWaitTimeSeconds = 180000;
class PlayPage {
    page;
    diagram;
    playTab;
    completeJobButton;
    configureTestPanel;
    configureTestPanelStartButton;
    startInstanceOverlayButton;
    constructor(page) {
        this.page = page;
        this.diagram = page.getByTestId('diagram');
        this.playTab = page.getByRole('tab', { name: 'Play' });
        this.completeJobButton = this.diagram.getByLabel('Complete job');
        // Newer Modeler Play UI: the "Configure Scenario" floating card hosts a
        // primary "Start" Carbon button (variants: "Start", "Start with
        // variables", "Start with a form"). Source:
        // camunda-hub frontend/packages/modeler/play/src/Definition/
        //   ConfigureTestPanel/index.tsx — renders <FloatingCard
        //   data-testid="configure-test-panel"> with a <Button> whose visible
        //   text starts with "Start".
        this.configureTestPanel = page.getByTestId('configure-test-panel');
        this.configureTestPanelStartButton = this.configureTestPanel.getByRole('button', { name: /^Start( with .*)?$/, exact: false });
        // Legacy bpmn-js canvas overlay button (still emitted by older Modeler
        // builds, also relabeled with cached/example-data suffixes). Kept as a
        // fallback for environments that haven't shipped the ConfigureTestPanel
        // yet.
        this.startInstanceOverlayButton = this.diagram.getByLabel('Start instance', { exact: false });
    }
    async waitForCompleteJobButtonToBeAvailable() {
        await (0, test_1.expect)(this.completeJobButton).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
        await (0, test_1.expect)(this.completeJobButton).toBeEnabled({
            timeout: maxWaitTimeSeconds,
        });
    }
    async clickCompleteJobButton() {
        await this.completeJobButton.click();
    }
    async clickStartInstanceButton() {
        // The Modeler Play UI has two surfaces that can hold the start trigger:
        //   - new: a "Start" Carbon button inside the ConfigureTestPanel
        //     floating card (`[data-testid="configure-test-panel"]`). This is
        //     what newer Modeler builds render. Variants: "Start",
        //     "Start with variables", "Start with a form".
        //   - legacy: a bpmn-js canvas overlay labelled "Start instance"
        //     (sometimes "Start instance with cached data" once a scenario
        //     chip exists). Older Modeler builds emit this; newer builds do
        //     not, so it cannot be the only locator.
        //
        // Try whichever appears first. On total failure, reload AND re-open
        // the Play tab (the legacy code path called `page.reload()` alone,
        // which dumped the user back on the Implement tab on stable/8.7).
        const startTrigger = this.configureTestPanelStartButton
            .or(this.startInstanceOverlayButton)
            .first();
        const tryClick = async () => {
            await (0, test_1.expect)(this.diagram).toBeVisible({ timeout: 120000 });
            await (0, clickLocatorWithRetry_1.clickLocatorWithRetry)(this.page, startTrigger, {
                totalTimeout: 240000,
                visibilityTimeout: 60000,
                maxRetries: 8,
                retryDelayMs: 5000,
            });
        };
        try {
            await tryClick();
        }
        catch (error) {
            console.warn(`clickStartInstanceButton: first pass failed (${error}); reloading, re-opening Play tab, and retrying once`);
            await this.page.reload();
            // After reload, the Modeler defaults to the Implement tab. Move
            // back to Play before trying again — otherwise the diagram
            // visibility check times out against the Implement-tab DOM.
            if (await this.playTab.isVisible({ timeout: 30000 }).catch(() => false)) {
                await this.playTab.click();
            }
            await tryClick();
        }
    }
    async dismissStartModal() {
        // The intro dialog cycles labels across Modeler versions/states.
        // Try the known variations in order; first match wins.
        const buttonVariations = [
            'Start a process instance',
            'Start another instance',
            'Start new instance',
            'Start instance',
        ];
        for (const buttonName of buttonVariations) {
            const button = this.page.getByRole('button', { name: buttonName });
            if ((await button.count()) > 0) {
                await button.first().click();
                return;
            }
        }
    }
    async waitForInstanceDetailsToBeLoaded() {
        const maxRetries = 2;
        let attempts = 0;
        while (attempts < maxRetries) {
            try {
                await (0, test_1.expect)(this.page.getByText(/process instance key|instance key/i).first()).toBeVisible({ timeout: maxWaitTimeSeconds });
                await (0, test_1.expect)(this.page
                    .getByText(/This process instance has no variables|No variables/i)
                    .first()).toBeVisible({ timeout: maxWaitTimeSeconds });
                return;
            }
            catch (error) {
                if (attempts >= maxRetries - 1)
                    throw error;
                await this.page.reload();
                attempts++;
            }
        }
    }
    async waitForNextElementToBeActive(historyItem) {
        await (0, test_1.expect)(this.page.getByText(new RegExp(`^${historyItem}`, 'i'))).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
    }
    async waitForProcessToBeCompleted() {
        await (0, test_1.expect)(this.page.getByText('Completed')).toBeVisible({
            timeout: maxWaitTimeSeconds,
        });
    }
}
exports.PlayPage = PlayPage;
