/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Shift+Tab after saving a citation comment focuses its pencil", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo");
  let thread;
  try {
    thread = await t3.thread({ project, title: "Replay: showcase", model: "showcase", messages: ["Showcase"] });
  } catch (error) {
    if (!String(error).includes("Advertised models: default")) throw error;
    thread = await t3.thread({ project, title: "Replay: showcase", model: "default", messages: ["Showcase"] });
  }
  await t3.open(thread);
  const item = screen.getByText("Reads the manifest first", { exact: false });
  await item.waitFor();
  await item.tap();
  await browser.evaluate(() => {
    const li = [...document.querySelectorAll("li")].find(el => el.textContent?.includes("Reads the manifest first"));
    if (!li) throw new Error("Missing showcase bullet");
    const range = document.createRange();
    range.selectNodeContents(li);
    const selection = window.getSelection();
    selection?.removeAllRanges();
    selection?.addRange(range);
    document.dispatchEvent(new Event("selectionchange"));
    return null;
  });
  await screen.getByRole("button", "Cite selection in composer").tap();
  await screen.getByPlaceholder("Add an optional comment...").pressSequentially("check this");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Shift+Tab");
  await app.screenshot("after-shift-tab");
  await expect(screen.getByRole("button", "Edit citation comment")).toBeFocused();
});
