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

const source = `import "vite-plus/test/config";
import * as NodePath from "node:path";

import { defineConfig, mergeConfig } from "vite-plus";

// The file reader reads configuration.
// The server reads configuration too.
export default mergeConfig({}, defineConfig({}));
`;

test("Clicking code beside Find places the caret at the clicked character", WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("Find bar demo", { "apps/server/vite.config.ts": source });
    const thread = await t3.thread({ project, title: "Find bar click", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Files F").tap();
    await screen.getByRole("button", "Expand all folders").tap();
    await screen.getByRole("treeitem", "vite.config.ts").tap();
    await screen.getByRole("button", "Maximize panel").tap();
    await screen.getByRole("button", "Hide file explorer").tap();
    await screen.getByRole("button", "Disable word wrap").tap();

    const point = (line: number, word: string, offset: number) => browser.evaluate(({ line, word, offset }) => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector(`[data-content] [data-line="${line}"]`);
        if (!row) continue;
        const wanted = (row.textContent ?? "").indexOf(word) + offset;
        const walker = document.createTreeWalker(row, NodeFilter.SHOW_TEXT);
        let passed = 0;
        while (walker.nextNode()) {
          const node = walker.currentNode;
          const length = node.textContent?.length ?? 0;
          if (wanted <= passed + length) {
            const range = document.createRange();
            range.setStart(node, wanted - passed);
            range.setEnd(node, Math.min(wanted - passed + 1, length));
            const box = range.getBoundingClientRect();
            return { x: box.left + 0.25, y: box.top + box.height / 2 };
          }
          passed += length;
        }
      }
      throw new Error(`No rendered code point on line ${line}`);
    }, { line, word, offset });
    const text = () => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const content = host.shadowRoot?.querySelector("[data-content]");
        if (content) return content.textContent ?? "";
      }
      return "";
    });

    // A genuine click (detail=1) is required: raw mouse.down/up sends detail=0.
    await screen.tapAt(await point(1, "import", 3));
    await browser.keyboard.press("ControlOrMeta+f");
    await screen.getByRole("textbox", "Search").fill("reads");
    await app.screenshot("001-find-open");

    // Control: the same click API must move the caret below the Find overlay.
    await screen.tapAt(await point(4, "mergeConfig", 1));
    await browser.keyboard.type("Q");
    await app.screenshot("002-below-find-control");
    const controlText = await text();
    await browser.keyboard.press("ControlOrMeta+z");
    await screen.getByRole("textbox", "Search").fill("reads");

    await screen.tapAt(await point(2, "from", 2));
    await browser.keyboard.type("Q");
    await app.screenshot("003-click-beside-find-and-type");
    const besideText = await text();
    await expect(controlText).toContain("mQergeConfig");
    await expect(besideText).toContain('frQom "node:path"');
  });
