import { expect } from "@playwright/test";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { Locator, Page } from "playwright";
import { logger } from "@formbricks/logger";
import { clickUntil, clickUntilVisible } from "@/playwright/utils/click-until";
import { CreateSurveyParams, CreateSurveyWithLogicParams } from "@/playwright/utils/mock";

const MOCK_STORAGE_UPLOAD_PATH = "/__playwright__/mock-storage-upload";
const SURVEY_CREATE_API_PATHS = new Set(["/api/v3/surveys", "/api/v3/surveys/templates"]);

type MockStorageFileFixture = {
  name: string;
  mimeType: string;
  buffer: Buffer;
  publicAssetPath?: string;
};

/**
 * Sets a Set value action's Expression switch to `on`, reading it first, so a step does what it says
 * whatever a new Set value starts as (that default has changed before: P73, P74).
 */
export const setExpressionMode = async (page: Page, actionIdx: number, on: boolean): Promise<void> => {
  const toggle = page.locator(`#action-${actionIdx}-formula-toggle`).first();
  if ((await toggle.getAttribute("aria-checked")) !== String(on)) await toggle.click();
};

export const PLAYWRIGHT_PICTURE_SELECTION_FILES: MockStorageFileFixture[] = [
  {
    name: "playwright-choice-1.png",
    mimeType: "image/png",
    buffer: readFileSync(resolve(process.cwd(), "apps/web/public/logo-transparent.png")),
    publicAssetPath: "/logo-transparent.png",
  },
  {
    name: "playwright-choice-2.png",
    mimeType: "image/png",
    buffer: readFileSync(resolve(process.cwd(), "apps/web/public/favicon/android-chrome-192x192.png")),
    publicAssetPath: "/favicon/android-chrome-192x192.png",
  },
];

const PLAYWRIGHT_STORAGE_FILE_FIXTURES = new Map(
  PLAYWRIGHT_PICTURE_SELECTION_FILES.map((file) => [file.name, file] as const)
);

const DEFAULT_MOCK_STORAGE_FILE_FIXTURE: MockStorageFileFixture = {
  name: "mock-file.svg",
  mimeType: "image/svg+xml",
  buffer: Buffer.from(
    `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#0f172a"/><circle cx="32" cy="32" r="18" fill="#22c55e"/></svg>`,
    "utf8"
  ),
};

export const waitForSurveyCreateResponse = async (page: Page): Promise<string> => {
  const response = await page.waitForResponse((response) => {
    const url = new URL(response.url());

    return SURVEY_CREATE_API_PATHS.has(url.pathname) && response.request().method() === "POST";
  });
  const responseBody = await response.json().catch(() => null);
  expect(response.status(), JSON.stringify(responseBody)).toBe(201);

  const surveyId = (responseBody as { data?: { id?: unknown } } | null)?.data?.id;
  if (typeof surveyId !== "string") {
    throw new TypeError("Survey create response did not include a survey id");
  }

  return surveyId;
};

export const waitForSurveyEditor = async (
  page: Page,
  surveyId: string,
  options: { mode?: "cx" } = {}
): Promise<void> => {
  const editorUrlPattern = new RegExp(`/workspaces/[^/]+/surveys/${surveyId}/edit(?:\\?.*)?$`);
  const currentUrl = new URL(page.url());

  if (!editorUrlPattern.test(`${currentUrl.pathname}${currentUrl.search}`)) {
    await page.waitForURL(editorUrlPattern);
  }
  // The route has a loading skeleton, so the URL changes as soon as the skeleton shows, before the
  // editor's data has loaded. Wait for the skeleton to go, bounded by the test timeout (no action timeout
  // is configured) rather than the 5 s assertion budget below: a cold editor under a full parallel suite
  // can take longer than that.
  await page.getByTestId("survey-editor-loading").waitFor({ state: "detached" });

  if (options.mode === "cx") {
    await expect(page).toHaveURL(
      new RegExp(String.raw`/workspaces/[^/]+/surveys/${surveyId}/edit\?.*mode=cx`)
    );
  }

  // A just-created survey the editor refuses renders the 404 page, which would otherwise surface as
  // a bare "Settings not found" timeout. Name it, so the failure points at authorization, not timing.
  const editorReady = page.getByRole("button", {
    name: options.mode === "cx" ? "Save & Close" : "Settings",
    exact: true,
  });
  const notFound = page.getByRole("heading", { name: "Page not found" });
  await expect(editorReady.or(notFound).first()).toBeVisible();
  if (await notFound.isVisible()) {
    throw new Error(`The editor answered 404 for survey ${surveyId}, which was just created by this user`);
  }
};

export const createSurveyFromScratch = async (page: Page, options: { mode?: "cx" } = {}): Promise<string> => {
  const createResponse = waitForSurveyCreateResponse(page);
  const createSurveyButton = page.getByRole("button", { name: "Create survey", exact: true });
  const startFromScratchButton = page.getByText("Start from scratch", { exact: true }).first();

  if (await createSurveyButton.isVisible().catch(() => false)) {
    await createSurveyButton.click();
  } else if (await startFromScratchButton.isVisible().catch(() => false)) {
    await startFromScratchButton.click();

    const createSurveyButtonAppeared = await Promise.race([
      createSurveyButton
        .waitFor({ state: "visible", timeout: 5000 })
        .then(() => true)
        .catch(() => false),
      createResponse.then(() => false),
    ]);

    if (createSurveyButtonAppeared) {
      await createSurveyButton.click();
    }
  } else {
    await page.getByRole("button", { name: "New Survey" }).click();
    await page.getByRole("menuitem", { name: "Start from scratch" }).click();
  }

  const surveyId = await createResponse;
  await waitForSurveyEditor(page, surveyId, options);
  await expect(page.getByRole("main").getByText("What would you like to know?").first()).toBeVisible();

  return surveyId;
};

export const useSelectedTemplate = async (page: Page): Promise<string> => {
  const createResponse = waitForSurveyCreateResponse(page);
  await page.getByRole("button", { name: "Use this template", exact: true }).click();
  const surveyId = await createResponse;
  await waitForSurveyEditor(page, surveyId);

  return surveyId;
};

export const createXMTemplateSurvey = async (page: Page, templateName: RegExp | string): Promise<string> => {
  const createResponse = waitForSurveyCreateResponse(page);
  await page.getByRole("button", { name: templateName, exact: typeof templateName === "string" }).click();
  const surveyId = await createResponse;
  await waitForSurveyEditor(page, surveyId, { mode: "cx" });

  return surveyId;
};

const getMockStorageFileUrl = ({
  appOrigin,
  fileName,
  accessType,
  storageId = "playwright-mock",
  filePathSegments = [],
}: {
  appOrigin: string;
  fileName: string;
  accessType: "public" | "private";
  storageId?: string;
  filePathSegments?: string[];
}): string => {
  if (accessType === "public") {
    const fixture = PLAYWRIGHT_STORAGE_FILE_FIXTURES.get(fileName);

    if (fixture?.publicAssetPath) {
      return new URL(fixture.publicAssetPath, appOrigin).toString();
    }
  }

  return `/storage/${storageId}/${accessType}/${[...filePathSegments, encodeURIComponent(fileName)].join("/")}`;
};

/**
 * Survey builder E2E tests exercise survey authoring and response flows.
 * They are not the right place to depend on browser reachability to a real object-storage sidecar,
 * especially when some CI browsers run remotely. Mock the storage boundary so these tests stay scoped
 * to survey behavior, while real storage compatibility is covered by dedicated smoke/integration checks.
 */
