import { createId } from "@paralleldrive/cuid2";
import { type Locator, type Page, expect } from "@playwright/test";
import { prisma } from "@formbricks/database";
import { type Prisma } from "@formbricks/database/prisma";
import { type TSurveyBlock } from "@formbricks/types/surveys/blocks";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { surveys } from "@/playwright/utils/mock";
import { test } from "./lib/fixtures";
import * as helper from "./utils/helper";
import {
  createSurvey,
  createSurveyFromScratch,
  createSurveyWithLogic,
  isWorkspaceStorageConfigured,
  uploadImageChoicesForPictureSelection,
} from "./utils/helper";

test.beforeEach(async ({ page }) => {
  await helper.mockStorageUploads(page);
});

// Picture choices are named by position, never by file name (a file name can carry personal data).
const firstPictureChoiceAlt = "Option 1";
const secondPictureChoiceAlt = "Option 2";
// ...unless the creator gave the image alt text (ENG-3417); createAndSubmit sets it on the first choice only.
const creatorPictureChoiceAlt = surveys.createAndSubmit.pictureSelectQuestion.firstChoiceAltText;

const selectPictureChoice = async (pictureSelectQuestion: Locator, choiceAlt: string) => {
  const choiceImage = pictureSelectQuestion.getByRole("img", { name: choiceAlt });
  await expect(choiceImage).toBeVisible();
  await choiceImage.click();
};

// The matrix radio input is visually hidden (sr-only), so it never becomes actionable itself;
// its wrapping <label> is the visible control. Click the label, then assert the radio state.
const checkMatrixRadio = async (page: Page, name: string) => {
  const radio = page.getByRole("radio", { name });
  await radio.locator("..").click();
  await expect(radio).toBeChecked();
};

