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

test("Mod+S outside the composer preserves its draft", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Shortcut proof", { "README.md": "# Shortcut proof\nEdit this file.\n" });
  const thread = await t3.thread({ project, title: "Draft survival", messages: ["first"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox", "Message Draft survival");
  await composer.fill("Unsent draft that must survive");
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="README.md"]');
        if (row) { row.click(); return true; }
      }
      return false;
    })).toBe(true);
  // Focus the real shadow-DOM editor, which the scenario locator cannot pierce.
  await expect.poll(() => browser.evaluate(() => {
      for (const host of document.querySelectorAll("diffs-container")) {
        const input = host.shadowRoot?.querySelector<HTMLElement>('[contenteditable="true"]');
        if (input) { input.focus(); return document.activeElement === host; }
      }
      return false;
    })).toBe(true);
  await browser.keyboard.press("End");
  await browser.keyboard.type(" edited");
  await browser.keyboard.press("ControlOrMeta+s");
  await app.screenshot("file-editor-save");
  const fileResult = await browser.evaluate(() => ({
    draft: document.querySelector('[role="textbox"]')?.textContent ?? "",
    stashes: [...document.querySelectorAll("button")].filter(b => /Stashed prompts:/.test(b.getAttribute("aria-label") ?? "")).length,
  }));
  await composer.fill("Second draft typed before searching");
  const search = screen.getByRole("combobox", "Search threads");
  await search.fill("foo");
  await browser.keyboard.press("ControlOrMeta+s");
  await app.screenshot("sidebar-search-save");
  const searchResult = await browser.evaluate(() => ({
    draft: document.querySelector('[role="textbox"]')?.textContent ?? "",
    stashes: [...document.querySelectorAll("button")].filter(b => /Stashed prompts:/.test(b.getAttribute("aria-label") ?? "")).length,
  }));
  await search.fill("");
  await composer.fill("Composer shortcut still stashes");
  await browser.keyboard.press("ControlOrMeta+s");
  await app.screenshot("composer-stash");
  await expect(fileResult).toEqual({ draft: "Unsent draft that must survive", stashes: 0 });
  await expect(searchResult).toEqual({ draft: "Second draft typed before searching", stashes: 0 });
  await expect(screen.getByRole("button", /Stashed prompts: 1/)).toBeVisible();
});
