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

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

test("first-room workflow covers create, texture, autosave recovery, and run", 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 page.getByRole("button", { name: "First Person" }).click();
  await expect(page.getByTestId("status-message")).toContainText("Author a Player Start before running");
  await expect(page.getByTestId("status-run-preflight")).toContainText("Blocked");

  await page.getByTestId("outliner-add-button").click();
  await page.getByTestId("add-menu-entities").click();
  await page.getByTestId("add-menu-player-start").click();
  await setViewportCreationPreview(page, "topLeft", { kind: "entity", entityKind: "playerStart", audioAssetId: null }, { x: 0, y: 0, z: 0 });
  await clickViewport(page, "topLeft");
  await page.getByTestId("player-start-position-x").fill("2");
  await page.getByTestId("player-start-position-x").press("Tab");
  await page.getByTestId("player-start-position-z").fill("-2");
  await page.getByTestId("player-start-position-z").press("Tab");
  await page.getByTestId("player-start-yaw").fill("90");
  await page.getByTestId("player-start-yaw").press("Tab");

  await expect(page.getByTestId("status-run-preflight")).toContainText("Ready for First Person");

  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");

  await page.getByTestId("enter-run-mode").click();

  await expect(page.getByTestId("runner-shell")).toBeVisible();
  await expect(page.getByTestId("runner-spawn-state")).toContainText("Player Start");
  await expect(page.getByTestId("runner-player-position")).toContainText("2.00,");
  await expect(page.getByTestId("runner-player-position")).toContainText(", -2.00");

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