import { expect, test } from "@playwright/test";

import { beginBoxCreation, clickViewport } from "./viewport-test-helpers";

test("user can assign a face material through the UI and keep it through an autosave reload", async ({ page }) => {
  const pageErrors: string[] = [];
  const consoleErrors: string[] = [];

  page.on("pageerror", (error) => {
    pageErrors.push(error.message);
  });

  page.on("console", (message) => {
    if (message.type() === "error") {
      consoleErrors.push(message.text());
    }
  });

  await page.goto("/");
  await page.evaluate((storageKey) => {
    window.localStorage.removeItem(storageKey);
  }, "webeditor3d.scene-document-draft");
  await page.reload();

  await beginBoxCreation(page);
  await clickViewport(page);
  await page.getByTestId("face-button-posZ").click();
  await page.getByTestId("material-button-starter-amber-grid").click();

  await expect(page.getByTestId("selected-face-material-name")).toContainText("Stacked Beige Terracotta Tile");

  await page.waitForTimeout(400);
  await page.reload();

  await page.getByRole("button", { name: /Whitebox Box 1/ }).click();
  await page.getByTestId("face-button-posZ").click();
  await expect(page.getByTestId("selected-face-material-name")).toContainText("Stacked Beige Terracotta Tile");

  expect(pageErrors).toEqual([]);
  expect(consoleErrors).toEqual([]);
});
