/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Focused file and thread chips can be deleted while dictation keeps recording", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Chip removal");
  const thread = await t3.thread({project, title: "go", messages: ["first"]});
  await browser.addInitScript(() => {
    // Feed a real MediaStream with a tone instead of requiring physical microphone hardware.
    Object.defineProperty(navigator.mediaDevices, "getUserMedia", { configurable: true, value: async () => {
      const context = new AudioContext();
      const source = context.createOscillator();
      const gain = context.createGain();
      gain.gain.value = 0.05;
      source.frequency.value = 440;
      const sink = context.createMediaStreamDestination();
      source.connect(gain).connect(sink);
      source.start();
      await context.resume();
      return sink.stream;
    }});
  });
  await t3.open(thread);
  await app.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  const card = browser.locator('xpath=//div[contains(@class,"@container/model")][.//span[text()="Moonshine Tiny"]]');
  await card.getByRole("button", "Download", {exact:true}).tap();
  await card.getByRole("button", "Use model", {exact:true}).tap({timeout:180000});
  await card.getByRole("button", "Test model", {exact:true}).waitFor();
  await t3.open(thread);
  // Use a fresh draft, as in the original reproduction.
  await screen.getByRole("button", "New thread", {exact:true}).tap();
  const editor = screen.getByRole("textbox");
  await editor.fill("Check this file ");
  await screen.getByRole("button", "Start voice input", {exact:true}).tap();
  await screen.getByRole("button", "Finish voice input", {exact:true}).waitFor();
  await browser.evaluate(() => {
    const data = new DataTransfer();
    data.items.add(new File(["column,value\n" + "a,1\n".repeat(250)], "data.csv", {type:"text/csv"}));
    const editor = document.querySelector('[role="textbox"]')!;
    editor.dispatchEvent(new ClipboardEvent("paste", {clipboardData:data, bubbles:true, cancelable:true}));
  });
  const file = editor.getByRole("button", "data.csv", {exact:false});
  await file.waitFor();
  await app.screenshot("file-inserted-during-recording");
  await file.focus();
  await browser.keyboard.press("Backspace");
  await browser.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
  await browser.mouse.move(980, 600);
  // Capture both cases before asserting, so a base failure still documents both chips.
  await app.screenshot("file-after-backspace");
  const fileRemoved = await file.count() === 0;
  await screen.getByRole("button", "go", {exact:false}).first().dragTo(editor);
  const chip = editor.getByRole("link", "Thread, go", {exact:true});
  await chip.waitFor();
  await app.screenshot("thread-inserted-during-recording");
  await chip.focus();
  await browser.keyboard.press("Delete");
  await browser.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
  await browser.mouse.move(980, 600);
  await app.screenshot("thread-after-delete");
  const threadRemoved = await chip.count() === 0;
  const recording = await screen.getByRole("button", "Finish voice input", {exact:true}).count() === 1;
  expect({fileRemoved, threadRemoved, recording}).toEqual({fileRemoved:true, threadRemoved:true, recording:true});
});