test.describe("Survey Create & Submit Response without logic", async () => {
  // 5 minutes
  test.setTimeout(1000 * 60 * 5);

  let url: string | null;

  test("Create survey and submit response", async ({ page, users }) => {
    const user = await users.create();
    await user.login();

    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);

    const workspaceId =
      user.workspaceId ??
      (() => {
        throw new Error("Unable to get workspaceId from user fixture");
      })();
    const storageConfigured = await isWorkspaceStorageConfigured(page, workspaceId);
    test.skip(!storageConfigured, "Storage-dependent survey E2E requires configured file storage.");

    await test.step("Create Survey", async () => {
      await createSurvey(page, surveys.createAndSubmit);

      // Save & Publish Survey
      await page.getByRole("button", { name: "Settings", exact: true }).click();

      await page.locator("#howToSendCardTrigger").click();
      await expect(page.locator("#howToSendCardOption-link")).toBeVisible();
      await page.locator("#howToSendCardOption-link").click();

      await page.getByRole("button", { name: "Save as draft", exact: true }).click();
      await expect(page.getByText("Changes saved.")).toBeVisible();

      await helper.publishSurvey(page);
      await page.getByLabel("Copy survey link to clipboard").click();
      url = await page.evaluate("navigator.clipboard.readText()");
    });

    await test.step("Submit Survey Response", async () => {
      await page.goto(url!);
      await page.waitForURL(/\/s\/[A-Za-z0-9]+$/);

      // Welcome Card
      await expect(
        page.locator("#questionCard--1").getByText(surveys.createAndSubmit.welcomeCard.headline)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard--1").getByText(surveys.createAndSubmit.welcomeCard.description)
      ).toBeVisible();
      await page.locator("#questionCard--1").getByRole("button", { name: "Next" }).click();

      // Open Text Question
      await expect(page.getByText(surveys.createAndSubmit.openTextQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.openTextQuestion.description)).toBeVisible();
      await expect(page.getByPlaceholder(surveys.createAndSubmit.openTextQuestion.placeholder)).toBeVisible();
      await page
        .getByPlaceholder(surveys.createAndSubmit.openTextQuestion.placeholder)
        .fill("Open Text answer");
      await page.locator("#questionCard-0").getByRole("button", { name: "Next" }).click();

      // Single Select Question
      await expect(page.getByText(surveys.createAndSubmit.singleSelectQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.singleSelectQuestion.description)).toBeVisible();
      for (let i = 0; i < surveys.createAndSubmit.singleSelectQuestion.options.length; i++) {
        await expect(
          page
            .locator("#questionCard-1 label")
            .filter({ hasText: surveys.createAndSubmit.singleSelectQuestion.options[i] })
        ).toBeVisible();
      }
      await expect(page.getByText("Other")).toBeVisible();
      await expect(page.locator("#questionCard-1").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-1").getByRole("button", { name: "Back" })).toBeVisible();
      await page
        .locator("#questionCard-1 label")
        .filter({ hasText: surveys.createAndSubmit.singleSelectQuestion.options[0] })
        .click();
      await page.locator("#questionCard-1").getByRole("button", { name: "Next" }).click();

      // Multi Select Question
      await expect(page.getByText(surveys.createAndSubmit.multiSelectQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.multiSelectQuestion.description)).toBeVisible();
      for (let i = 0; i < surveys.createAndSubmit.multiSelectQuestion.options.length; i++) {
        await expect(
          page
            .locator("#questionCard-2 label")
            .filter({ hasText: surveys.createAndSubmit.multiSelectQuestion.options[i] })
        ).toBeVisible();
      }
      await expect(page.locator("#questionCard-2").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-2").getByRole("button", { name: "Back" })).toBeVisible();
      for (let i = 0; i < surveys.createAndSubmit.multiSelectQuestion.options.length; i++) {
        await page
          .locator("#questionCard-2 label")
          .filter({ hasText: surveys.createAndSubmit.multiSelectQuestion.options[i] })
          .click();
      }
      await page.locator("#questionCard-2").getByRole("button", { name: "Next" }).click();

      // Rating Question
      await expect(page.getByText(surveys.createAndSubmit.ratingQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.ratingQuestion.description)).toBeVisible();
      await expect(
        page.locator("#questionCard-3").getByText(surveys.createAndSubmit.ratingQuestion.lowLabel)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard-3").getByText(surveys.createAndSubmit.ratingQuestion.highLabel)
      ).toBeVisible();
      // Rating component uses fieldset with labels, not a group with name "Choices"
      expect(await page.locator("#questionCard-3").locator("fieldset label").count()).toBe(5);
      await expect(page.locator("#questionCard-3").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-3").getByRole("button", { name: "Back" })).toBeVisible();
      // Click on the label instead of the radio to avoid SVG intercepting pointer events
      await page.locator("#questionCard-3").locator('label:has(input[value="3"])').click();
      await page.locator("#questionCard-3").getByRole("button", { name: "Next" }).click();

      // NPS Question
      await expect(page.getByText(surveys.createAndSubmit.npsQuestion.question)).toBeVisible();
      await expect(
        page.locator("#questionCard-4").getByText(surveys.createAndSubmit.npsQuestion.lowLabel)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard-4").getByText(surveys.createAndSubmit.npsQuestion.highLabel)
      ).toBeVisible();
      await expect(page.locator("#questionCard-4").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-4").getByRole("button", { name: "Back" })).toBeVisible();

      for (let i = 0; i < 11; i++) {
        await expect(page.locator("#questionCard-4").getByText(`${i}`, { exact: true })).toBeVisible();
      }
      await page.locator("#questionCard-4").getByText("8", { exact: true }).click();
      await page.locator("#questionCard-4").getByRole("button", { name: "Next" }).click();

      // CTA Question
      await expect(page.getByText(surveys.createAndSubmit.ctaQuestion.question)).toBeVisible();
      await expect(
        page.getByRole("button", { name: surveys.createAndSubmit.ctaQuestion.buttonLabel })
      ).toBeVisible();
      await page.locator("#questionCard-5").getByRole("button", { name: "Next" }).click();

      // Consent Question
      await expect(page.getByText(surveys.createAndSubmit.consentQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.consentQuestion.checkboxLabel)).toBeVisible();
      await expect(page.locator("#questionCard-6").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-6").getByRole("button", { name: "Back" })).toBeVisible();
      await page.getByLabel(surveys.createAndSubmit.consentQuestion.checkboxLabel).check();
      await page.locator("#questionCard-6").getByRole("button", { name: "Next" }).click();

      // Picture Select Question
      await expect(page.getByText(surveys.createAndSubmit.pictureSelectQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.pictureSelectQuestion.description)).toBeVisible();
      const pictureSelectQuestion = page.locator("#questionCard-7");
      await expect(pictureSelectQuestion.getByRole("button", { name: "Next" })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("button", { name: "Back" })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("img", { name: creatorPictureChoiceAlt })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("img", { name: secondPictureChoiceAlt })).toBeVisible();
      await selectPictureChoice(pictureSelectQuestion, creatorPictureChoiceAlt);
      await pictureSelectQuestion.getByRole("button", { name: "Next" }).click();

      // File Upload Question
      await expect(page.getByText(surveys.createAndSubmit.fileUploadQuestion.question)).toBeVisible();
      await expect(page.locator("#questionCard-8").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-8").getByRole("button", { name: "Back" })).toBeVisible();
      await expect(page.getByText("Click or drag to upload files")).toBeVisible();

      await page.locator("input[type=file]").setInputFiles({
        name: "file.doc",
        mimeType: "application/msword",
        buffer: Buffer.from("this is test"),
      });

      await page.getByText("Uploading…").waitFor({ state: "hidden" });
      await page.locator("#questionCard-8").getByRole("button", { name: "Next" }).click();

      // Matrix Question
      await expect(page.getByText(surveys.createAndSubmit.matrix.question)).toBeVisible();
      await expect(page.getByText(surveys.createAndSubmit.matrix.description)).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createAndSubmit.matrix.rows[0] })
      ).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createAndSubmit.matrix.rows[1] })
      ).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createAndSubmit.matrix.rows[2] })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", { name: surveys.createAndSubmit.matrix.columns[0], exact: true })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", { name: surveys.createAndSubmit.matrix.columns[1], exact: true })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", { name: surveys.createAndSubmit.matrix.columns[2], exact: true })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", { name: surveys.createAndSubmit.matrix.columns[3], exact: true })
      ).toBeVisible();
      await expect(page.locator("#questionCard-9").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-9").getByRole("button", { name: "Back" })).toBeVisible();
      await checkMatrixRadio(page, "Roses 0");
      await checkMatrixRadio(page, "Trees 0");
      await checkMatrixRadio(page, "Ocean 0");
      await page.locator("#questionCard-9").getByRole("button", { name: "Next" }).click();

      // Address Question
      await expect(page.getByText(surveys.createAndSubmit.address.question)).toBeVisible();
      await expect(page.getByLabel(surveys.createAndSubmit.address.placeholder.addressLine1)).toBeVisible();
      await page.getByLabel(surveys.createAndSubmit.address.placeholder.addressLine1).fill("Address");
      await expect(page.getByLabel(surveys.createAndSubmit.address.placeholder.city)).toBeVisible();
      await page.getByLabel(surveys.createAndSubmit.address.placeholder.city).fill("city");
      await expect(page.getByLabel(surveys.createAndSubmit.address.placeholder.zip)).toBeVisible();
      await page.getByLabel(surveys.createAndSubmit.address.placeholder.zip).fill("12345");
      await page.locator("#questionCard-10").getByRole("button", { name: "Next" }).click();

      // Contact Info Question
      await expect(page.getByText(surveys.createAndSubmit.contactInfo.question)).toBeVisible();
      await expect(page.getByLabel(surveys.createAndSubmit.contactInfo.placeholder)).toBeVisible();
      await page.getByLabel(surveys.createAndSubmit.contactInfo.placeholder).fill("John Doe");
      await page.locator("#questionCard-11").getByRole("button", { name: "Next" }).click();

      // Ranking Question
      await expect(page.getByText(surveys.createAndSubmit.ranking.question)).toBeVisible();
      for (let i = 0; i < surveys.createAndSubmit.ranking.choices.length; i++) {
        await page.getByText(surveys.createAndSubmit.ranking.choices[i]).click();
      }
      // Ranking "Other" opens a required free-text box inside it
      await page.getByRole("button", { name: "Add Other to ranking" }).click();
      const rankingOtherInput = page.getByRole("textbox", { name: "Other" });
      await page.locator("#questionCard-12").getByRole("button", { name: "Finish" }).click();
      await expect(rankingOtherInput).toHaveAttribute("aria-invalid", "true");
      await rankingOtherInput.fill(surveys.createAndSubmit.ranking.otherText);
      await page.locator("#questionCard-12").getByRole("button", { name: "Finish" }).click();
      // loading spinner -> wait for it to disappear
      await page.getByTestId("loading-spinner").waitFor({ state: "hidden" });
    });
  });
});