export const mockStorageUploads = async (page: Page): Promise<void> => {
  await page.route("**/api/v1/management/storage", async (route) => {
    if (route.request().method() !== "POST") {
      await route.fallback();
      return;
    }

    const payload = route.request().postDataJSON() as { fileName?: string } | undefined;
    const fileName = payload?.fileName ?? "uploaded-file.bin";
    const appOrigin = new URL(route.request().url()).origin;

    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        data: {
          signedUrl: `${appOrigin}${MOCK_STORAGE_UPLOAD_PATH}/${encodeURIComponent(fileName)}`,
          presignedFields: {
            key: fileName,
          },
          fileUrl: getMockStorageFileUrl({ appOrigin, fileName, accessType: "public" }),
          signingData: null,
          updatedFileName: fileName,
        },
      }),
    });
  });

  await page.route(
    (url) => {
      const pathname = url.pathname;
      const segments = pathname.split("/").filter(Boolean);

      return (
        segments.length === 5 &&
        segments[0] === "api" &&
        segments[1] === "v1" &&
        segments[2] === "client" &&
        segments[4] === "storage"
      );
    },
    async (route) => {
      if (route.request().method() !== "POST") {
        await route.fallback();
        return;
      }

      const payload = route.request().postDataJSON() as
        | { fileName?: string; surveyId?: string; elementId?: string }
        | undefined;
      const fileName = payload?.fileName ?? "uploaded-file.bin";
      const requestUrl = new URL(route.request().url());
      const appOrigin = requestUrl.origin;
      const workspaceId = requestUrl.pathname.split("/").filter(Boolean)[3] ?? "playwright-mock";
      const filePathSegments =
        payload?.surveyId && payload?.elementId
          ? ["surveys", payload.surveyId, "elements", payload.elementId]
          : [];

      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          data: {
            signedUrl: `${appOrigin}${MOCK_STORAGE_UPLOAD_PATH}/${encodeURIComponent(fileName)}`,
            presignedFields: {
              key: fileName,
            },
            fileUrl: getMockStorageFileUrl({
              appOrigin,
              fileName,
              accessType: "private",
              storageId: workspaceId,
              filePathSegments,
            }),
            signingData: null,
            updatedFileName: fileName,
          },
        }),
      });
    }
  );

  await page.route(`**${MOCK_STORAGE_UPLOAD_PATH}/**`, async (route) => {
    if (route.request().method() !== "POST") {
      await route.fallback();
      return;
    }

    await route.fulfill({
      status: 201,
      contentType: "application/xml",
      body: `<?xml version="1.0" encoding="UTF-8"?><PostResponse><Location>${MOCK_STORAGE_UPLOAD_PATH}</Location></PostResponse>`,
    });
  });

  await page.route("**/storage/**", async (route) => {
    if (!["GET", "HEAD"].includes(route.request().method())) {
      await route.fallback();
      return;
    }

    const fileName = decodeURIComponent(route.request().url().split("/").pop() ?? "");
    const fixture = PLAYWRIGHT_STORAGE_FILE_FIXTURES.get(fileName) ?? DEFAULT_MOCK_STORAGE_FILE_FIXTURE;

    await route.fulfill({
      status: 200,
      contentType: fixture.mimeType,
      body: route.request().method() === "HEAD" ? "" : fixture.buffer,
    });
  });
};

export const signUpAndLogin = async (
  page: Page,
  name: string,
  email: string,
  password: string
): Promise<void> => {
  await page.goto("/auth/login");
  await page.getByRole("link", { name: "Create an account" }).click();
  await page.getByRole("button", { name: "Continue with Email" }).click();

  await expect(page.getByPlaceholder("Full Name")).toBeVisible();
  await page.getByPlaceholder("Full Name").fill(name);
  await page.getByPlaceholder("Full Name").press("Tab");

  await expect(page.getByPlaceholder("work@email.com")).toBeVisible();

  await page.getByPlaceholder("work@email.com").click();
  await page.getByPlaceholder("work@email.com").fill(email);
  await page.getByPlaceholder("work@email.com").press("Tab");

  await expect(page.getByPlaceholder("*******")).toBeVisible();

  await page.getByPlaceholder("*******").click();
  await page.getByPlaceholder("*******").fill(password);
  await page.getByRole("button", { name: "Continue with Email" }).click();
  await page.getByText("Login").click();
  await page.getByRole("button", { name: "Log in with Email" }).click();
  await page.getByPlaceholder("work@email.com").fill(email);
  await page.getByPlaceholder("*******").click();
  await page.getByPlaceholder("*******").fill(password);
  await page.getByRole("button", { name: "Log in with Email" }).click();
};

export const login = async (page: Page, email: string, password: string): Promise<void> => {
  await page.goto("/auth/login");

  await expect(page.getByRole("button", { name: "Log in with Email" })).toBeVisible();

  await page.getByRole("button", { name: "Log in with Email" }).click();

  await expect(page.getByPlaceholder("work@email.com")).toBeVisible();

  await page.getByPlaceholder("work@email.com").fill(email);

  await expect(page.getByPlaceholder("*******")).toBeVisible();

  await page.getByPlaceholder("*******").click();
  await page.getByPlaceholder("*******").fill(password);
  await page.getByRole("button", { name: "Log in with Email" }).click();
};

export const apiLogin = async (page: Page, email: string, password: string) => {
  // Better Auth sign-in (replaces the NextAuth csrf + credentials-callback flow). The signed session
  // cookie set on the response is shared with the browser through Playwright's request/context jar.
  return page.context().request.post("/api/auth/sign-in/email", {
    data: { email, password },
  });
};

export const isWorkspaceStorageConfigured = async (page: Page, workspaceId: string): Promise<boolean> => {
  const response = await page.context().request.post("/api/v1/management/storage", {
    data: {
      fileName: "e2e-storage-check.png",
      fileType: "image/png",
      workspaceId,
    },
  });

  return response.ok();
};

export const uploadFileForFileUploadQuestion = async (page: Page) => {
  try {
    const fileInput = page.locator('input[type="file"]');
    const response1 = await fetch("https://formbricks-cdn.s3.eu-central-1.amazonaws.com/puppy-1-small.jpg");
    const response2 = await fetch("https://formbricks-cdn.s3.eu-central-1.amazonaws.com/puppy-2-small.jpg");
    const buffer1 = Buffer.from(await response1.arrayBuffer());
    const buffer2 = Buffer.from(await response2.arrayBuffer());

    await fileInput.setInputFiles([
      {
        name: "puppy-1-small.jpg",
        mimeType: "image/jpeg",
        buffer: buffer1,
      },
      {
        name: "puppy-2-small.jpg",
        mimeType: "image/jpeg",
        buffer: buffer2,
      },
    ]);
  } catch (error) {
    logger.error(error, "Error uploading files");
  }
};

export const waitForPendingFileUploads = async (page: Page): Promise<void> => {
  await expect(page.locator("svg.animate-spin.text-slate-700")).toHaveCount(0, { timeout: 60000 });
  await expect(page.getByText("Some files failed to upload")).toHaveCount(0);
  await expect(page.getByText("No files were uploaded")).toHaveCount(0);
  await expect(page.getByText("Invalid file name, please rename your file and try again")).toHaveCount(0);
};

export const uploadImageChoicesForPictureSelection = async (page: Page) => {
  const fileInput = page.locator('input[type="file"]');
  await fileInput.setInputFiles(PLAYWRIGHT_PICTURE_SELECTION_FILES);

  try {
    await waitForPendingFileUploads(page);
  } catch (error) {
    logger.error(error, "Error waiting for file uploads to finish");
    throw error;
  }
};

export const finishOnboarding = async (page: Page): Promise<void> => {
  await page.waitForURL(/\/organizations\/[^/]+\/workspaces\/new\/survey/);
  await page.getByRole("button", { name: "Start from scratch" }).click();

  await page.waitForURL(/\/workspaces\/[^/]+\/surveys\/[^/]+\/edit(\?.*)mode=cx/);
  await page.getByRole("button", { name: "Save & Close" }).click();

  await page.waitForURL(/\/workspaces\/[^/]+\/surveys\/[^/]+\/summary(\?.*)?$/);
};

