import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Dictation follows an empty draft when its project is removed", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("server");
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  await screen.getByRole("searchbox", "Search transcription models").fill("Whisper Base English");
  await screen.getByRole("button", "Download", {exact:true}).tap();
  await screen.getByRole("button", "Use model", {exact:true}).waitFor({timeout:180000});
  await screen.getByRole("button", "Use model", {exact:true}).tap();
  await screen.getByRole("button", "Selected", {exact:true}).waitFor();
  await t3.open();
  await screen.getByRole("button", "New thread in server", {exact:true}).tap();
  await screen.getByText("or start without a project", {exact:true}).waitFor();
  const original = new URL(await browser.url()).pathname;
  await screen.getByRole("button", "Start voice input", {exact:true}).tap();
  await screen.getByRole("button", "Finish voice input", {exact:true}).waitFor();
  // Allow the real speech sample to reach the browser's emulated microphone.
  await new Promise(resolve => setTimeout(resolve, 6000));
  await screen.getByText("or start without a project", {exact:true}).tap();
  await screen.getByRole("heading", "What should we work on?", {exact:true}).waitFor();
  const recording = await browser.evaluate(() => !!document.querySelector('[data-chat-composer-form] button[aria-label="Finish voice input"]'));
  await app.screenshot("recording-after-project-removal");
  const moved = new URL(await browser.url()).pathname;
  await screen.getByRole("button", "Finish voice input", {exact:true}).tap();
  await new Promise(resolve => setTimeout(resolve, 15000));
  await app.screenshot("transcript-after-project-removal");
  const text = await screen.getByRole("textbox").textContent();
  expect({draft: moved, recording, text}, "The moved draft keeps its identity and receives the dictated text").toEqual({draft: original, recording: true, text: expect.stringMatching(/country/i)});
});