test.describe("Multi Language Survey Create", async () => {
  // 5 minutes
  test.setTimeout(1000 * 60 * 5);

  test("Create Survey", async ({ browser, page, users }) => {
    const user = await users.create();
    await user.login();

    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);

    const workspaceId =
      user.workspaceId ??
      (() => {
        throw new Error("Unable to get workspaceId from user fixture");
      })();
    const storageConfigured = await isWorkspaceStorageConfigured(page, workspaceId);
    test.skip(!storageConfigured, "Storage-dependent survey E2E requires configured file storage.");

    // Add workspace languages (English + German)
    await page.goto(`/workspaces/${workspaceId}/settings/workspace/languages`);
    await page.waitForURL(/\/workspaces\/[^/]+\/settings\/workspace\/languages/);
    await page.getByRole("button", { name: "Edit languages" }).click();
    await page.getByRole("button", { name: "Add language" }).click();
    await page.getByRole("button", { name: "Select" }).click();
    await page.getByPlaceholder("Search items").click();
    await page.getByPlaceholder("Search items").fill("Eng");
    await page.getByText("English", { exact: true }).click();
    await page.getByRole("button", { name: "Save changes" }).click();
    await page.getByRole("button", { name: "Edit languages" }).click();
    await page.getByRole("button", { name: "Add language" }).click();
    await page.getByRole("button", { name: "Select" }).click();
    await page.getByRole("textbox", { name: "Search items" }).click();
    await page.getByRole("textbox", { name: "Search items" }).fill("German");
    await page.getByText("German", { exact: true }).nth(1).click();
    await page.getByRole("button", { name: "Save changes" }).click();
    await page.waitForTimeout(2000);

    // Create survey and add all questions in English (default language)
    await page.goto(`/workspaces/${workspaceId}/surveys`);
    await createSurveyFromScratch(page);

    // Enable welcome card
    await page.locator("#welcome-toggle").click();

    // Add questions in default language
    await helper.addElement(page, "Single-Select");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.singleSelectQuestion.question);
    await helper.fillChoiceOptions(page, surveys.createAndSubmit.singleSelectQuestion.options);

    await helper.addElement(page, "Multi-Select", { exact: true });
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.multiSelectQuestion.question);
    await helper.fillChoiceOptions(page, surveys.createAndSubmit.multiSelectQuestion.options);

    await helper.addElement(page, "Picture Selection");
    await helper.fillRichTextEditor(
      page,
      "Question*",
      surveys.createAndSubmit.pictureSelectQuestion.question
    );

    await uploadImageChoicesForPictureSelection(page);

    await helper.addElement(page, "Rating");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.ratingQuestion.question);
    await page.getByPlaceholder("Not good").fill(surveys.createAndSubmit.ratingQuestion.lowLabel);
    await page.getByPlaceholder("Very satisfied").fill(surveys.createAndSubmit.ratingQuestion.highLabel);

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

    await helper.addElement(page, "Date");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.dateQuestion.question);

    await helper.addElement(page, "File Upload");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.fileUploadQuestion.question);

    await helper.addElement(page, "Matrix");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.matrix.question);
    await helper.fillMatrixLabels(page, "row", surveys.createAndSubmit.matrix.rows);
    await helper.fillMatrixLabels(page, "column", surveys.createAndSubmit.matrix.columns);

    await helper.addElement(page, "Address");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.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();

    await helper.addElement(page, "Ranking");
    await helper.fillRichTextEditor(page, "Question*", surveys.createAndSubmit.ranking.question);
    await helper.fillChoiceOptions(page, surveys.createAndSubmit.ranking.choices);

    // Navigate to Language tab to enable translations and add German
    await page.getByText("Language").click();
    const translationsToggle = page.locator("#activate-translations-toggle");
    await expect(translationsToggle).toBeVisible();
    const translationsWereEnabled = (await translationsToggle.getAttribute("aria-checked")) === "true";
    if (!translationsWereEnabled) {
      await translationsToggle.click();
      await expect(translationsToggle).toHaveAttribute("aria-checked", "true");
    }

    // Select English as default language if the survey does not already have one.
    const defaultLanguageSelect = page.locator("button", { hasText: "Select Language" });
    if (!translationsWereEnabled || (await defaultLanguageSelect.isVisible())) {
      await defaultLanguageSelect.click();
      await page.getByText("English (en)", { exact: true }).click();
      await page.getByRole("button", { name: "Confirm" }).click();
    }

    // Enable German by toggling its switch in the language table
    await page
      .getByRole("row", { name: /German/ })
      .getByRole("switch")
      .click();

    // Open translation modal for German by clicking the German row
    await page.getByRole("cell", { name: "German" }).click();
    await expect(page.getByRole("dialog")).toBeVisible();

    // Fill translations in the Manage Translations modal
    // Welcome card translations (rich text for headline/subheader, plain for buttonLabel)
    await helper.fillModalRichTranslation(
      page,
      "welcomeCard.headline",
      surveys.germanCreate.welcomeCard.headline
    );
    await helper.fillModalRichTranslation(
      page,
      "welcomeCard.subheader",
      surveys.germanCreate.welcomeCard.description
    );
    await helper.fillModalTranslation(
      page,
      "welcomeCard.buttonLabel",
      surveys.germanCreate.welcomeCard.buttonLabel
    );

    // Block 0 - Open text question
    await helper.fillModalTranslation(page, "blocks.0.buttonLabel", surveys.germanCreate.next);
    await helper.fillModalRichTranslation(
      page,
      "blocks.0.elements.0.headline",
      surveys.germanCreate.openTextQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.0.elements.0.placeholder",
      surveys.germanCreate.openTextQuestion.placeholder
    );

    // Block 1 - Single-select question
    await helper.fillModalRichTranslation(
      page,
      "blocks.1.elements.0.headline",
      surveys.germanCreate.singleSelectQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.1.elements.0.choices.0.label",
      surveys.germanCreate.singleSelectQuestion.options[0]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.1.elements.0.choices.1.label",
      surveys.germanCreate.singleSelectQuestion.options[1]
    );

    // Block 2 - Multi-select question
    await helper.fillModalRichTranslation(
      page,
      "blocks.2.elements.0.headline",
      surveys.germanCreate.multiSelectQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.2.elements.0.choices.0.label",
      surveys.germanCreate.multiSelectQuestion.options[0]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.2.elements.0.choices.1.label",
      surveys.germanCreate.multiSelectQuestion.options[1]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.2.elements.0.choices.2.label",
      surveys.germanCreate.multiSelectQuestion.options[2]
    );

    // Block 3 - Picture selection question
    await helper.fillModalRichTranslation(
      page,
      "blocks.3.elements.0.headline",
      surveys.germanCreate.pictureSelectQuestion.question
    );

    // Block 4 - Rating question
    await helper.fillModalRichTranslation(
      page,
      "blocks.4.elements.0.headline",
      surveys.germanCreate.ratingQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.4.elements.0.lowerLabel",
      surveys.germanCreate.ratingQuestion.lowLabel
    );
    await helper.fillModalTranslation(
      page,
      "blocks.4.elements.0.upperLabel",
      surveys.germanCreate.ratingQuestion.highLabel
    );

    // Block 5 - NPS question
    await helper.fillModalRichTranslation(
      page,
      "blocks.5.elements.0.headline",
      surveys.germanCreate.npsQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.5.elements.0.lowerLabel",
      surveys.germanCreate.npsQuestion.lowLabel
    );
    await helper.fillModalTranslation(
      page,
      "blocks.5.elements.0.upperLabel",
      surveys.germanCreate.npsQuestion.highLabel
    );

    // Block 6 - Date question
    await helper.fillModalRichTranslation(
      page,
      "blocks.6.elements.0.headline",
      surveys.germanCreate.dateQuestion.question
    );

    // Block 7 - File upload question
    await helper.fillModalRichTranslation(
      page,
      "blocks.7.elements.0.headline",
      surveys.germanCreate.fileUploadQuestion.question
    );

    // Block 8 - Matrix question
    await helper.fillModalRichTranslation(
      page,
      "blocks.8.elements.0.headline",
      surveys.germanCreate.matrix.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.rows.0.label",
      surveys.germanCreate.matrix.rows[0]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.rows.1.label",
      surveys.germanCreate.matrix.rows[1]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.rows.2.label",
      surveys.germanCreate.matrix.rows[2]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.columns.0.label",
      surveys.germanCreate.matrix.columns[0]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.columns.1.label",
      surveys.germanCreate.matrix.columns[1]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.columns.2.label",
      surveys.germanCreate.matrix.columns[2]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.8.elements.0.columns.3.label",
      surveys.germanCreate.matrix.columns[3]
    );

    // Block 9 - Address question
    await helper.fillModalRichTranslation(
      page,
      "blocks.9.elements.0.headline",
      surveys.germanCreate.addressQuestion.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.addressLine1.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.addressLine1
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.addressLine2.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.addressLine2
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.city.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.city
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.state.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.state
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.zip.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.zip
    );
    await helper.fillModalTranslation(
      page,
      "blocks.9.elements.0.country.placeholder",
      surveys.germanCreate.addressQuestion.placeholder.country
    );

    // Block 10 - Ranking question
    await helper.fillModalRichTranslation(
      page,
      "blocks.10.elements.0.headline",
      surveys.germanCreate.ranking.question
    );
    await helper.fillModalTranslation(
      page,
      "blocks.10.elements.0.choices.0.label",
      surveys.germanCreate.ranking.choices[0]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.10.elements.0.choices.1.label",
      surveys.germanCreate.ranking.choices[1]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.10.elements.0.choices.2.label",
      surveys.germanCreate.ranking.choices[2]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.10.elements.0.choices.3.label",
      surveys.germanCreate.ranking.choices[3]
    );
    await helper.fillModalTranslation(
      page,
      "blocks.10.elements.0.choices.4.label",
      surveys.germanCreate.ranking.choices[4]
    );

    // Ending card translations
    await helper.fillModalRichTranslation(
      page,
      "endings.0.headline",
      surveys.germanCreate.endingCard.headline
    );
    await helper.fillModalRichTranslation(
      page,
      "endings.0.subheader",
      surveys.germanCreate.endingCard.description
    );
    await helper.fillModalTranslation(
      page,
      "endings.0.buttonLabel",
      surveys.germanCreate.endingCard.buttonLabel
    );

    // Save translations
    await page.getByRole("button", { name: "Save" }).click();

    // Configure as link survey and publish
    await page.getByRole("button", { name: "Settings", exact: true }).click();

    await page.locator("#howToSendCardTrigger").click();
    await expect(page.locator("#howToSendCardOption-link")).toBeVisible();
    await page.locator("#howToSendCardOption-link").click();

    await page.getByRole("button", { name: "Save as draft", exact: true }).click();
    await expect(page.getByText("Changes saved.")).toBeVisible();

    await helper.publishSurvey(page);
    await page.getByLabel("Select Language").click();
    await page.getByText("German").click();
    await page.getByLabel("Copy survey link to clipboard").click();
    const germanSurveyUrl = await page.evaluate("navigator.clipboard.readText()");
    expect(germanSurveyUrl).toContain("lang=de");

    await test.step("Browser language picks the survey language when no ?lang= is given", async () => {
      const surveyUrl = new URL(germanSurveyUrl as string);
      surveyUrl.search = "";
      const surveyId = surveyUrl.pathname.split("/").pop()!;
      const welcomeCard = (respondent: Page) => respondent.locator("#questionCard--1");

      await prisma.survey.update({ where: { id: surveyId }, data: { autoSelectLanguage: true } });
      // The runner's default `locale` ("en-US") overrides an Accept-Language in extraHTTPHeaders, so
      // clear it for the header to reach the server as written.
      const germanBrowser = await browser.newContext({
        locale: undefined,
        extraHTTPHeaders: { "Accept-Language": "de-DE,de;q=0.9,en;q=0.8" },
      });
      try {
        const respondent = await germanBrowser.newPage();
        await respondent.goto(surveyUrl.toString());
        await expect(
          welcomeCard(respondent).getByText(surveys.germanCreate.welcomeCard.headline)
        ).toBeVisible();

        // With the setting off, the same German browser gets the default (English) language —
        // this survey keeps the template's English welcome headline.
        await prisma.survey.update({ where: { id: surveyId }, data: { autoSelectLanguage: false } });
        await respondent.reload();
        await expect(welcomeCard(respondent).getByText("Welcome!", { exact: true })).toBeVisible();
      } finally {
        await germanBrowser.close();
      }
    });
  });
});