export const signupUsingInviteToken = async (page: Page, name: string, email: string, password: string) => {
  await page.getByRole("button", { name: "Continue with Email" }).click();
  await page.getByPlaceholder("Full Name").fill(name);
  await page.getByPlaceholder("Full Name").press("Tab");

  // the email is already filled in the input field
  const inputValue = await page.getByPlaceholder("work@email.com").inputValue();
  expect(inputValue).toEqual(email);
  await page.getByPlaceholder("work@email.com").press("Tab");
  await page.getByPlaceholder("*******").click();
  await page.getByPlaceholder("*******").fill(password);
  await page.waitForTimeout(500);
  await page.getByText("Continue with Email").click();
  await page.getByText("Login").click();
  await page.getByRole("button", { name: "Log in with Email" }).click();
  await page.getByPlaceholder("work@email.com").fill(email);
  await page.getByPlaceholder("*******").click();
  await page.getByPlaceholder("*******").fill(password);
  await page.getByRole("button", { name: "Log in with Email" }).click();
};

/**
 * Wait for the previous interaction to reach the survey state, then for a frame after it.
 *
 * `ElementFormInput` pushes edits upstream through `debounce(handleUpdate, 100)`
 * (apps/web/modules/survey/components/element-form-input/index.tsx), and the editor's add handlers
 * (`handleAddLabel`, `updateChoice`, `addElement`, the "Add description"/"Add “Other”" buttons) each
 * build their payload from the `element`/`survey` prop of the render they were created in. A
 * structural click that lands before that debounce has fired writes a stale array back and silently
 * drops the edit — what the spec-wide `slowMo: 150` was really paying for.
 *
 * Order matters: the sleep clears the 100ms debounce, and the two animation frames then confirm the
 * resulting commit has painted. Frames first would resolve at ~16/32ms — before the debounce had
 * even run — and guarantee nothing. Cost is ~180ms at each of the ~40 structural seams, against
 * 150ms on every one of the spec's 726 actions.
 */
const RENDER_SETTLE_MS = 150;

const flushRender = async (page: Page): Promise<void> => {
  await page.evaluate(async (settleMs) => {
    // Sequential awaits rather than nested callbacks: the callback form stacked six functions deep,
    // and the order it encoded — sleep, then two frames — is what the doc comment above requires.
    const nextFrame = (): Promise<unknown> => new Promise((resolve) => requestAnimationFrame(resolve));

    await new Promise((resolve) => setTimeout(resolve, settleMs));
    await nextFrame();
    await nextFrame();
  }, RENDER_SETTLE_MS);
};

/**
 * Helper function to fill content into a rich text editor (contenteditable div).
 * The rich text editor uses a contenteditable div with class "editor-input" instead of a regular input.
 *
 * @param page - Playwright Page object
 * @param labelText - The label text to find the editor (e.g., "Note*", "Description")
 * @param content - The text content to fill into the editor
 */
export const fillRichTextEditor = async (page: Page, labelText: string, content: string): Promise<void> => {
  // Find the editor by locating the label and then finding the .editor-input within the same form group
  const label = page.locator(`label:has-text("${labelText}")`);
  const editorContainer = label.locator("..").locator("..");
  const editor = editorContainer.locator(".editor-input").first();

  // Waiting for the editor before touching it is what lets this run without a global `slowMo`: the
  // element card mounts its form asynchronously after an element is added, so an unguarded action
  // used to resolve against the outgoing render and fail as a detached node.
  await expect(editor).toBeVisible();
  // `fill` on the contenteditable, not `pressSequentially`. One `insertText` replaces the whole
  // value, where per-key typing raced Lexical's own re-render and truncated the text ("Picture
  // Select Question" landing as "Picture S") unless every keystroke was paced by `slowMo`.
  //
  // Repeated until the value survives a render: Lexical loads the element's stored text after the
  // editor mounts, and a fill that lands before that load is overwritten by it — the editor then
  // still reads "What would you like to know?". The assertion after the settle, not a delay, is what
  // keeps the caller's next action off a mid-render tree.
  await expect(async () => {
    await editor.fill(content);
    await flushRender(page);
    await expect(editor).toHaveText(content, { timeout: 1000 });
  }).toPass({ timeout: 20_000 });
};

/**
 * Fill a plain text translation in the Manage Translations modal.
 * Targets the row by data-testid which includes the translation path.
 */
export const fillModalTranslation = async (page: Page, path: string, text: string): Promise<void> => {
  const row = page.locator(`[data-testid="translation-row-${path}"]`);
  await row.scrollIntoViewIfNeeded();
  const input = row.locator("input");
  await input.fill(text);
};

/**
 * Fill a rich text translation in the Manage Translations modal.
 */
export const fillModalRichTranslation = async (page: Page, path: string, text: string): Promise<void> => {
  const row = page.locator(`[data-testid="translation-row-${path}"]`);
  await row.scrollIntoViewIfNeeded();
  const editor = row.locator(".editor-input").first();
  await expect(editor).toBeVisible();
  await editor.fill(text);
  await expect(editor).toHaveText(text);
};

/** Reveal an element's description field. Structural, so the pending edit is flushed first. */
const addDescription = async (page: Page, options: { exact?: boolean } = {}) => {
  await flushRender(page);
  await page.getByRole("button", { name: "Add description", exact: options.exact ?? false }).click();
  await expect(page.locator('label:has-text("Description")').first()).toBeVisible();
};

/** Append the "Other" choice to a select element. Structural, so flush first. */
const addOtherChoice = async (page: Page) => {
  await flushRender(page);
  await page.getByRole("button", { name: "Add “Other”", exact: true }).click();
  await expect(page.getByPlaceholder("Other", { exact: true })).toBeVisible();
};

/**
 * Add an element to the survey via the editor's "Add Block" collapsible.
 *
 * Every step asserts the state it depends on, which is what replaced the spec-wide `slowMo: 150`:
 * the collapsible animates open and shut (`animate-collapsible-down`/`-up`) while the new element
 * card mounts, so an unguarded "click trigger, click type" pair raced the animation and the React
 * commit, and failed with "element detached from the DOM".
 */
export const addElement = async (page: Page, elementType: string, options: { exact?: boolean } = {}) => {
  const trigger = page.getByTestId("add-element-trigger");

  // The add rebuilds the element list from the current render — let the previous edit commit first.
  await flushRender(page);
  await expect(trigger).toBeVisible();
  await trigger.scrollIntoViewIfNeeded();
  await trigger.click();

  // Radix flips `data-state` on the trigger, so this waits for the panel to be open rather than
  // for a timeout to expire.
  await expect(trigger).toHaveAttribute("data-state", "open");

  // Scoped to the picker panel: the editor renders a card per existing element plus its settings, so
  // an unscoped non-exact name ("Date", "Rating") can match several buttons late in a build and fail
  // strict mode.
  const option = page
    .getByTestId("add-element-picker")
    .getByRole("button", { name: elementType, exact: options.exact ?? false });
  await expect(option).toBeVisible();
  // The picker is a two-column grid that overflows on shorter viewports (e.g. "Matrix").
  await option.scrollIntoViewIfNeeded();

  // The picker closes itself from `handleAddElement`, so a collapsed trigger is the signal that the
  // element was committed and the new card is rendering. A click that lands while the panel is still
  // animating open can be lost, so it is retried until the trigger collapses; the panel closes in the
  // same commit as the add, so a retry can never add the element twice.
  await clickUntil(
    option,
    async () => (await trigger.getAttribute("data-state")) === "closed",
    () => expect(trigger).toHaveAttribute("data-state", "closed")
  );
};

/**
 * The editor's live preview, which renders from the committed survey state.
 *
 * The label inputs keep their own local state, so an input can still show text that the survey no
 * longer holds — exactly what happens when a later edit overwrites an earlier one from a stale
 * array. Asserting against the preview is therefore the only reliable proof that an edit landed.
 */
const surveyPreview = (page: Page): Locator => page.locator("#survey-preview");

