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

test("Editing after a matching file search keeps focus in the editor", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Search focus demo", {
    "graphql.config.ts": 'export const config = {\n  schema: "schema.graphql",\n  documents: "src/**/*.graphql",\n  extensions: {\n    schema: "schema",\n    name: "schema",\n  },\n};\n\n\n',
  });
  const thread = await t3.thread({ project, title: "File search focus", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "graphql.config.ts").tap();
  const focusDeep = (selector: string) => browser.evaluate((selector) => new Promise<boolean>((resolve, reject) => {
    const deadline = Date.now() + 20000;
    const find = () => {
      const roots: Array<Document | ShadowRoot> = [document];
      while (roots.length) {
        const root = roots.shift()!;
        const target = root.querySelector<HTMLElement>(selector);
        if (target) { target.focus(); resolve(true); return; }
        for (const element of root.querySelectorAll("*")) if (element.shadowRoot) roots.push(element.shadowRoot);
      }
      if (Date.now() > deadline) { reject(new Error(`Control missing: ${selector}`)); return; }
      setTimeout(find, 100);
    };
    find();
  }), selector);
  await focusDeep('[data-content][contenteditable="true"]');
  await browser.keyboard.press("Control+f");
  await focusDeep('input[data-search]');
  await browser.keyboard.press("Control+a");
  await browser.keyboard.type("schema");
  await app.screenshot("matching-search");
  await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const editor = host.shadowRoot?.querySelector<HTMLElement>("[data-content]");
      if (editor) { editor.click(); editor.focus(); return; }
    }
    throw new Error("Editor missing");
  });
  await browser.keyboard.press("Control+End");
  await browser.keyboard.press("x");
  await app.screenshot("after-first-keystroke");
  await browser.keyboard.press("y");
  await browser.keyboard.press("z");
  await app.screenshot("after-typing-xyz");
  await browser.keyboard.press("Backspace");
  await app.screenshot("after-backspace");
  const state = () => browser.evaluate(() => {
    let active = document.activeElement;
    while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
    for (const host of document.querySelectorAll("*")) {
      const editor = host.shadowRoot?.querySelector("[data-content]");
      if (editor) return { text: editor.textContent ?? "", editorFocused: active === editor };
    }
    return { text: "", editorFocused: false };
  });
  await expect.poll(state).toMatchObject({ editorFocused: true });
  await expect.poll(async () => (await state()).text).toContain("xy");
  await expect.poll(() => browser.evaluate(() => {
    const roots: Array<Document | ShadowRoot> = [document];
    while (roots.length) {
      const root = roots.shift()!;
      const input = root.querySelector<HTMLInputElement>('input[data-search]');
      if (input) return input.value;
      for (const host of root.querySelectorAll("*")) if (host.shadowRoot) roots.push(host.shadowRoot);
    }
    return null;
  })).toBe("schema");
});