test.describe("Testing Survey with advanced logic", async () => {
  // 8 minutes
  test.setTimeout(1000 * 60 * 8);
  let url: string | null;

  test("Create survey and submit response", async ({ page, users }) => {
    const user = await users.create();
    await user.login();

    await page.waitForURL(/\/workspaces\/[^/]+\/surveys/);

    const workspaceId =
      user.workspaceId ??
      (() => {
        throw new Error("Unable to get workspaceId from user fixture");
      })();
    const storageConfigured = await isWorkspaceStorageConfigured(page, workspaceId);
    test.skip(!storageConfigured, "Storage-dependent survey E2E requires configured file storage.");

    await test.step("Create Survey", async () => {
      await createSurveyWithLogic(page, surveys.createWithLogicAndSubmit);

      // Save & Publish Survey
      await page.getByRole("button", { name: "Settings", exact: true }).click();

      await page.locator("#howToSendCardTrigger").click();
      await expect(page.locator("#howToSendCardOption-link")).toBeVisible();
      await page.locator("#howToSendCardOption-link").click();

      await page.getByRole("button", { name: "Save as draft", exact: true }).click();
      await expect(page.getByText("Changes saved.")).toBeVisible();

      await helper.publishSurvey(page);

      // Get URL
      await page.getByLabel("Copy survey link to clipboard").click();
      url = await page.evaluate("navigator.clipboard.readText()");
    });

    await test.step("Submit Survey Response", async () => {
      await page.goto(url!);
      await page.waitForURL(/\/s\/[A-Za-z0-9]+$/);

      // Welcome Card
      await expect(
        page.locator("#questionCard--1").getByText(surveys.createWithLogicAndSubmit.welcomeCard.headline)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard--1").getByText(surveys.createWithLogicAndSubmit.welcomeCard.description)
      ).toBeVisible();
      await page.locator("#questionCard--1").getByRole("button", { name: "Next" }).click();

      // Open Text Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.openTextQuestion.question)).toBeVisible();
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.openTextQuestion.description)
      ).toBeVisible();
      await expect(
        page.getByPlaceholder(surveys.createWithLogicAndSubmit.openTextQuestion.placeholder)
      ).toBeVisible();
      await page
        .getByPlaceholder(surveys.createWithLogicAndSubmit.openTextQuestion.placeholder)
        .fill("Open Text answer");
      await page.locator("#questionCard-0").getByRole("button", { name: "Next" }).click();

      // Single Select Question
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.singleSelectQuestion.question)
      ).toBeVisible();
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.singleSelectQuestion.description)
      ).toBeVisible();
      for (let i = 0; i < surveys.createWithLogicAndSubmit.singleSelectQuestion.options.length; i++) {
        await expect(
          page
            .locator("#questionCard-1 label")
            .filter({ hasText: surveys.createWithLogicAndSubmit.singleSelectQuestion.options[i] })
        ).toBeVisible();
      }
      await expect(page.getByText("Other")).toBeVisible();
      await expect(page.locator("#questionCard-1").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-1").getByRole("button", { name: "Back" })).toBeVisible();
      await page
        .locator("#questionCard-1 label")
        .filter({ hasText: surveys.createWithLogicAndSubmit.singleSelectQuestion.options[0] })
        .click();
      await page.locator("#questionCard-1").getByRole("button", { name: "Next" }).click();

      // Multi Select Question
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.multiSelectQuestion.question)
      ).toBeVisible();
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.multiSelectQuestion.description)
      ).toBeVisible();
      for (let i = 0; i < surveys.createWithLogicAndSubmit.multiSelectQuestion.options.length; i++) {
        await expect(
          page
            .locator("#questionCard-2 label")
            .filter({ hasText: surveys.createWithLogicAndSubmit.multiSelectQuestion.options[i] })
        ).toBeVisible();
      }
      await expect(page.locator("#questionCard-2").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-2").getByRole("button", { name: "Back" })).toBeVisible();
      for (let i = 0; i < surveys.createWithLogicAndSubmit.multiSelectQuestion.options.length; i++) {
        await page
          .locator("#questionCard-2 label")
          .filter({ hasText: surveys.createWithLogicAndSubmit.multiSelectQuestion.options[i] })
          .click();
      }
      await page.locator("#questionCard-2").getByRole("button", { name: "Next" }).click();

      // Picture Select Question
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.pictureSelectQuestion.question)
      ).toBeVisible();
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.pictureSelectQuestion.description)
      ).toBeVisible();
      const pictureSelectQuestion = page.locator("#questionCard-3");
      await expect(pictureSelectQuestion.getByRole("button", { name: "Next" })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("button", { name: "Back" })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("img", { name: firstPictureChoiceAlt })).toBeVisible();
      await expect(pictureSelectQuestion.getByRole("img", { name: secondPictureChoiceAlt })).toBeVisible();
      await selectPictureChoice(pictureSelectQuestion, firstPictureChoiceAlt);
      await pictureSelectQuestion.getByRole("button", { name: "Next" }).click();

      // Rating Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.ratingQuestion.question)).toBeVisible();
      await expect(page.getByText(surveys.createWithLogicAndSubmit.ratingQuestion.description)).toBeVisible();
      await expect(
        page.locator("#questionCard-4").getByText(surveys.createWithLogicAndSubmit.ratingQuestion.lowLabel)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard-4").getByText(surveys.createWithLogicAndSubmit.ratingQuestion.highLabel)
      ).toBeVisible();
      await expect(page.locator("#questionCard-4").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-4").getByRole("button", { name: "Back" })).toBeVisible();
      // Click on the label instead of the radio to avoid SVG intercepting pointer events
      await page.locator("#questionCard-4").locator('label:has(input[value="4"])').click();
      await page.locator("#questionCard-4").getByRole("button", { name: "Next" }).click();

      // NPS Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.npsQuestion.question)).toBeVisible();
      await expect(
        page.locator("#questionCard-5").getByText(surveys.createWithLogicAndSubmit.npsQuestion.lowLabel)
      ).toBeVisible();
      await expect(
        page.locator("#questionCard-5").getByText(surveys.createWithLogicAndSubmit.npsQuestion.highLabel)
      ).toBeVisible();
      await expect(page.locator("#questionCard-5").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-5").getByRole("button", { name: "Back" })).toBeVisible();

      for (let i = 0; i < 11; i++) {
        await expect(page.locator("#questionCard-5").getByText(`${i}`, { exact: true })).toBeVisible();
      }
      await page.locator("#questionCard-5").getByText("5", { exact: true }).click();
      await page.locator("#questionCard-5").getByRole("button", { name: "Next" }).click();

      // Ranking Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.ranking.question)).toBeVisible();
      await page.locator("#questionCard-6").getByRole("button", { name: "Next" }).click();

      // Matrix Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.matrix.question)).toBeVisible();
      await expect(page.getByText(surveys.createWithLogicAndSubmit.matrix.description)).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createWithLogicAndSubmit.matrix.rows[0] })
      ).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createWithLogicAndSubmit.matrix.rows[1] })
      ).toBeVisible();
      await expect(
        page.getByRole("rowheader", { name: surveys.createWithLogicAndSubmit.matrix.rows[2] })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", {
          name: surveys.createWithLogicAndSubmit.matrix.columns[0],
          exact: true,
        })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", {
          name: surveys.createWithLogicAndSubmit.matrix.columns[1],
          exact: true,
        })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", {
          name: surveys.createWithLogicAndSubmit.matrix.columns[2],
          exact: true,
        })
      ).toBeVisible();
      await expect(
        page.getByRole("columnheader", {
          name: surveys.createWithLogicAndSubmit.matrix.columns[3],
          exact: true,
        })
      ).toBeVisible();
      await expect(page.locator("#questionCard-7").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-7").getByRole("button", { name: "Back" })).toBeVisible();
      await checkMatrixRadio(page, "Roses 0");
      await checkMatrixRadio(page, "Trees 0");
      await checkMatrixRadio(page, "Ocean 0");
      await page.locator("#questionCard-7").getByRole("button", { name: "Next" }).click();

      // CTA Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.ctaQuestion.question)).toBeVisible();
      await expect(
        page.getByRole("button", { name: surveys.createWithLogicAndSubmit.ctaQuestion.buttonLabel })
      ).toBeVisible();
      await page
        .getByRole("button", { name: surveys.createWithLogicAndSubmit.ctaQuestion.buttonLabel })
        .click();
      await page.locator("#questionCard-8").getByRole("button", { name: "Next" }).click();

      // Consent Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.consentQuestion.question)).toBeVisible();
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.consentQuestion.checkboxLabel)
      ).toBeVisible();
      await expect(page.locator("#questionCard-9").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-9").getByRole("button", { name: "Back" })).toBeVisible();
      await page.getByLabel(surveys.createWithLogicAndSubmit.consentQuestion.checkboxLabel).check();
      await page.locator("#questionCard-9").getByRole("button", { name: "Next" }).click();

      // File Upload Question
      await expect(
        page.getByText(surveys.createWithLogicAndSubmit.fileUploadQuestion.question)
      ).toBeVisible();
      await expect(page.locator("#questionCard-10").getByRole("button", { name: "Next" })).toBeVisible();
      await expect(page.locator("#questionCard-10").getByRole("button", { name: "Back" })).toBeVisible();

      await expect(page.getByText("Click or drag to upload files")).toBeVisible();

      await page.locator("input[type=file]").setInputFiles({
        name: "file.doc",
        mimeType: "application/msword",
        buffer: Buffer.from("this is test"),
      });
      await page.getByText("Uploading…").waitFor({ state: "hidden" });
      await page.locator("#questionCard-10").getByRole("button", { name: "Next" }).click();

      // Date Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.date.question)).toBeVisible();
      // Click the "Today" button in the date picker - matches format like "Today, Tuesday, December 16th,"
      await page.getByRole("button", { name: /^Today,/ }).click();
      // No "Scroll to bottom" step: the click scrolls Next into view itself. Clicking that button only when
      // `isVisible()` was a check-then-act: it could vanish between the check and the click, which then
      // waited out the whole test timeout.
      await page.locator("#questionCard-11").getByRole("button", { name: "Next", exact: true }).click();

      // Cal Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.cal.question)).toBeVisible();
      await page.locator("#questionCard-12").getByRole("button", { name: "Next" }).click();

      // Address Question
      await expect(page.getByText(surveys.createWithLogicAndSubmit.address.question)).toBeVisible();
      await expect(
        page.getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.addressLine1)
      ).toBeVisible();
      await page
        .getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.addressLine1)
        .fill("Address");
      await expect(page.getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.city)).toBeVisible();
      await page.getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.city).fill("city");
      await expect(page.getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.zip)).toBeVisible();
      await page.getByLabel(surveys.createWithLogicAndSubmit.address.placeholder.zip).fill("12345");
      await page.locator("#questionCard-13").getByRole("button", { name: "Finish" }).click();

      // loading spinner -> wait for it to disappear
      await page.getByTestId("loading-spinner").waitFor({ state: "hidden" });

      // Thank You Card
      await expect(page.getByText(surveys.createWithLogicAndSubmit.endingCard.headline)).toBeVisible();
      await expect(page.getByText(surveys.createWithLogicAndSubmit.endingCard.description)).toBeVisible();
    });

    await test.step("Verify Survey Response", async () => {
      await page.goBack();
      await page.waitForURL(/\/workspaces\/[^/]+\/surveys\/[^/]+\/summary(\?.*)?$/);

      const currentUrl = page.url();
      const updatedUrl = currentUrl.replace(/summary(?:\?.*)?$/, "responses");

      await page.goto(updatedUrl);
      const responseTable = page.getByTestId("response-table").locator("table");
      await expect(responseTable).toBeVisible();
      await expect(responseTable.getByRole("columnheader", { name: /^score$/i })).toBeVisible({
        timeout: 15000,
      });

      // No settle wait here on purpose: the cell assertions below auto-wait, and
      // `waitForLoadState("networkidle")` never resolved on this page — it burned the whole 8 minute
      // test timeout, then a retry, which is what pushed the Playwright step past its 15 minute cap.

      // Look for any cell containing "32" or a score-related value
      const scoreCell = page.getByRole("cell").filter({ hasText: /^32/ });
      await expect(scoreCell).toBeVisible({
        timeout: 15000,
      });

      // Look for the secret message in the table
      const secretCell = page.getByRole("cell").filter({ hasText: /This is a secret message for e2e tests/ });
      await expect(secretCell).toBeVisible({
        timeout: 15000,
      });
    });
  });
});

