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

test("Restored composer drafts preserve Cyrillic underscores and explicit emphasis", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Draft examples");
  const thread = await t3.thread({ project, title: "Filename drafts", messages: ["Ready for filename examples"] });
  await t3.open(thread);
  const editor = screen.getByRole("textbox");
  const cyrillic = "переименуй файл_один и файл_два";
  const read = () => browser.evaluate(() => {
    const editor = document.querySelector('[contenteditable="true"][role="textbox"]');
    return { text: editor?.textContent, html: editor?.innerHTML, emphasis: editor?.querySelector("em")?.textContent ?? null };
  });
  const prompts = () => browser.evaluate(() => {
    const raw = localStorage.getItem("t3code:composer-drafts:v1") ?? "{}";
    const values: string[] = [];
    const visit = (value: unknown) => {
      if (!value || typeof value !== "object") return;
      for (const [key, child] of Object.entries(value)) {
        if (key === "prompt" && typeof child === "string") values.push(child);
        else visit(child);
      }
    };
    visit(JSON.parse(raw));
    return values;
  });
  await editor.tap();
  await browser.keyboard.type(cyrillic);
  await expect.poll(prompts).toContain(cyrillic);
  await app.screenshot("typed-cyrillic");
  await browser.reload();
  await screen.getByText("first fixture turn complete").waitFor({ state: "visible" });
  await editor.tap();
  const restored = await read();
  await app.screenshot("restored-cyrillic");
  await browser.keyboard.press("End");
  await browser.keyboard.type("!");
  const edited = await read();
  await expect.poll(async () => (await prompts()).some((prompt) => prompt.endsWith("!"))).toBe(true);
  const persisted = (await prompts()).find((prompt) => prompt.endsWith("!"));
  await app.screenshot("edited-cyrillic");

  await editor.fill("rename file_one and file_two");
  await expect.poll(prompts).toContain("rename file_one and file_two");
  await browser.reload();
  await screen.getByText("first fixture turn complete").waitFor({ state: "visible" });
  await editor.tap();
  const ascii = await read();
  await app.screenshot("ascii-control");

  await editor.fill("_файл_один.py_");
  await expect.poll(prompts).toContain("_файл_один.py_");
  await browser.reload();
  await screen.getByText("first fixture turn complete").waitFor({ state: "visible" });
  await editor.tap();
  const outer = await read();
  await app.screenshot("explicit-filename-emphasis");

  expect({ restored: restored.text, restoredEmphasis: restored.emphasis, edited: edited.text, persisted, ascii: ascii.text, outer: outer.emphasis }).toEqual({ restored: cyrillic, restoredEmphasis: null, edited: cyrillic + "!", persisted: cyrillic + "!", ascii: "rename file_one and file_two", outer: "файл_один.py" });
});