/**
 * Fill a list of label inputs until every value is present in the live preview at the same time.
 *
 * `updateChoice`/`updateMatrixLabel` rebuild their whole array from the props of the render they
 * were created in, so two quick edits overwrite each other — filling "Option 2" reverts "Option 1"
 * to "". Re-filling whatever the preview is still missing converges on the intended state without
 * pacing every action, which is what the spec-wide `slowMo: 150` used to do.
 */
const fillLabelsUntilCommitted = async (
  page: Page,
  values: string[],
  fieldFor: (index: number) => Locator
): Promise<void> => {
  const preview = surveyPreview(page);

  await expect(async () => {
    for (const [index, value] of values.entries()) {
      const field = fieldFor(index);
      if ((await field.inputValue()) !== value) {
        await expect(field).toBeEditable();
        await field.fill(value);
        await flushRender(page);
      }
    }

    for (const value of values) {
      await expect(preview.getByText(value, { exact: true }).first()).toBeVisible({ timeout: 2000 });
    }
  }).toPass({ timeout: 60000 });
};

/**
 * Click "Add row"/"Add column" until the matrix has `total` labels.
 *
 * One click per pass, each verified by the count growing by exactly one. Waiting for the *final*
 * count instead would burn the whole timeout on every intermediate pass, and could not keep its
 * promise not to overshoot: if a commit outlasted the wait, the next pass would still read the
 * pre-click count and click again, pushing the list past `total` with no way back.
 */
export const ensureMatrixLabelCount = async (page: Page, type: "row" | "column", total: number) => {
  const labels = page.locator(`input[id^="${type}-"]`);
  const addButton = page.getByRole("button", { name: type === "row" ? "Add row" : "Add column" });

  // One label per iteration, each add retried against its own target count. Driving the loop from
  // the outside is what keeps it honest: a `toPass` that merely "added one" reports success and
  // stops, and a `toPass` waiting for `total` burns its whole budget on every intermediate pass.
  for (let count = await labels.count(); count < total; count++) {
    const target = count + 1;

    await expect(async () => {
      if ((await labels.count()) < target) {
        await flushRender(page);
        await expect(addButton).toBeEnabled();
        await addButton.click();
      }
      await expect(labels).toHaveCount(target, { timeout: 2000 });
    }).toPass({ timeout: 20000 });
  }

  await expect(labels).toHaveCount(total);
};

/** Add every matrix label, then fill them — see fillLabelsUntilCommitted for the ordering reason. */
export const fillMatrixLabels = async (page: Page, type: "row" | "column", values: string[]) => {
  await ensureMatrixLabelCount(page, type, values.length);
  await fillLabelsUntilCommitted(page, values, (index) => page.locator(`#${type}-${index}`));
};

/**
 * Click until the choice list holds `total` inputs, one added per pass.
 *
 * Two different controls, because the forms disagree: the ranking form renders a single "Add option"
 * button (ranking-element-form.tsx), while the multiple-choice forms only offer the per-row
 * "Add choice below" icon (element-option-choice.tsx). Whichever exists is used, so this works for
 * select and ranking elements alike — with the select presets currently matching the fixtures, the
 * select path would otherwise only be exercised the day a fixture grew an option.
 */
export const ensureChoiceCount = async (page: Page, total: number) => {
  // Counting by placeholder, not by `id^="choice-"`: the "Other" and "None of the above" choices
  // share that id prefix, so an id-based count would never match the number of real options.
  const choices = page.locator('input[placeholder^="Option "]');
  const addOption = page.getByRole("button", { name: "Add option" });
  const addChoiceBelow = page.getByRole("button", { name: "Add choice below" });

  // One choice per iteration, each add retried against its own target count — see
  // ensureMatrixLabelCount for why the loop lives outside the retry.
  for (let count = await choices.count(); count < total; count++) {
    const target = count + 1;

    await expect(async () => {
      if ((await choices.count()) < target) {
        await flushRender(page);

        if (await addOption.count()) {
          await expect(addOption).toBeEnabled();
          await addOption.click();
        } else {
          const lastRowAdd = addChoiceBelow.last();
          await expect(lastRowAdd).toBeEnabled();
          await lastRowAdd.click();
        }
      }
      await expect(choices).toHaveCount(target, { timeout: 2000 });
    }).toPass({ timeout: 20000 });
  }

  await expect(choices).toHaveCount(total);
};

/** Add every choice, then fill them — see fillLabelsUntilCommitted for the ordering reason. */
export const fillChoiceOptions = async (page: Page, values: string[]) => {
  await ensureChoiceCount(page, values.length);
  await fillLabelsUntilCommitted(page, values, (index) => page.getByPlaceholder(`Option ${index + 1}`));
};

// Scoped to react-hot-toast's own error class (set in modules/ui/components/toaster-client) rather
// than `role="status"`, which the shared `Alert` also uses — several of those are on screen in the
// editor and would be reported as publish failures.
const errorToastsOf = (page: Page): Locator => page.locator(".formbricks__toast__error");

// The editor button that activates a survey: "Activate", "Schedule survey" once a publish date is set,
// or the CX editor's "Save & Close".
const ACTIVATION_TRIGGERS = {
  activate: "Activate",
  schedule: "Schedule survey",
  saveAndClose: "Save & Close",
} as const;

/**
 * Activates (or schedules) the survey open in the editor.
 *
 * Survey visibility is enforced in the E2E run, so a survey a person creates starts restricted and the
 * editor asks "Who can view this survey in your workspace?" before it goes active. Nothing is
 * preselected there, so this answers "Visible to {workspace}" — the state every spec other than
 * survey-visibility.spec.ts expects, and the one webhooks, integrations and other members need. The
 * dialog is required, not optional: a survey that skips it has not started restricted, which is itself
 * a regression.
 *
 * Returns once the dialog has closed; callers wait for the navigation they expect.
 */
export const activateSurvey = async (
  page: Page,
  { via = "activate" }: { via?: keyof typeof ACTIVATION_TRIGGERS } = {}
) => {
  const trigger = page.getByRole("button", { name: ACTIVATION_TRIGGERS[via], exact: true });
  await expect(trigger).toBeEnabled();
  await trigger.click({ noWaitAfter: true });
  const actionName = via === "schedule" ? "Schedule survey" : "Activate";

  // The editor validates before it opens the dialog and reports a problem only through a toast, so
  // wait for whichever comes first and fail with the editor's own message rather than a locator timeout.
  const dialog = page.getByRole("dialog", { name: "Who can view this survey in your workspace?" });
  const errorToast = errorToastsOf(page).first();
  await expect(dialog.or(errorToast).first()).toBeVisible();
  if (await errorToast.isVisible()) {
    throw new Error(`${actionName} was rejected by the editor: ${(await errorToast.innerText()).trim()}`);
  }

  await dialog.getByRole("radio", { name: /^Visible to / }).check();
  await dialog.getByRole("button", { name: actionName, exact: true }).click({ noWaitAfter: true });
  // The dialog stays open, loading, while the visibility change is saved; it closes as activation starts.
  await expect(dialog).toBeHidden({ timeout: 30_000 });
};

/**
 * Publish the survey being edited and wait for the summary page.
 *
 * The editor validates client-side and reports problems only through a toast that auto-dismisses, so
 * a failed publish otherwise surfaces as an opaque `waitForURL` timeout. This watches for the
 * navigation and collects error toasts alongside it, then fails with the message the editor actually
 * gave — or says plainly that none was shown, which points at a slow publish rather than a rejected
 * one.
 */