// One card with two upload questions and a text question. Seeded through Prisma because the editor
// puts each new question on its own card, and the race below needs them on the same one.
const seedOverlappingUploadsSurvey = async (workspaceId: string, userId: string) => {
  const ids = { multiUpload: createId(), singleUpload: createId(), text: createId() };
  const block: TSurveyBlock = {
    id: createId(),
    name: "Block 1",
    elements: [
      {
        id: ids.multiUpload,
        type: TSurveyElementTypeEnum.FileUpload,
        headline: { default: "Upload your photos" },
        required: false,
        allowMultipleFiles: true,
      },
      {
        id: ids.singleUpload,
        type: TSurveyElementTypeEnum.FileUpload,
        headline: { default: "Upload your ticket" },
        required: false,
        allowMultipleFiles: false,
      },
      {
        id: ids.text,
        type: TSurveyElementTypeEnum.OpenText,
        headline: { default: "Anything else?" },
        required: false,
        inputType: "text",
        charLimit: { enabled: false },
      },
    ],
  };
  const endings = [{ id: createId(), type: "endScreen", headline: { default: "Thank you!" } }];

  const survey = await prisma.survey.create({
    data: {
      workspaceId,
      createdBy: userId,
      name: "Overlapping uploads",
      type: "link",
      status: "inProgress",
      blocks: [block] as unknown as Prisma.InputJsonValue[],
      endings: endings as unknown as Prisma.InputJsonValue[],
    },
    select: { id: true },
  });
  return { surveyId: survey.id, ...ids };
};

const pngFile = (name: string) => ({ name, mimeType: "image/png", buffer: Buffer.from(name) });

test.describe("Overlapping file uploads", () => {
  // ENG-3945: an upload that finished after others wrote back the answers from when it started,
  // dropping the files that had landed since and undoing text typed in the meantime.
  test("keeps every answer when uploads on one card finish out of order", async ({ page, users }) => {
    const user = await users.create({ skipSurveySeed: true });
    if (!user.workspaceId) throw new Error("users.create() did not return a workspaceId");
    const { surveyId, multiUpload, singleUpload, text } = await seedOverlappingUploadsSurvey(
      user.workspaceId,
      user.id
    );

    // Holds first.png's upload until the test releases it, so it finishes after the others.
    // Registered after the storage mock in beforeEach, so it runs first and then hands over to it.
    let markFirstUploadHeld = () => {};
    let releaseFirstUpload = () => {};
    const firstUploadHeld = new Promise<void>((resolve) => (markFirstUploadHeld = resolve));
    const firstUploadReleased = new Promise<void>((resolve) => (releaseFirstUpload = resolve));
    await page.route("**/api/v1/client/*/storage", async (route) => {
      const payload = route.request().postDataJSON() as { fileName?: string } | null;
      if (payload?.fileName === "first.png") {
        markFirstUploadHeld();
        await firstUploadReleased;
      }
      await route.fallback();
    });

    const multiUploadQuestion = page.locator(`div[id="${multiUpload}"]`);
    const singleUploadQuestion = page.locator(`div[id="${singleUpload}"]`);
    const textInput = page.getByRole("textbox", { name: "Anything else?" });

    await test.step("start an upload, then answer the rest of the card while it runs", async () => {
      await page.goto(`/s/${surveyId}`);
      await textInput.fill("typed before the uploads");

      await multiUploadQuestion.locator('input[type="file"]').setInputFiles(pngFile("first.png"));
      await firstUploadHeld;

      await singleUploadQuestion.locator('input[type="file"]').setInputFiles(pngFile("second.png"));
      await expect(singleUploadQuestion.getByRole("button", { name: "Delete second.png" })).toBeVisible();
      await multiUploadQuestion.locator('input[type="file"]').setInputFiles(pngFile("third.png"));
      await expect(multiUploadQuestion.getByRole("button", { name: "Delete third.png" })).toBeVisible();

      await textInput.fill("typed during the upload");
    });

    await test.step("the late upload keeps everything answered since it started", async () => {
      releaseFirstUpload();
      await expect(multiUploadQuestion.getByRole("button", { name: "Delete first.png" })).toBeVisible();

      await expect(multiUploadQuestion.getByRole("button", { name: "Delete third.png" })).toBeVisible();
      await expect(singleUploadQuestion.getByRole("button", { name: "Delete second.png" })).toBeVisible();
      await expect(textInput).toHaveValue("typed during the upload");
    });

    await test.step("the saved response has every answer", async () => {
      await page.getByRole("button", { name: "Finish" }).click();
      await expect(page.getByText("Thank you!")).toBeVisible();

      await expect
        .poll(async () => {
          const response = await prisma.response.findFirst({ where: { surveyId }, select: { data: true } });
          return response?.data;
        })
        .toEqual(
          expect.objectContaining({
            [multiUpload]: [expect.stringContaining("third.png"), expect.stringContaining("first.png")],
            [singleUpload]: [expect.stringContaining("second.png")],
            [text]: "typed during the upload",
          })
        );
    });
  });
});