export const publishSurvey = async (page: Page): Promise<void> => {
  // Matches the per-test timeout in playwright.config.ts, and the `waitForURL` timeout every call
  // site used before this helper existed. Publishing the 13-element survey is the slowest step in
  // the suite; a shorter budget would turn a slow-but-passing run red.
  const publishTimeoutMs = 120000;
  const summaryUrl = /\/workspaces\/[^/]+\/surveys\/[^/]+\/summary(\?.*)?$/;
  const errorToasts = errorToastsOf(page);

  await activateSurvey(page);

  const navigated = page
    .waitForURL(summaryUrl, { timeout: publishTimeoutMs })
    .then(() => true)
    .catch(() => false);

  const seen = new Set<string>();

  for (;;) {
    // Racing the navigation keeps the toast reads off a destroyed execution context: once the
    // summary page starts loading, `navigated` wins and no further query is issued.
    const settled = await Promise.race([navigated, page.waitForTimeout(250).then(() => null)]);

    if (settled === true) return;
    if (settled === false) break;

    // The publish may still navigate between the race above and this read.
    for (const text of await errorToasts.allInnerTexts().catch(() => [])) {
      const message = text.trim();
      if (message) seen.add(message);
    }
  }

  const reported =
    seen.size > 0
      ? `Editor reported: ${JSON.stringify([...seen])}`
      : "No validation toast was shown, so this is a slow publish rather than a rejected one";

  throw new Error(
    `Publish did not reach the summary page within ${publishTimeoutMs}ms. ${reported} (url: ${page.url()})`
  );
};

export const createSurvey = async (page: Page, params: CreateSurveyParams) => {
  await createSurveyFromScratch(page);

  // Welcome Card
  await expect(page.locator("#welcome-toggle")).toBeVisible();
  await page.getByText("Welcome Card").click();
  await page.locator("#welcome-toggle").check();

  // Use the helper function for rich text editors
  await fillRichTextEditor(page, "Note*", params.welcomeCard.headline);
  await fillRichTextEditor(page, "Welcome message", params.welcomeCard.description);

  await page.getByText("Welcome CardOn").click();

  // Open Text Question
  await page.getByRole("main").getByText("What would you like to know?").click();

  await fillRichTextEditor(page, "Question*", params.openTextQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.openTextQuestion.description);
  await page.getByLabel("Placeholder").fill(params.openTextQuestion.placeholder);

  await page.locator("h3").filter({ hasText: params.openTextQuestion.question }).click();

  // Single Select Question
  await addElement(page, "Single-Select");
  await fillRichTextEditor(page, "Question*", params.singleSelectQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.singleSelectQuestion.description);
  // "Other" is added before the labels are filled: the add rebuilds the choice array and would
  // otherwise wipe whatever had just been typed into Option 1/2.
  await addOtherChoice(page);
  await fillChoiceOptions(page, params.singleSelectQuestion.options);

  // Multi Select Question
  await addElement(page, "Multi-Select", { exact: true });
  await fillRichTextEditor(page, "Question*", params.multiSelectQuestion.question);
  await addDescription(page, { exact: true });
  await fillRichTextEditor(page, "Description", params.multiSelectQuestion.description);
  await fillChoiceOptions(page, params.multiSelectQuestion.options);

  // Rating Question
  await addElement(page, "Rating");
  await fillRichTextEditor(page, "Question*", params.ratingQuestion.question);
  await addDescription(page, { exact: true });
  await fillRichTextEditor(page, "Description", params.ratingQuestion.description);
  await page.getByPlaceholder("Not good").fill(params.ratingQuestion.lowLabel);
  await page.getByPlaceholder("Very satisfied").fill(params.ratingQuestion.highLabel);

  // NPS Question
  await addElement(page, "Net Promoter Score (NPS)");
  await fillRichTextEditor(page, "Question*", params.npsQuestion.question);
  await page.getByLabel("Lower label").fill(params.npsQuestion.lowLabel);
  await page.getByLabel("Upper label").fill(params.npsQuestion.highLabel);

  // CTA Question
  await addElement(page, "Statement (Call to Action)");
  await fillRichTextEditor(page, "Question*", params.ctaQuestion.question);

  // Enable external button and fill URL
  await page.locator("#buttonExternal").check();
  await page.getByRole("textbox", { name: "https://website.com" }).fill("https://example.com");
  await page.getByPlaceholder("Finish").fill(params.ctaQuestion.buttonLabel);

  // Consent Question
  await addElement(page, "Consent");
  await fillRichTextEditor(page, "Question*", params.consentQuestion.question);
  await page.getByPlaceholder("I agree to the terms and").fill(params.consentQuestion.checkboxLabel);

  // Picture Select Question
  await addElement(page, "Picture Selection");
  await fillRichTextEditor(page, "Question*", params.pictureSelectQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.pictureSelectQuestion.description);

  await uploadImageChoicesForPictureSelection(page);
  await page.getByRole("button", { name: "Image alt text, choice 1", exact: true }).click();
  const altTextDialog = page.getByRole("dialog", { name: "Add alt text" });
  await altTextDialog
    .getByLabel("Image alt text, choice 1", { exact: true })
    .fill(params.pictureSelectQuestion.firstChoiceAltText);
  await altTextDialog.getByRole("button", { name: "Done" }).click();
  await expect(altTextDialog).toBeHidden();

  // File Upload Question
  await addElement(page, "File Upload");
  await fillRichTextEditor(page, "Question*", params.fileUploadQuestion.question);

  // Matrix Upload Question
  await addElement(page, "Matrix");
  await fillRichTextEditor(page, "Question*", params.matrix.question);
  await addDescription(page, { exact: true });
  await fillRichTextEditor(page, "Description", params.matrix.description);
  await fillMatrixLabels(page, "row", params.matrix.rows);
  await fillMatrixLabels(page, "column", params.matrix.columns);

  // Fill Address Question
  await addElement(page, "Address");
  await fillRichTextEditor(page, "Question*", params.address.question);
  await page.getByRole("row", { name: "Address Line 2" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "City" }).getByRole("cell").nth(2).click();
  await page.getByRole("row", { name: "State" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "Zip" }).getByRole("cell").nth(2).click();
  await page.getByRole("row", { name: "Country" }).getByRole("switch").nth(1).click();

  // Fill Contact Info Question
  await addElement(page, "Contact Info");
  await fillRichTextEditor(page, "Question*", params.contactInfo.question);
  await page.getByRole("row", { name: "Last Name" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "Email" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "Phone" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "Company" }).getByRole("switch").nth(1).click();

  // Fill Ranking question, with an "Other" option respondents can rank and describe
  await addElement(page, "Ranking");
  await fillRichTextEditor(page, "Question*", params.ranking.question);
  await fillChoiceOptions(page, params.ranking.choices);
  await page.getByRole("button", { name: "Add “Other”" }).click();
};

/**
 * Picks a condition's left operand, filtering the list before clicking it.
 *
 * This is the one combobox in the logic editor that also offers the reserved Embedded Data fields
 * (ENG-1840) on top of every question, variable and hidden field, and that list overflows the 400px
 * `CommandList`. A bare `getByRole("option").click()` then fails with "element is outside of the
 * viewport" however long Playwright scrolls and retries — the click never lands and the test dies on
 * its own timeout rather than on an assertion.
 *
 * Typing first is also what an author does with a list this long: the search box is `autoFocus`ed when
 * the popover opens, and cmdk matches items on their label (`keywords`), so the wanted row ends up at
 * the top. Only the left-operand picker needs this; the operator and action pickers are short and
 * carry no reserved entries.
 */
const selectConditionLeftOperand = async (page: Page, conditionId: string, label: string) => {
  await page.locator(`#${conditionId}`).first().click();

  // The rule editor's field list (ENG-6969 T6) says what it searches.
  const search = page.getByPlaceholder("Search questions and fields", { exact: true });
  await expect(search).toBeVisible();
  await search.fill(label);

  await page.getByRole("option", { name: label }).first().click();
};

const formatVisibleMonth = (date: Date): string =>
  new Intl.DateTimeFormat("en-US", { month: "long", year: "numeric" }).format(date);

/**
 * Clicks a day in the calendar an already-open `DatePicker` popover shows.
 *
 * Navigates by month rather than assuming the target is on screen: picking "yesterday" on the first
 * of a month needs the previous one, which is the kind of two-days-a-month flake that reads as
 * random. The caller opens the popover, because what triggers it differs per surface.
 */
export const pickCalendarDay = async (page: Page, target: Date): Promise<void> => {
  const calendar = page.locator("[data-radix-popper-content-wrapper]").last().locator(".rdp-root");
  const targetMonthLabel = formatVisibleMonth(target);

  for (let attempt = 0; attempt < 12; attempt++) {
    const visibleMonthLabel = (await calendar.locator(".rdp-caption_label").textContent())?.trim();
    if (visibleMonthLabel?.includes(targetMonthLabel)) break;

    const showingLater = visibleMonthLabel ? new Date(`1 ${visibleMonthLabel}`) > target : false;
    await calendar.locator(showingLater ? ".rdp-button_previous" : ".rdp-button_next").click();
  }

  // `:not(.rdp-outside)` matters where the grid pads with the neighbouring months' days: a bare
  // day-number match would otherwise hit the same number in the wrong month.
  await calendar
    .locator(".rdp-day:not(.rdp-outside) .rdp-day_button:not([disabled])")
    .filter({ hasText: new RegExp(`^${target.getDate().toString()}$`) })
    .click();
};

/**
 * Sets the date a logic condition compares against.
 *
 * A date condition's right-hand side is a `DatePicker`, not a text input (ENG-1853) — the editor
 * never renders a raw date input — so the day is chosen from the calendar its trigger opens. The
 * trigger sits beside the combobox carrying the condition's id.
 */
const setConditionDate = async (page: Page, conditionId: string, target: Date): Promise<void> => {
  await page.locator(`#${conditionId}`).locator("..").getByRole("button").first().click();
  await pickCalendarDay(page, target);
};

/**
 * Driving the editor's Embedded Data card (ENG-1851).
 *
 * Shared rather than per-spec: `survey-editor-embedded-fields.spec.ts` exercises the card itself and
 * `survey.spec.ts` only needs two calculated fields on its way to the logic editor, and a second copy
 * of "open the card, open the dialog, pick a source" is exactly the duplication that goes stale when
 * the card changes.
 */

/** The source a field's value comes from, as the dialog's radios label it. */
export type EmbeddedFieldSource = "Passed in" | "Calculated";

/**
 * The radio behind each source label. Clicked by id rather than by its text: the label and the span
 * inside it both read "Calculated", so a text locator is two elements and fails strict mode.
 */
const EMBEDDED_FIELD_SOURCE_IDS: Record<EmbeddedFieldSource, string> = {
  "Passed in": "embedded-field-source-ingested",
  Calculated: "embedded-field-source-computed",
};

/** The kind of value a field holds, as the dialog's Type list labels it. */
export type EmbeddedFieldType = "Text" | "Number" | "True/false" | "Date";

/** The editor's left panel. Scoping to it keeps the live preview's copies of the same text out. */
export const editorPanel = (page: Page): Locator => page.getByRole("main");

/**
 * Opens the Embedded Data card. Only one editor card is open at a time, so this is expressed as
 * "click until its content is on screen": the click is a toggle, and asserting on the content first
 * keeps it idempotent whichever card was open before.
 */
export const openEmbeddedDataCard = async (page: Page): Promise<void> => {
  const content = editorPanel(page).getByTestId("embedded-data-card-content");

  await clickUntilVisible(editorPanel(page).getByTestId("embedded-data-card-trigger"), content);
};

/** One field's row in the card, addressed by the name it renders. */
export const embeddedFieldRow = (page: Page, name: string): Locator =>
  editorPanel(page).getByTestId("embedded-field-row").filter({ hasText: name });

/** The open Add field / edit-field dialog. */
const embeddedFieldDialog = (page: Page): Locator => page.getByRole("dialog");

/**
 * Opens the card's one "Add field" control and switches to the create tab.
 *
 * Two steps because the card follows the Actions flow: one control opens a dialog whose first tab is
 * the workspace library, and declaring a field the survey owns is the second tab.
 */
export const openCreateEmbeddedFieldTab = async (page: Page): Promise<Locator> => {
  await openEmbeddedDataCard(page);
  await editorPanel(page).getByRole("button", { name: "Add field", exact: true }).click();

  const dialog = embeddedFieldDialog(page);
  await expect(dialog).toBeVisible();
  await dialog.getByRole("button", { name: "Create new field", exact: true }).click();
  await expect(dialog.getByTestId("embedded-field-name")).toBeVisible();
  return dialog;
};

/** Fills the dialog that is already open, without submitting it. */
export const fillEmbeddedFieldDialog = async (
  page: Page,
  field: { name?: string; source?: EmbeddedFieldSource; type?: EmbeddedFieldType; defaultValue?: string }
): Promise<void> => {
  const dialog = embeddedFieldDialog(page);

  if (field.name !== undefined) await dialog.getByTestId("embedded-field-name").fill(field.name);
  // Absent when editing: the source and the address a field is stored under are fixed once set.
  if (field.source !== undefined) {
    await dialog.locator(`#${EMBEDDED_FIELD_SOURCE_IDS[field.source]}`).click();
  }
  if (field.type !== undefined) {
    await dialog.getByTestId("embedded-field-type").click();
    await page.getByRole("option", { name: field.type, exact: true }).click();
  }
  if (field.defaultValue !== undefined) {
    await dialog.getByTestId("embedded-field-default").fill(field.defaultValue);
  }
};

/** Declares a field the survey owns, and waits for its row to appear. */
export const addEmbeddedField = async (
  page: Page,
  field: { name: string; source: EmbeddedFieldSource; type?: EmbeddedFieldType; defaultValue?: string }
): Promise<void> => {
  await openCreateEmbeddedFieldTab(page);
  await fillEmbeddedFieldDialog(page, field);
  await embeddedFieldDialog(page).getByRole("button", { name: "Add", exact: true }).click();
  await expect(embeddedFieldRow(page, field.name)).toBeVisible();
};

/** Opens one row's menu and picks an action from it. */
const openEmbeddedFieldAction = async (page: Page, name: string, action: string): Promise<void> => {
  await openEmbeddedDataCard(page);
  await embeddedFieldRow(page, name)
    .getByRole("button", { name: /Open options/ })
    .click();
  await page.getByRole("menuitem", { name: action, exact: true }).click();
};

/** Edits a field through its row menu, and waits for the change to reach the card. */
export const editEmbeddedField = async (
  page: Page,
  name: string,
  patch: { name?: string; type?: EmbeddedFieldType; defaultValue?: string }
): Promise<void> => {
  await openEmbeddedFieldAction(page, name, "Edit");
  await fillEmbeddedFieldDialog(page, patch);
  await embeddedFieldDialog(page).getByRole("button", { name: "Save", exact: true }).click();
  await expect(embeddedFieldRow(page, patch.name ?? name)).toBeVisible();
};

/**
 * Adds a rule to block `blockNumber` (1-based) on the Flow tab, where logic lives since ENG-6929, and
 * waits for its editor: a "Jump to" rule with a condition on the block's first question, as "Add logic"
 * on the block card used to start one. Only the new rule's editor is open, so its ids
 * (`condition-0-0-…`, `action-0-…`) are the ones the steps after it fill in.
 */
export const addFlowRule = async (page: Page, blockNumber: number): Promise<void> => {
  // The Flow tab opens with every block collapsed; a block's Add logic shows once it is open.
  const expand = page.getByRole("button", { name: "Expand", exact: true });
  if (await expand.isVisible()) await expand.click();
  await page
    .locator('[id^="flow-add-logic-"]:not([id="flow-add-logic-start"])')
    .nth(blockNumber - 1)
    .click();
  await page.getByRole("menuitem", { name: "Jump to", exact: true }).click();
  await expect(page.locator("#condition-0-0-conditionValue")).toBeVisible();
};

export const createSurveyWithLogic = async (page: Page, params: CreateSurveyWithLogicParams) => {
  await createSurveyFromScratch(page);

  // Two calculated fields for the logic below to read and write.
  await addEmbeddedField(page, { name: "score", source: "Calculated", type: "Number" });
  await addEmbeddedField(page, { name: "secret", source: "Calculated", type: "Text" });

  // Welcome Card
  await expect(page.locator("#welcome-toggle")).toBeVisible();
  await page.getByText("Welcome Card").click();
  await page.locator("#welcome-toggle").check();

  // Use the helper function for rich text editors
  await fillRichTextEditor(page, "Note*", params.welcomeCard.headline);
  await fillRichTextEditor(page, "Welcome message", params.welcomeCard.description);

  await page.getByText("Welcome CardOn").click();

  // Open Text Question
  await page.getByRole("main").getByText("What would you like to know?").click();

  await fillRichTextEditor(page, "Question*", params.openTextQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.openTextQuestion.description);
  await page.getByLabel("Placeholder").fill(params.openTextQuestion.placeholder);

  await page.locator("h3").filter({ hasText: params.openTextQuestion.question }).click();

  // Single Select Question
  await addElement(page, "Single-Select");
  await fillRichTextEditor(page, "Question*", params.singleSelectQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.singleSelectQuestion.description);
  // "Other" is added before the labels are filled: the add rebuilds the choice array and would
  // otherwise wipe whatever had just been typed into Option 1/2.
  await addOtherChoice(page);
  await fillChoiceOptions(page, params.singleSelectQuestion.options);

  // Multi Select Question
  await addElement(page, "Multi-Select", { exact: true });
  await fillRichTextEditor(page, "Question*", params.multiSelectQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.multiSelectQuestion.description);
  await fillChoiceOptions(page, params.multiSelectQuestion.options);

  // Picture Select Question
  await addElement(page, "Picture Selection");
  await fillRichTextEditor(page, "Question*", params.pictureSelectQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.pictureSelectQuestion.description);
  await uploadImageChoicesForPictureSelection(page);

  // Rating Question
  await addElement(page, "Rating");
  await fillRichTextEditor(page, "Question*", params.ratingQuestion.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.ratingQuestion.description);
  await page.getByPlaceholder("Not good").fill(params.ratingQuestion.lowLabel);
  await page.getByPlaceholder("Very satisfied").fill(params.ratingQuestion.highLabel);

  // NPS Question
  await addElement(page, "Net Promoter Score (NPS)");
  await fillRichTextEditor(page, "Question*", params.npsQuestion.question);
  await page.getByLabel("Lower label").fill(params.npsQuestion.lowLabel);
  await page.getByLabel("Upper label").fill(params.npsQuestion.highLabel);

  // Fill Ranking question
  await addElement(page, "Ranking");
  await fillRichTextEditor(page, "Question*", params.ranking.question);
  await fillChoiceOptions(page, params.ranking.choices);

  // Matrix Question
  await addElement(page, "Matrix");
  await fillRichTextEditor(page, "Question*", params.matrix.question);
  await addDescription(page);
  await fillRichTextEditor(page, "Description", params.matrix.description);
  await fillMatrixLabels(page, "row", params.matrix.rows);
  await fillMatrixLabels(page, "column", params.matrix.columns);

  // CTA Question
  await addElement(page, "Statement (Call to Action)");
  await fillRichTextEditor(page, "Question*", params.ctaQuestion.question);

  // Enable external button and fill URL
  await page.locator("#buttonExternal").check();
  await page.getByRole("textbox", { name: "https://website.com" }).fill("https://example.com");
  await page.getByPlaceholder("Finish").fill(params.ctaQuestion.buttonLabel);

  // Consent Question
  await addElement(page, "Consent");
  await fillRichTextEditor(page, "Question*", params.consentQuestion.question);
  await page.getByPlaceholder("I agree to the terms and").fill(params.consentQuestion.checkboxLabel);

  // File Upload Question
  await addElement(page, "File Upload");
  await fillRichTextEditor(page, "Question*", params.fileUploadQuestion.question);

  // Date Question
  await addElement(page, "Date");
  await fillRichTextEditor(page, "Question*", params.date.question);

  // Cal Question
  await addElement(page, "Schedule a meeting");
  await fillRichTextEditor(page, "Question*", params.cal.question);

  // Fill Address Question
  await addElement(page, "Address");
  await fillRichTextEditor(page, "Question*", params.address.question);
  await page.getByRole("row", { name: "Address Line 2" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "City" }).getByRole("cell").nth(2).click();
  await page.getByRole("row", { name: "State" }).getByRole("switch").nth(1).click();
  await page.getByRole("row", { name: "Zip" }).getByRole("cell").nth(2).click();
  await page.getByRole("row", { name: "Country" }).getByRole("switch").nth(1).click();

  // Adding logic to blocks, on the Flow tab (ENG-6929): one "Add logic" per block, each opening its new rule.
  await page.getByRole("button", { name: "Flow", exact: true }).click();
  // Every Set value below uses the one-step operators, to keep covering one-step calculations.
  // Block 1 (Open Text Question)
  await addFlowRule(page, 1);
  await selectConditionLeftOperand(page, "condition-0-0-conditionValue", params.openTextQuestion.question);
  await page.locator("#condition-0-0-conditionOperator").first().click();
  await page.getByRole("option", { name: "is submitted" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").first().click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").first().click();
  await page.getByRole("option", { name: "Assign", exact: true }).click();
  await page.locator("#action-0-value-input").first().click();
  await page.locator("#action-0-value-input").first().fill("1");
  await page.locator("#actions-0-dropdown").first().click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Require answer" }).click();
  await page.locator("#action-1-target").click();
  await page.getByRole("option", { name: params.singleSelectQuestion.question }).click();
  await page.locator("#actions-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-2-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 2, false);
  await page.locator("#action-2-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-2-operator").click();
  await page.getByRole("option", { name: "Assign", exact: true }).click();
  await page.locator("#action-2-value-input").click();
  await page.locator("#action-2-value-input").fill("This ");

  // Block 2 (Single Select Question)
  await addFlowRule(page, 2);
  await selectConditionLeftOperand(
    page,
    "condition-0-0-conditionValue",
    params.singleSelectQuestion.question
  );
  await page.locator("#condition-0-0-conditionOperator").first().click();
  await page.getByRole("option", { name: "Equals one of" }).click();
  await page.locator("#condition-0-0-conditionMatchValue").first().click();
  await page.getByRole("option", { name: params.singleSelectQuestion.options[0] }).click();
  await page.getByRole("option", { name: params.singleSelectQuestion.options[1] }).click();
  // Escape closes the multi-select list; a click on the page centre can land inside the open list.
  await page.keyboard.press("Escape");
  await page.waitForSelector('[data-testid="dropdown-menu-content"]', { state: "hidden", timeout: 3000 });
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("is ");

  // Block 3 (Multi Select Question)
  await addFlowRule(page, 3);
  await selectConditionLeftOperand(page, "condition-0-0-conditionValue", params.multiSelectQuestion.question);
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: "Includes all of" }).click();
  await page.locator("#condition-0-0-conditionMatchValue").click();
  await page.getByRole("option", { name: params.multiSelectQuestion.options[0] }).click();
  await page.getByRole("option", { name: params.multiSelectQuestion.options[1] }).click();
  await page.getByRole("option", { name: params.multiSelectQuestion.options[2] }).click();
  // Escape closes the multi-select list; a click on the page centre can land inside the open list.
  await page.keyboard.press("Escape");
  await page.waitForSelector('[data-testid="dropdown-menu-content"]', { state: "hidden", timeout: 3000 });
  await page.locator("#condition-0-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await selectConditionLeftOperand(
    page,
    "condition-0-1-conditionValue",
    params.singleSelectQuestion.question
  );
  await page.locator("#condition-0-1-conditionOperator").click();
  await page.getByRole("option", { name: "is submitted" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Require answer" }).click();
  await page.locator("#action-1-target").click();
  await page.getByRole("option", { name: params.pictureSelectQuestion.question }).click();
  await page.locator("#actions-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-2-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 2, false);
  await page.locator("#action-2-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-2-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("a ");

  // Block 4 (Picture Select Question)
  await addFlowRule(page, 4);
  await selectConditionLeftOperand(
    page,
    "condition-0-0-conditionValue",
    params.pictureSelectQuestion.question
  );
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: "is submitted" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("secret ");

  // Block 5 (Rating Question)
  await addFlowRule(page, 5);
  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.ratingQuestion.question }).click();
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: ">=" }).click();
  await page.locator("#condition-0-0-conditionMatchValue").click();
  await page.getByRole("option", { name: "3" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("message ");

  // Block 6 (NPS Question)
  await addFlowRule(page, 6);
  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.npsQuestion.question }).click();
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: ">", exact: true }).click();
  await page.locator("#condition-0-0-conditionMatchValue").click();
  await page.getByRole("option", { name: "2" }).click();
  await page.locator("#condition-0-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-1-conditionValue").click();
  await page.getByRole("option", { name: params.npsQuestion.question }).click();
  await page.locator("#condition-0-1-conditionOperator").click();
  await page.getByRole("option", { name: "<", exact: true }).click();
  await page.locator("#condition-0-1-conditionMatchValue").click();
  await page.getByRole("option", { name: "8" }).click();
  await page.locator("#condition-0-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-2-conditionValue").click();
  await page.getByRole("option", { name: params.ratingQuestion.question }).click();
  await page.locator("#condition-0-2-conditionOperator").click();
  await page.getByRole("option", { name: "=", exact: true }).click();
  await page.locator("#condition-0-2-conditionMatchValue").click();
  await page.getByRole("option", { name: "4" }).click();
  await page.locator("#condition-0-2-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-3-conditionValue").click();
  await page.getByRole("option", { name: params.ratingQuestion.question }).click();
  await page.locator("#condition-0-3-conditionOperator").click();
  await page.getByRole("option", { name: "<=" }).click();
  await page.locator("#condition-0-3-conditionMatchValue").click();
  await page.getByRole("option", { name: "1" }).click();
  await page.locator("#condition-0-3-dropdown").click();
  await page.getByRole("menuitem", { name: "Create group" }).click();
  await page.locator("#condition-1-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();

  // The and/or select sits before a group's second condition (ENG-6969 T6): the nested group's is second.
  await page.getByRole("combobox", { name: "Combine conditions with" }).nth(1).click();
  await page.getByRole("option", { name: "or", exact: true }).click();

  await page.locator("#condition-1-1-conditionValue").click();
  await page
    .getByRole("option")
    // The picker lists a question as "q4 · Picture Select Question": its code, then its headline.
    .filter({ hasText: new RegExp(`(?:^|· )${params.pictureSelectQuestion.question}$`) })
    .click();
  await page.locator("#condition-1-1-conditionOperator").click();
  await page.getByRole("option", { name: "is submitted" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("for ");

  // Block 7 (Ranking Question)
  await addFlowRule(page, 7);
  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.ranking.question }).click();
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: "is skipped" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("e2e ");

  // Block 8 (Matrix Question)
  await addFlowRule(page, 8);
  await page.locator("#condition-0-0-conditionValue").first().click();
  await page.getByTestId("dropdown-menu-content").getByText(params.matrix.question).click();
  // The whole matrix, named like a row since ENG-6934: "Any row (q8 · Matrix Question)".
  await page.getByRole("menuitem", { name: /^Any row \(/ }).click();
  // Click the operator dropdown (currently shows "Is partially submitted")
  await page.getByText("Is partially submitted", { exact: true }).click();
  // Select "Is completely submitted" from the dropdown
  await page.getByText("Is completely submitted", { exact: true }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Append", exact: true }).click();
  await page.getByRole("textbox", { name: "Value" }).click();
  await page.getByRole("textbox", { name: "Value" }).fill("tests");
  await page.locator("#actions-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-2-objective").click();
  await page.getByRole("option", { name: "Require answer" }).click();
  await page.locator("#action-2-target").click();
  await page.getByRole("option", { name: params.ctaQuestion.question }).click();

  // Block 9 (CTA Question)
  await addFlowRule(page, 9);
  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.ctaQuestion.question }).click();
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: "is not clicked" }).click();
  await page.locator("#condition-0-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.getByRole("combobox", { name: "Combine conditions with" }).first().click();
  await page.getByRole("option", { name: "or", exact: true }).click();
  await page.locator("#condition-0-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Create group" }).click();
  await page.locator("#condition-1-0-conditionValue").click();
  await page.getByRole("option", { name: params.ctaQuestion.question }).click();
  await page.locator("#condition-1-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-1-1-conditionValue").click();
  await page.getByRole("option", { name: "secret" }).click();
  await page.locator("#condition-1-1-conditionOperator").click();
  await page.getByRole("option", { name: "contains" }).click();
  await page.getByPlaceholder("Value").click();
  await page.getByPlaceholder("Value").fill("test");
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("1");

  // Block 10 (Consent Question)
  await addFlowRule(page, 10);
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("2");

  // Block 11 (File Upload Question)
  await addFlowRule(page, 11);
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("1");

  // Block 12 (Date Question)
  const today = new Date();
  const yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
  const tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));

  await addFlowRule(page, 12);

  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.date.question }).click();
  await setConditionDate(page, "condition-0-0-conditionMatchValue", today);
  await page.locator("#condition-0-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-1-conditionValue").click();
  await page.getByRole("option", { name: params.date.question }).click();
  await page.locator("#condition-0-1-conditionOperator").click();
  await page.getByRole("option", { name: "does not equal" }).click();
  await setConditionDate(page, "condition-0-1-conditionMatchValue", yesterday);
  await page.locator("#condition-0-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-2-conditionValue").click();
  await page.getByRole("option", { name: params.date.question }).click();
  await page.locator("#condition-0-2-conditionOperator").click();
  await page.getByRole("option", { name: "is before" }).click();
  await setConditionDate(page, "condition-0-2-conditionMatchValue", tomorrow);
  await page.locator("#condition-0-2-dropdown").click();
  await page.getByRole("menuitem", { name: "Add condition below" }).click();
  await page.locator("#condition-0-3-conditionValue").click();
  await page.getByRole("option", { name: params.date.question }).click();
  await page.locator("#condition-0-3-conditionOperator").click();
  await page.getByRole("option", { name: "is after" }).click();
  await setConditionDate(page, "condition-0-3-conditionMatchValue", yesterday);
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("1");

  // Block 13 (Cal Question)
  await addFlowRule(page, 13);
  await page.locator("#condition-0-0-conditionValue").click();
  await page.getByRole("option", { name: params.cal.question }).click();
  await page.locator("#condition-0-0-conditionOperator").click();
  await page.getByRole("option", { name: "is skipped" }).click();
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("1");

  // Block 14 (Address Question)
  await addFlowRule(page, 14);
  await page.locator("#action-0-objective").first().click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 0, false);
  await page.locator("#action-0-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-0-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-0-value-input").click();
  await page.locator("#action-0-value-input").fill("1");
  await page.locator("#actions-0-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-1-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 1, false);
  await page.locator("#action-1-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-1-operator").click();
  await page.getByRole("option", { name: "Add", exact: true }).click();
  await page.locator("#action-1-value-input").click();
  await page.locator("#action-1-value-input").fill("1");
  await page.locator("#actions-1-dropdown").click();
  await page.getByRole("menuitem", { name: "Add action below" }).click();
  await page.locator("#action-2-objective").click();
  await page.getByRole("option", { name: "Set value", exact: true }).click();
  await setExpressionMode(page, 2, false);
  await page.locator("#action-2-variableId").click();
  await page.getByRole("option", { name: "score" }).click();
  await page.locator("#action-2-operator").click();
  await page.getByRole("option", { name: "Multiply", exact: true }).click();
  await page.locator("#action-2-value-input").click();
  await page.locator("#action-2-value-input").fill("2");
};
